blob: 47560c8aa334e8a971ac0107ac0d3f5538d4273e [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"
Michael Wright44753b12020-07-08 13:48:11 +010054
Michael Wrightd02c5b62014-02-10 15:10:22 -080055#define INDENT " "
56#define INDENT2 " "
57#define INDENT3 " "
58#define INDENT4 " "
59
Siarhei Vishniakou253f4642022-11-09 13:42:06 -080060using namespace android::ftl::flag_operators;
Siarhei Vishniakou23740b92023-04-21 11:30:20 -070061using android::base::Error;
Peter Collingbourneb04b9b82021-02-08 12:09:47 -080062using android::base::HwTimeoutMultiplier;
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +000063using android::base::Result;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080064using android::base::StringPrintf;
Prabir Pradhan48f8cb92021-08-26 14:05:36 -070065using android::gui::DisplayInfo;
chaviw98318de2021-05-19 16:45:23 -050066using android::gui::FocusRequest;
67using android::gui::TouchOcclusionMode;
68using android::gui::WindowInfo;
69using android::gui::WindowInfoHandle;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -080070using android::os::InputEventInjectionResult;
71using android::os::InputEventInjectionSync;
Ameer Armalycff4fa52023-10-04 23:45:11 +000072namespace input_flags = com::android::input::flags;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080073
Garfield Tane84e6f92019-08-29 17:28:41 -070074namespace android::inputdispatcher {
Michael Wrightd02c5b62014-02-10 15:10:22 -080075
Prabir Pradhancef936d2021-07-21 16:17:52 +000076namespace {
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +000077
78template <class Entry>
79void ensureEventTraced(const Entry& entry) {
80 if (!entry.traceTracker) {
81 LOG(FATAL) << "Expected event entry to be traced, but it wasn't: " << entry;
82 }
83}
84
Prabir Pradhancef936d2021-07-21 16:17:52 +000085// Temporarily releases a held mutex for the lifetime of the instance.
86// Named to match std::scoped_lock
87class scoped_unlock {
88public:
89 explicit scoped_unlock(std::mutex& mutex) : mMutex(mutex) { mMutex.unlock(); }
90 ~scoped_unlock() { mMutex.lock(); }
91
92private:
93 std::mutex& mMutex;
94};
95
Michael Wrightd02c5b62014-02-10 15:10:22 -080096// Default input dispatching timeout if there is no focused application or paused window
97// from which to determine an appropriate dispatching timeout.
Peter Collingbourneb04b9b82021-02-08 12:09:47 -080098const std::chrono::duration DEFAULT_INPUT_DISPATCHING_TIMEOUT = std::chrono::milliseconds(
99 android::os::IInputConstants::UNMULTIPLIED_DEFAULT_DISPATCHING_TIMEOUT_MILLIS *
100 HwTimeoutMultiplier());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800101
Yeabkal Wubshitb8aadfa2024-01-17 17:03:42 -0800102// The default minimum time gap between two user activity poke events.
103const std::chrono::milliseconds DEFAULT_USER_ACTIVITY_POKE_INTERVAL = 100ms;
104
Siarhei Vishniakou289e9242022-02-15 14:50:16 -0800105const std::chrono::duration STALE_EVENT_TIMEOUT = std::chrono::seconds(10) * HwTimeoutMultiplier();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800106
Michael Wrightd02c5b62014-02-10 15:10:22 -0800107// 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 +0000108constexpr nsecs_t SLOW_EVENT_PROCESSING_WARNING_TIMEOUT = 2000 * 1000000LL; // 2sec
109
110// Log a warning when an interception call takes longer than this to process.
111constexpr std::chrono::milliseconds SLOW_INTERCEPTION_THRESHOLD = 50ms;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800112
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700113// Additional key latency in case a connection is still processing some motion events.
114// This will help with the case when a user touched a button that opens a new window,
115// and gives us the chance to dispatch the key to this new window.
116constexpr std::chrono::nanoseconds KEY_WAITING_FOR_EVENTS_TIMEOUT = 500ms;
117
Michael Wrightd02c5b62014-02-10 15:10:22 -0800118// Number of recent events to keep for debugging purposes.
Michael Wright2b3c3302018-03-02 17:19:13 +0000119constexpr size_t RECENT_QUEUE_MAX_SIZE = 10;
120
Antonio Kantekea47acb2021-12-23 12:41:25 -0800121// Event log tags. See EventLogTags.logtags for reference.
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +0000122constexpr int LOGTAG_INPUT_INTERACTION = 62000;
123constexpr int LOGTAG_INPUT_FOCUS = 62001;
Arthur Hungb3307ee2021-10-14 10:57:37 +0000124constexpr int LOGTAG_INPUT_CANCEL = 62003;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +0000125
Prabir Pradhan33e3baa2022-12-06 20:30:22 +0000126const ui::Transform kIdentityTransform;
127
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000128inline nsecs_t now() {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800129 return systemTime(SYSTEM_TIME_MONOTONIC);
130}
131
Siarhei Vishniakou63b63612023-04-12 11:00:23 -0700132inline const std::string binderToString(const sp<IBinder>& binder) {
Bernardo Rufino49d99e42021-01-18 15:16:59 +0000133 if (binder == nullptr) {
134 return "<null>";
135 }
136 return StringPrintf("%p", binder.get());
137}
138
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +0000139static std::string uidString(const gui::Uid& uid) {
140 return uid.toString();
141}
142
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700143Result<void> checkKeyAction(int32_t action) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800144 switch (action) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700145 case AKEY_EVENT_ACTION_DOWN:
146 case AKEY_EVENT_ACTION_UP:
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700147 return {};
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700148 default:
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700149 return Error() << "Key event has invalid action code " << action;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800150 }
151}
152
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700153Result<void> validateKeyEvent(int32_t action) {
154 return checkKeyAction(action);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800155}
156
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700157Result<void> checkMotionAction(int32_t action, int32_t actionButton, int32_t pointerCount) {
Siarhei Vishniakou2f61bdc2022-12-02 08:55:51 -0800158 switch (MotionEvent::getActionMasked(action)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700159 case AMOTION_EVENT_ACTION_DOWN:
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700160 case AMOTION_EVENT_ACTION_UP: {
161 if (pointerCount != 1) {
162 return Error() << "invalid pointer count " << pointerCount;
163 }
164 return {};
165 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700166 case AMOTION_EVENT_ACTION_MOVE:
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700167 case AMOTION_EVENT_ACTION_HOVER_ENTER:
168 case AMOTION_EVENT_ACTION_HOVER_MOVE:
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700169 case AMOTION_EVENT_ACTION_HOVER_EXIT: {
170 if (pointerCount < 1) {
171 return Error() << "invalid pointer count " << pointerCount;
172 }
173 return {};
174 }
Siarhei Vishniakou2f61bdc2022-12-02 08:55:51 -0800175 case AMOTION_EVENT_ACTION_CANCEL:
176 case AMOTION_EVENT_ACTION_OUTSIDE:
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700177 case AMOTION_EVENT_ACTION_SCROLL:
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700178 return {};
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700179 case AMOTION_EVENT_ACTION_POINTER_DOWN:
180 case AMOTION_EVENT_ACTION_POINTER_UP: {
Siarhei Vishniakou2f61bdc2022-12-02 08:55:51 -0800181 const int32_t index = MotionEvent::getActionIndex(action);
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700182 if (index < 0) {
183 return Error() << "invalid index " << index << " for "
184 << MotionEvent::actionToString(action);
185 }
186 if (index >= pointerCount) {
187 return Error() << "invalid index " << index << " for pointerCount " << pointerCount;
188 }
189 if (pointerCount <= 1) {
190 return Error() << "invalid pointer count " << pointerCount << " for "
191 << MotionEvent::actionToString(action);
192 }
193 return {};
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700194 }
195 case AMOTION_EVENT_ACTION_BUTTON_PRESS:
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700196 case AMOTION_EVENT_ACTION_BUTTON_RELEASE: {
197 if (actionButton == 0) {
198 return Error() << "action button should be nonzero for "
199 << MotionEvent::actionToString(action);
200 }
201 return {};
202 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700203 default:
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700204 return Error() << "invalid action " << action;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800205 }
206}
207
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000208int64_t millis(std::chrono::nanoseconds t) {
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -0500209 return std::chrono::duration_cast<std::chrono::milliseconds>(t).count();
210}
211
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700212Result<void> validateMotionEvent(int32_t action, int32_t actionButton, size_t pointerCount,
213 const PointerProperties* pointerProperties) {
214 Result<void> actionCheck = checkMotionAction(action, actionButton, pointerCount);
215 if (!actionCheck.ok()) {
216 return actionCheck;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800217 }
218 if (pointerCount < 1 || pointerCount > MAX_POINTERS) {
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700219 return Error() << "Motion event has invalid pointer count " << pointerCount
220 << "; value must be between 1 and " << MAX_POINTERS << ".";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800221 }
Siarhei Vishniakou8a878352023-01-30 14:05:01 -0800222 std::bitset<MAX_POINTER_ID + 1> pointerIdBits;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800223 for (size_t i = 0; i < pointerCount; i++) {
224 int32_t id = pointerProperties[i].id;
225 if (id < 0 || id > MAX_POINTER_ID) {
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700226 return Error() << "Motion event has invalid pointer id " << id
227 << "; value must be between 0 and " << MAX_POINTER_ID;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800228 }
Siarhei Vishniakou8a878352023-01-30 14:05:01 -0800229 if (pointerIdBits.test(id)) {
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700230 return Error() << "Motion event has duplicate pointer id " << id;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800231 }
Siarhei Vishniakou8a878352023-01-30 14:05:01 -0800232 pointerIdBits.set(id);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800233 }
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700234 return {};
235}
236
237Result<void> validateInputEvent(const InputEvent& event) {
238 switch (event.getType()) {
239 case InputEventType::KEY: {
240 const KeyEvent& key = static_cast<const KeyEvent&>(event);
241 const int32_t action = key.getAction();
242 return validateKeyEvent(action);
243 }
244 case InputEventType::MOTION: {
245 const MotionEvent& motion = static_cast<const MotionEvent&>(event);
246 const int32_t action = motion.getAction();
247 const size_t pointerCount = motion.getPointerCount();
248 const PointerProperties* pointerProperties = motion.getPointerProperties();
249 const int32_t actionButton = motion.getActionButton();
250 return validateMotionEvent(action, actionButton, pointerCount, pointerProperties);
251 }
252 default: {
253 return {};
254 }
255 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800256}
257
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -0800258std::bitset<MAX_POINTER_ID + 1> getPointerIds(const std::vector<PointerProperties>& pointers) {
259 std::bitset<MAX_POINTER_ID + 1> pointerIds;
260 for (const PointerProperties& pointer : pointers) {
261 pointerIds.set(pointer.id);
262 }
263 return pointerIds;
264}
265
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000266std::string dumpRegion(const Region& region) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800267 if (region.isEmpty()) {
Bernardo Rufino53fc31e2020-11-03 11:01:07 +0000268 return "<empty>";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800269 }
270
Bernardo Rufino53fc31e2020-11-03 11:01:07 +0000271 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800272 bool first = true;
273 Region::const_iterator cur = region.begin();
274 Region::const_iterator const tail = region.end();
275 while (cur != tail) {
276 if (first) {
277 first = false;
278 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800279 dump += "|";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800280 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800281 dump += StringPrintf("[%d,%d][%d,%d]", cur->left, cur->top, cur->right, cur->bottom);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800282 cur++;
283 }
Bernardo Rufino53fc31e2020-11-03 11:01:07 +0000284 return dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800285}
286
Prabir Pradhan8c90d782023-09-15 21:16:44 +0000287std::string dumpQueue(const std::deque<std::unique_ptr<DispatchEntry>>& queue,
288 nsecs_t currentTime) {
Siarhei Vishniakou14411c92020-09-18 21:15:05 -0500289 constexpr size_t maxEntries = 50; // max events to print
290 constexpr size_t skipBegin = maxEntries / 2;
291 const size_t skipEnd = queue.size() - maxEntries / 2;
292 // skip from maxEntries / 2 ... size() - maxEntries/2
293 // only print from 0 .. skipBegin and then from skipEnd .. size()
294
295 std::string dump;
296 for (size_t i = 0; i < queue.size(); i++) {
297 const DispatchEntry& entry = *queue[i];
298 if (i >= skipBegin && i < skipEnd) {
299 dump += StringPrintf(INDENT4 "<skipped %zu entries>\n", skipEnd - skipBegin);
300 i = skipEnd - 1; // it will be incremented to "skipEnd" by 'continue'
301 continue;
302 }
303 dump.append(INDENT4);
304 dump += entry.eventEntry->getDescription();
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +0000305 dump += StringPrintf(", seq=%" PRIu32 ", targetFlags=%s, age=%" PRId64 "ms", entry.seq,
306 entry.targetFlags.string().c_str(),
Siarhei Vishniakou14411c92020-09-18 21:15:05 -0500307 ns2ms(currentTime - entry.eventEntry->eventTime));
308 if (entry.deliveryTime != 0) {
309 // This entry was delivered, so add information on how long we've been waiting
310 dump += StringPrintf(", wait=%" PRId64 "ms", ns2ms(currentTime - entry.deliveryTime));
311 }
312 dump.append("\n");
313 }
314 return dump;
315}
316
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -0700317/**
318 * Find the entry in std::unordered_map by key, and return it.
319 * If the entry is not found, return a default constructed entry.
320 *
321 * Useful when the entries are vectors, since an empty vector will be returned
322 * if the entry is not found.
323 * Also useful when the entries are sp<>. If an entry is not found, nullptr is returned.
324 */
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700325template <typename K, typename V>
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000326V getValueByKey(const std::unordered_map<K, V>& map, K key) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -0700327 auto it = map.find(key);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700328 return it != map.end() ? it->second : V{};
Tiger Huang721e26f2018-07-24 22:26:19 +0800329}
330
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000331bool haveSameToken(const sp<WindowInfoHandle>& first, const sp<WindowInfoHandle>& second) {
chaviwaf87b3e2019-10-01 16:59:28 -0700332 if (first == second) {
333 return true;
334 }
335
336 if (first == nullptr || second == nullptr) {
337 return false;
338 }
339
340 return first->getToken() == second->getToken();
341}
342
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000343bool haveSameApplicationToken(const WindowInfo* first, const WindowInfo* second) {
Bernardo Rufino1ff9d592021-01-18 16:58:57 +0000344 if (first == nullptr || second == nullptr) {
345 return false;
346 }
347 return first->applicationInfo.token != nullptr &&
348 first->applicationInfo.token == second->applicationInfo.token;
349}
350
Siarhei Vishniakou8a878352023-01-30 14:05:01 -0800351template <typename T>
352size_t firstMarkedBit(T set) {
353 // TODO: replace with std::countr_zero from <bit> when that's available
354 LOG_ALWAYS_FATAL_IF(set.none());
355 size_t i = 0;
356 while (!set.test(i)) {
357 i++;
358 }
359 return i;
360}
361
Siarhei Vishniakou253f4642022-11-09 13:42:06 -0800362std::unique_ptr<DispatchEntry> createDispatchEntry(
Prabir Pradhan24047542023-11-02 17:14:59 +0000363 const InputTarget& inputTarget, std::shared_ptr<const EventEntry> eventEntry,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -0800364 ftl::Flags<InputTarget::Flags> inputTargetFlags) {
chaviw1ff3d1e2020-07-01 15:53:47 -0700365 if (inputTarget.useDefaultPointerTransform()) {
366 const ui::Transform& transform = inputTarget.getDefaultPointerTransform();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700367 return std::make_unique<DispatchEntry>(eventEntry, inputTargetFlags, transform,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700368 inputTarget.displayTransform,
369 inputTarget.globalScaleFactor);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000370 }
371
372 ALOG_ASSERT(eventEntry->type == EventEntry::Type::MOTION);
373 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(*eventEntry);
374
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700375 std::vector<PointerCoords> pointerCoords;
Siarhei Vishniakouedd61202023-10-18 11:22:40 -0700376 pointerCoords.resize(motionEntry.getPointerCount());
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000377
378 // Use the first pointer information to normalize all other pointers. This could be any pointer
379 // as long as all other pointers are normalized to the same value and the final DispatchEntry
chaviw1ff3d1e2020-07-01 15:53:47 -0700380 // uses the transform for the normalized pointer.
381 const ui::Transform& firstPointerTransform =
Siarhei Vishniakou8a878352023-01-30 14:05:01 -0800382 inputTarget.pointerTransforms[firstMarkedBit(inputTarget.pointerIds)];
chaviw1ff3d1e2020-07-01 15:53:47 -0700383 ui::Transform inverseFirstTransform = firstPointerTransform.inverse();
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000384
385 // Iterate through all pointers in the event to normalize against the first.
Siarhei Vishniakouedd61202023-10-18 11:22:40 -0700386 for (uint32_t pointerIndex = 0; pointerIndex < motionEntry.getPointerCount(); pointerIndex++) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000387 const PointerProperties& pointerProperties = motionEntry.pointerProperties[pointerIndex];
388 uint32_t pointerId = uint32_t(pointerProperties.id);
chaviw1ff3d1e2020-07-01 15:53:47 -0700389 const ui::Transform& currTransform = inputTarget.pointerTransforms[pointerId];
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000390
391 pointerCoords[pointerIndex].copyFrom(motionEntry.pointerCoords[pointerIndex]);
chaviw1ff3d1e2020-07-01 15:53:47 -0700392 // First, apply the current pointer's transform to update the coordinates into
393 // window space.
394 pointerCoords[pointerIndex].transform(currTransform);
395 // Next, apply the inverse transform of the normalized coordinates so the
396 // current coordinates are transformed into the normalized coordinate space.
397 pointerCoords[pointerIndex].transform(inverseFirstTransform);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000398 }
399
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700400 std::unique_ptr<MotionEntry> combinedMotionEntry =
Prabir Pradhana8cdbe12023-11-01 21:30:02 +0000401 std::make_unique<MotionEntry>(motionEntry.id, motionEntry.injectionState,
402 motionEntry.eventTime, motionEntry.deviceId,
403 motionEntry.source, motionEntry.displayId,
404 motionEntry.policyFlags, motionEntry.action,
405 motionEntry.actionButton, motionEntry.flags,
406 motionEntry.metaState, motionEntry.buttonState,
407 motionEntry.classification, motionEntry.edgeFlags,
408 motionEntry.xPrecision, motionEntry.yPrecision,
409 motionEntry.xCursorPosition, motionEntry.yCursorPosition,
410 motionEntry.downTime, motionEntry.pointerProperties,
411 pointerCoords);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000412
413 std::unique_ptr<DispatchEntry> dispatchEntry =
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700414 std::make_unique<DispatchEntry>(std::move(combinedMotionEntry), inputTargetFlags,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700415 firstPointerTransform, inputTarget.displayTransform,
416 inputTarget.globalScaleFactor);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000417 return dispatchEntry;
418}
419
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000420status_t openInputChannelPair(const std::string& name, std::shared_ptr<InputChannel>& serverChannel,
421 std::unique_ptr<InputChannel>& clientChannel) {
Garfield Tan15601662020-09-22 15:32:38 -0700422 std::unique_ptr<InputChannel> uniqueServerChannel;
423 status_t result = InputChannel::openInputChannelPair(name, uniqueServerChannel, clientChannel);
424
425 serverChannel = std::move(uniqueServerChannel);
426 return result;
427}
428
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -0500429template <typename T>
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000430bool sharedPointersEqual(const std::shared_ptr<T>& lhs, const std::shared_ptr<T>& rhs) {
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -0500431 if (lhs == nullptr && rhs == nullptr) {
432 return true;
433 }
434 if (lhs == nullptr || rhs == nullptr) {
435 return false;
436 }
437 return *lhs == *rhs;
438}
439
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000440KeyEvent createKeyEvent(const KeyEntry& entry) {
Siarhei Vishniakou2e2ea992020-12-15 02:57:19 +0000441 KeyEvent event;
442 event.initialize(entry.id, entry.deviceId, entry.source, entry.displayId, INVALID_HMAC,
443 entry.action, entry.flags, entry.keyCode, entry.scanCode, entry.metaState,
444 entry.repeatCount, entry.downTime, entry.eventTime);
445 return event;
446}
447
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000448bool shouldReportMetricsForConnection(const Connection& connection) {
Siarhei Vishniakouf2652122021-03-05 21:39:46 +0000449 // Do not keep track of gesture monitors. They receive every event and would disproportionately
450 // affect the statistics.
451 if (connection.monitor) {
452 return false;
453 }
454 // If the connection is experiencing ANR, let's skip it. We have separate ANR metrics
455 if (!connection.responsive) {
456 return false;
457 }
458 return true;
459}
460
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000461bool shouldReportFinishedEvent(const DispatchEntry& dispatchEntry, const Connection& connection) {
Siarhei Vishniakouf2652122021-03-05 21:39:46 +0000462 const EventEntry& eventEntry = *dispatchEntry.eventEntry;
463 const int32_t& inputEventId = eventEntry.id;
Siarhei Vishniakouf2652122021-03-05 21:39:46 +0000464 if (inputEventId == android::os::IInputConstants::INVALID_INPUT_EVENT_ID) {
465 return false;
466 }
467 // Only track latency for events that originated from hardware
468 if (eventEntry.isSynthesized()) {
469 return false;
470 }
471 const EventEntry::Type& inputEventEntryType = eventEntry.type;
472 if (inputEventEntryType == EventEntry::Type::KEY) {
473 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
474 if (keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) {
475 return false;
476 }
477 } else if (inputEventEntryType == EventEntry::Type::MOTION) {
478 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
479 if (motionEntry.action == AMOTION_EVENT_ACTION_CANCEL ||
480 motionEntry.action == AMOTION_EVENT_ACTION_HOVER_EXIT) {
481 return false;
482 }
483 } else {
484 // Not a key or a motion
485 return false;
486 }
487 if (!shouldReportMetricsForConnection(connection)) {
488 return false;
489 }
490 return true;
491}
492
Prabir Pradhancef936d2021-07-21 16:17:52 +0000493/**
494 * Connection is responsive if it has no events in the waitQueue that are older than the
495 * current time.
496 */
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000497bool isConnectionResponsive(const Connection& connection) {
Prabir Pradhancef936d2021-07-21 16:17:52 +0000498 const nsecs_t currentTime = now();
Prabir Pradhan8c90d782023-09-15 21:16:44 +0000499 for (const auto& dispatchEntry : connection.waitQueue) {
500 if (dispatchEntry->timeoutTime < currentTime) {
Prabir Pradhancef936d2021-07-21 16:17:52 +0000501 return false;
502 }
503 }
504 return true;
505}
506
Antonio Kantekf16f2832021-09-28 04:39:20 +0000507// Returns true if the event type passed as argument represents a user activity.
508bool isUserActivityEvent(const EventEntry& eventEntry) {
509 switch (eventEntry.type) {
Josep del Riob3981622023-04-18 15:49:45 +0000510 case EventEntry::Type::CONFIGURATION_CHANGED:
511 case EventEntry::Type::DEVICE_RESET:
512 case EventEntry::Type::DRAG:
Antonio Kantekf16f2832021-09-28 04:39:20 +0000513 case EventEntry::Type::FOCUS:
514 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
Antonio Kantekf16f2832021-09-28 04:39:20 +0000515 case EventEntry::Type::SENSOR:
Josep del Riob3981622023-04-18 15:49:45 +0000516 case EventEntry::Type::TOUCH_MODE_CHANGED:
Antonio Kantekf16f2832021-09-28 04:39:20 +0000517 return false;
Antonio Kantekf16f2832021-09-28 04:39:20 +0000518 case EventEntry::Type::KEY:
519 case EventEntry::Type::MOTION:
520 return true;
521 }
522}
523
Prabir Pradhan3f90d312021-11-19 03:57:24 -0800524// Returns true if the given window can accept pointer events at the given display location.
Prabir Pradhan82e081e2022-12-06 09:50:09 +0000525bool windowAcceptsTouchAt(const WindowInfo& windowInfo, int32_t displayId, float x, float y,
Prabir Pradhan33e3baa2022-12-06 20:30:22 +0000526 bool isStylus, const ui::Transform& displayTransform) {
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -0800527 const auto inputConfig = windowInfo.inputConfig;
528 if (windowInfo.displayId != displayId ||
529 inputConfig.test(WindowInfo::InputConfig::NOT_VISIBLE)) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -0800530 return false;
531 }
Prabir Pradhand65552b2021-10-07 11:23:50 -0700532 const bool windowCanInterceptTouch = isStylus && windowInfo.interceptsStylus();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -0800533 if (inputConfig.test(WindowInfo::InputConfig::NOT_TOUCHABLE) && !windowCanInterceptTouch) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -0800534 return false;
535 }
Prabir Pradhan33e3baa2022-12-06 20:30:22 +0000536
537 // Window Manager works in the logical display coordinate space. When it specifies bounds for a
538 // window as (l, t, r, b), the range of x in [l, r) and y in [t, b) are considered to be inside
539 // the window. Points on the right and bottom edges should not be inside the window, so we need
540 // to be careful about performing a hit test when the display is rotated, since the "right" and
541 // "bottom" of the window will be different in the display (un-rotated) space compared to in the
542 // logical display in which WM determined the bounds. Perform the hit test in the logical
543 // display space to ensure these edges are considered correctly in all orientations.
544 const auto touchableRegion = displayTransform.transform(windowInfo.touchableRegion);
545 const auto p = displayTransform.transform(x, y);
546 if (!touchableRegion.contains(std::floor(p.x), std::floor(p.y))) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -0800547 return false;
548 }
549 return true;
550}
551
Prabir Pradhand65552b2021-10-07 11:23:50 -0700552bool isPointerFromStylus(const MotionEntry& entry, int32_t pointerIndex) {
553 return isFromSource(entry.source, AINPUT_SOURCE_STYLUS) &&
Prabir Pradhane5626962022-10-27 20:30:53 +0000554 isStylusToolType(entry.pointerProperties[pointerIndex].toolType);
Prabir Pradhand65552b2021-10-07 11:23:50 -0700555}
556
Siarhei Vishniakou253f4642022-11-09 13:42:06 -0800557// Determines if the given window can be targeted as InputTarget::Flags::FOREGROUND.
Prabir Pradhan6dfbf262022-03-14 15:24:30 +0000558// Foreground events are only sent to "foreground targetable" windows, but not all gestures sent to
559// such window are necessarily targeted with the flag. For example, an event with ACTION_OUTSIDE can
560// be sent to such a window, but it is not a foreground event and doesn't use
Siarhei Vishniakou253f4642022-11-09 13:42:06 -0800561// InputTarget::Flags::FOREGROUND.
Prabir Pradhan6dfbf262022-03-14 15:24:30 +0000562bool canReceiveForegroundTouches(const WindowInfo& info) {
563 // A non-touchable window can still receive touch events (e.g. in the case of
564 // STYLUS_INTERCEPTOR), so prevent such windows from receiving foreground events for touches.
565 return !info.inputConfig.test(gui::WindowInfo::InputConfig::NOT_TOUCHABLE) && !info.isSpy();
566}
567
Prabir Pradhanaeebeb42023-06-13 19:53:03 +0000568bool isWindowOwnedBy(const sp<WindowInfoHandle>& windowHandle, gui::Pid pid, gui::Uid uid) {
Antonio Kantek48710e42022-03-24 14:19:30 -0700569 if (windowHandle == nullptr) {
570 return false;
571 }
572 const WindowInfo* windowInfo = windowHandle->getInfo();
573 if (pid == windowInfo->ownerPid && uid == windowInfo->ownerUid) {
574 return true;
575 }
576 return false;
577}
578
Prabir Pradhan5735a322022-04-11 17:23:34 +0000579// Checks targeted injection using the window's owner's uid.
580// Returns an empty string if an entry can be sent to the given window, or an error message if the
581// entry is a targeted injection whose uid target doesn't match the window owner.
582std::optional<std::string> verifyTargetedInjection(const sp<WindowInfoHandle>& window,
583 const EventEntry& entry) {
584 if (entry.injectionState == nullptr || !entry.injectionState->targetUid) {
585 // The event was not injected, or the injected event does not target a window.
586 return {};
587 }
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +0000588 const auto uid = *entry.injectionState->targetUid;
Prabir Pradhan5735a322022-04-11 17:23:34 +0000589 if (window == nullptr) {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +0000590 return StringPrintf("No valid window target for injection into uid %s.",
591 uid.toString().c_str());
Prabir Pradhan5735a322022-04-11 17:23:34 +0000592 }
593 if (entry.injectionState->targetUid != window->getInfo()->ownerUid) {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +0000594 return StringPrintf("Injected event targeted at uid %s would be dispatched to window '%s' "
595 "owned by uid %s.",
596 uid.toString().c_str(), window->getName().c_str(),
597 window->getInfo()->ownerUid.toString().c_str());
Prabir Pradhan5735a322022-04-11 17:23:34 +0000598 }
599 return {};
600}
601
Prabir Pradhan82e081e2022-12-06 09:50:09 +0000602std::pair<float, float> resolveTouchedPosition(const MotionEntry& entry) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -0700603 const bool isFromMouse = isFromSource(entry.source, AINPUT_SOURCE_MOUSE);
604 // Always dispatch mouse events to cursor position.
605 if (isFromMouse) {
Prabir Pradhan82e081e2022-12-06 09:50:09 +0000606 return {entry.xCursorPosition, entry.yCursorPosition};
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -0700607 }
608
Siarhei Vishniakou5b9766d2023-07-18 14:06:29 -0700609 const int32_t pointerIndex = MotionEvent::getActionIndex(entry.action);
Prabir Pradhan82e081e2022-12-06 09:50:09 +0000610 return {entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_X),
611 entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_Y)};
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -0700612}
613
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -0700614std::optional<nsecs_t> getDownTime(const EventEntry& eventEntry) {
615 if (eventEntry.type == EventEntry::Type::KEY) {
616 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
617 return keyEntry.downTime;
618 } else if (eventEntry.type == EventEntry::Type::MOTION) {
619 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
620 return motionEntry.downTime;
621 }
622 return std::nullopt;
623}
624
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000625/**
626 * Compare the old touch state to the new touch state, and generate the corresponding touched
627 * windows (== input targets).
628 * If a window had the hovering pointer, but now it doesn't, produce HOVER_EXIT for that window.
629 * If the pointer just entered the new window, produce HOVER_ENTER.
630 * For pointers remaining in the window, produce HOVER_MOVE.
631 */
632std::vector<TouchedWindow> getHoveringWindowsLocked(const TouchState* oldState,
633 const TouchState& newTouchState,
634 const MotionEntry& entry) {
635 std::vector<TouchedWindow> out;
636 const int32_t maskedAction = MotionEvent::getActionMasked(entry.action);
Siarhei Vishniakou2899c552023-07-10 18:20:46 -0700637
638 if (maskedAction == AMOTION_EVENT_ACTION_SCROLL) {
639 // ACTION_SCROLL events should not affect the hovering pointer dispatch
640 return {};
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000641 }
642
643 // We should consider all hovering pointers here. But for now, just use the first one
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -0800644 const PointerProperties& pointer = entry.pointerProperties[0];
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000645
646 std::set<sp<WindowInfoHandle>> oldWindows;
647 if (oldState != nullptr) {
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -0800648 oldWindows = oldState->getWindowsWithHoveringPointer(entry.deviceId, pointer.id);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000649 }
650
651 std::set<sp<WindowInfoHandle>> newWindows =
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -0800652 newTouchState.getWindowsWithHoveringPointer(entry.deviceId, pointer.id);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000653
654 // If the pointer is no longer in the new window set, send HOVER_EXIT.
655 for (const sp<WindowInfoHandle>& oldWindow : oldWindows) {
656 if (newWindows.find(oldWindow) == newWindows.end()) {
657 TouchedWindow touchedWindow;
658 touchedWindow.windowHandle = oldWindow;
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +0000659 touchedWindow.dispatchMode = InputTarget::DispatchMode::HOVER_EXIT;
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000660 out.push_back(touchedWindow);
661 }
662 }
663
664 for (const sp<WindowInfoHandle>& newWindow : newWindows) {
665 TouchedWindow touchedWindow;
666 touchedWindow.windowHandle = newWindow;
667 if (oldWindows.find(newWindow) == oldWindows.end()) {
668 // Any windows that have this pointer now, and didn't have it before, should get
669 // HOVER_ENTER
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +0000670 touchedWindow.dispatchMode = InputTarget::DispatchMode::HOVER_ENTER;
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000671 } else {
672 // This pointer was already sent to the window. Use ACTION_HOVER_MOVE.
Siarhei Vishniakouc2eb8502023-04-11 18:33:36 -0700673 if (CC_UNLIKELY(maskedAction != AMOTION_EVENT_ACTION_HOVER_MOVE)) {
Daniel Norman7487dfa2023-08-02 16:39:45 -0700674 android::base::LogSeverity severity = android::base::LogSeverity::FATAL;
Ameer Armalycff4fa52023-10-04 23:45:11 +0000675 if (!input_flags::a11y_crash_on_inconsistent_event_stream() &&
676 entry.flags & AMOTION_EVENT_FLAG_IS_ACCESSIBILITY_EVENT) {
Daniel Norman7487dfa2023-08-02 16:39:45 -0700677 // The Accessibility injected touch exploration event stream
678 // has known inconsistencies, so log ERROR instead of
679 // crashing the device with FATAL.
Daniel Norman7487dfa2023-08-02 16:39:45 -0700680 severity = android::base::LogSeverity::ERROR;
681 }
682 LOG(severity) << "Expected ACTION_HOVER_MOVE instead of " << entry.getDescription();
Siarhei Vishniakouc2eb8502023-04-11 18:33:36 -0700683 }
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +0000684 touchedWindow.dispatchMode = InputTarget::DispatchMode::AS_IS;
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000685 }
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -0800686 touchedWindow.addHoveringPointer(entry.deviceId, pointer);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000687 if (canReceiveForegroundTouches(*newWindow->getInfo())) {
688 touchedWindow.targetFlags |= InputTarget::Flags::FOREGROUND;
689 }
690 out.push_back(touchedWindow);
691 }
692 return out;
693}
694
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -0800695template <typename T>
696std::vector<T>& operator+=(std::vector<T>& left, const std::vector<T>& right) {
697 left.insert(left.end(), right.begin(), right.end());
698 return left;
699}
700
Harry Cuttsb166c002023-05-09 13:06:05 +0000701// Filter windows in a TouchState and targets in a vector to remove untrusted windows/targets from
702// both.
703void filterUntrustedTargets(TouchState& touchState, std::vector<InputTarget>& targets) {
704 std::erase_if(touchState.windows, [&](const TouchedWindow& window) {
705 if (!window.windowHandle->getInfo()->inputConfig.test(
706 WindowInfo::InputConfig::TRUSTED_OVERLAY)) {
707 // In addition to TouchState, erase this window from the input targets! We don't have a
708 // good way to do this today except by adding a nested loop.
709 // TODO(b/282025641): simplify this code once InputTargets are being identified
710 // separately from TouchedWindows.
711 std::erase_if(targets, [&](const InputTarget& target) {
712 return target.inputChannel->getConnectionToken() == window.windowHandle->getToken();
713 });
714 return true;
715 }
716 return false;
717 });
718}
719
Siarhei Vishniakouce1fd472023-09-18 18:38:07 -0700720/**
721 * In general, touch should be always split between windows. Some exceptions:
722 * 1. Don't split touch if all of the below is true:
723 * (a) we have an active pointer down *and*
724 * (b) a new pointer is going down that's from the same device *and*
725 * (c) the window that's receiving the current pointer does not support split touch.
726 * 2. Don't split mouse events
727 */
728bool shouldSplitTouch(const TouchState& touchState, const MotionEntry& entry) {
729 if (isFromSource(entry.source, AINPUT_SOURCE_MOUSE)) {
730 // We should never split mouse events
731 return false;
732 }
733 for (const TouchedWindow& touchedWindow : touchState.windows) {
734 if (touchedWindow.windowHandle->getInfo()->isSpy()) {
735 // Spy windows should not affect whether or not touch is split.
736 continue;
737 }
738 if (touchedWindow.windowHandle->getInfo()->supportsSplitTouch()) {
739 continue;
740 }
741 if (touchedWindow.windowHandle->getInfo()->inputConfig.test(
742 gui::WindowInfo::InputConfig::IS_WALLPAPER)) {
743 // Wallpaper window should not affect whether or not touch is split
744 continue;
745 }
746
747 if (touchedWindow.hasTouchingPointers(entry.deviceId)) {
748 return false;
749 }
750 }
751 return true;
752}
753
Siarhei Vishniakouf77f60a2023-10-23 17:26:05 -0700754/**
755 * Return true if stylus is currently down anywhere on the specified display, and false otherwise.
756 */
757bool isStylusActiveInDisplay(
758 int32_t displayId,
759 const std::unordered_map<int32_t /*displayId*/, TouchState>& touchStatesByDisplay) {
760 const auto it = touchStatesByDisplay.find(displayId);
761 if (it == touchStatesByDisplay.end()) {
762 return false;
763 }
764 const TouchState& state = it->second;
765 return state.hasActiveStylus();
766}
767
Siarhei Vishniakouaeed0da2024-01-09 08:57:13 -0800768Result<void> validateWindowInfosUpdate(const gui::WindowInfosUpdate& update) {
769 struct HashFunction {
770 size_t operator()(const WindowInfo& info) const { return info.id; }
771 };
772
773 std::unordered_set<WindowInfo, HashFunction> windowSet;
774 for (const WindowInfo& info : update.windowInfos) {
775 const auto [_, inserted] = windowSet.insert(info);
776 if (!inserted) {
777 return Error() << "Duplicate entry for " << info;
778 }
779 }
780 return {};
781}
782
Yeabkal Wubshitb8aadfa2024-01-17 17:03:42 -0800783int32_t getUserActivityEventType(const EventEntry& eventEntry) {
784 switch (eventEntry.type) {
785 case EventEntry::Type::KEY: {
786 return USER_ACTIVITY_EVENT_BUTTON;
787 }
788 case EventEntry::Type::MOTION: {
789 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
790 if (MotionEvent::isTouchEvent(motionEntry.source, motionEntry.action)) {
791 return USER_ACTIVITY_EVENT_TOUCH;
792 }
793 return USER_ACTIVITY_EVENT_OTHER;
794 }
795 default: {
796 LOG_ALWAYS_FATAL("%s events are not user activity",
797 ftl::enum_string(eventEntry.type).c_str());
798 }
799 }
800}
801
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000802} // namespace
803
Michael Wrightd02c5b62014-02-10 15:10:22 -0800804// --- InputDispatcher ---
805
Prabir Pradhana41d2442023-04-20 21:30:40 +0000806InputDispatcher::InputDispatcher(InputDispatcherPolicyInterface& policy)
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +0000807 : InputDispatcher(policy, nullptr) {}
808
809InputDispatcher::InputDispatcher(InputDispatcherPolicyInterface& policy,
810 std::unique_ptr<trace::InputTracingBackendInterface> traceBackend)
Garfield Tan00f511d2019-06-12 16:55:40 -0700811 : mPolicy(policy),
812 mPendingEvent(nullptr),
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700813 mLastDropReason(DropReason::NOT_DROPPED),
Garfield Tanff1f1bb2020-01-28 13:24:04 -0800814 mIdGenerator(IdGenerator::Source::INPUT_DISPATCHER),
Yeabkal Wubshitb8aadfa2024-01-17 17:03:42 -0800815 mMinTimeBetweenUserActivityPokes(DEFAULT_USER_ACTIVITY_POKE_INTERVAL),
Garfield Tan00f511d2019-06-12 16:55:40 -0700816 mNextUnblockedEvent(nullptr),
Prabir Pradhan1376fcd2022-01-21 09:56:35 -0800817 mMonitorDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT),
Garfield Tan00f511d2019-06-12 16:55:40 -0700818 mDispatchEnabled(false),
819 mDispatchFrozen(false),
820 mInputFilterEnabled(false),
Bernardo Rufinoea97d182020-08-19 14:43:14 +0100821 mMaximumObscuringOpacityForTouch(1.0f),
Siarhei Vishniakou2508b872020-12-03 16:33:53 -1000822 mFocusedDisplayId(ADISPLAY_ID_DEFAULT),
Prabir Pradhan99987712020-11-10 18:43:05 -0800823 mWindowTokenWithPointerCapture(nullptr),
Siarhei Vishniakoua04181f2021-03-26 05:56:49 +0000824 mLatencyAggregator(),
Antonio Kantek15beb512022-06-13 22:35:41 +0000825 mLatencyTracker(&mLatencyAggregator) {
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -0700826 mLooper = sp<Looper>::make(false);
Prabir Pradhanf93562f2018-11-29 12:13:37 -0800827 mReporter = createInputReporter();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800828
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -0700829 mWindowInfoListener = sp<DispatcherWindowListener>::make(*this);
Siarhei Vishniakou31977182022-09-30 08:51:23 -0700830#if defined(__ANDROID__)
Siarhei Vishniakou18050092021-09-01 13:32:49 -0700831 SurfaceComposerClient::getDefault()->addWindowInfosListener(mWindowInfoListener);
Siarhei Vishniakou31977182022-09-30 08:51:23 -0700832#endif
Yi Kong9b14ac62018-07-17 13:48:38 -0700833 mKeyRepeatState.lastKeyEntry = nullptr;
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +0000834
835 if (traceBackend) {
836 // TODO: Create input tracer instance.
837 }
Yeabkal Wubshitb8aadfa2024-01-17 17:03:42 -0800838
839 mLastUserActivityTimes.fill(0);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800840}
841
842InputDispatcher::~InputDispatcher() {
Prabir Pradhancef936d2021-07-21 16:17:52 +0000843 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800844
Prabir Pradhancef936d2021-07-21 16:17:52 +0000845 resetKeyRepeatLocked();
846 releasePendingEventLocked();
847 drainInboundQueueLocked();
848 mCommandQueue.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800849
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +0000850 while (!mConnectionsByToken.empty()) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -0700851 std::shared_ptr<Connection> connection = mConnectionsByToken.begin()->second;
Harry Cutts33476232023-01-30 19:57:29 +0000852 removeInputChannelLocked(connection->inputChannel->getConnectionToken(), /*notify=*/false);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800853 }
854}
855
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700856status_t InputDispatcher::start() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700857 if (mThread) {
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700858 return ALREADY_EXISTS;
859 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700860 mThread = std::make_unique<InputThread>(
861 "InputDispatcher", [this]() { dispatchOnce(); }, [this]() { mLooper->wake(); });
862 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700863}
864
865status_t InputDispatcher::stop() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700866 if (mThread && mThread->isCallingThread()) {
867 ALOGE("InputDispatcher cannot be stopped from its own thread!");
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700868 return INVALID_OPERATION;
869 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700870 mThread.reset();
871 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700872}
873
Michael Wrightd02c5b62014-02-10 15:10:22 -0800874void InputDispatcher::dispatchOnce() {
Colin Cross5b799302022-10-18 21:52:41 -0700875 nsecs_t nextWakeupTime = LLONG_MAX;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800876 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -0800877 std::scoped_lock _l(mLock);
878 mDispatcherIsAlive.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800879
880 // Run a dispatch loop if there are no pending commands.
881 // The dispatch loop might enqueue commands to run afterwards.
882 if (!haveCommandsLocked()) {
Siarhei Vishniakou69505962023-12-28 12:07:04 -0800883 dispatchOnceInnerLocked(/*byref*/ nextWakeupTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800884 }
885
886 // Run all pending commands if there are any.
887 // If any commands were run then force the next poll to wake up immediately.
Prabir Pradhancef936d2021-07-21 16:17:52 +0000888 if (runCommandsLockedInterruptable()) {
Colin Cross5b799302022-10-18 21:52:41 -0700889 nextWakeupTime = LLONG_MIN;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800890 }
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800891
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700892 // If we are still waiting for ack on some events,
893 // we might have to wake up earlier to check if an app is anr'ing.
894 const nsecs_t nextAnrCheck = processAnrsLocked();
895 nextWakeupTime = std::min(nextWakeupTime, nextAnrCheck);
896
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800897 // We are about to enter an infinitely long sleep, because we have no commands or
898 // pending or queued events
Colin Cross5b799302022-10-18 21:52:41 -0700899 if (nextWakeupTime == LLONG_MAX) {
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800900 mDispatcherEnteredIdle.notify_all();
901 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800902 } // release lock
903
904 // Wait for callback or timeout or wake. (make sure we round up, not down)
905 nsecs_t currentTime = now();
906 int timeoutMillis = toMillisecondTimeoutDelay(currentTime, nextWakeupTime);
907 mLooper->pollOnce(timeoutMillis);
908}
909
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700910/**
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500911 * Raise ANR if there is no focused window.
912 * Before the ANR is raised, do a final state check:
913 * 1. The currently focused application must be the same one we are waiting for.
914 * 2. Ensure we still don't have a focused window.
915 */
916void InputDispatcher::processNoFocusedWindowAnrLocked() {
917 // Check if the application that we are waiting for is still focused.
918 std::shared_ptr<InputApplicationHandle> focusedApplication =
919 getValueByKey(mFocusedApplicationHandlesByDisplay, mAwaitedApplicationDisplayId);
920 if (focusedApplication == nullptr ||
921 focusedApplication->getApplicationToken() !=
922 mAwaitedFocusedApplication->getApplicationToken()) {
923 // Unexpected because we should have reset the ANR timer when focused application changed
924 ALOGE("Waited for a focused window, but focused application has already changed to %s",
925 focusedApplication->getName().c_str());
926 return; // The focused application has changed.
927 }
928
chaviw98318de2021-05-19 16:45:23 -0500929 const sp<WindowInfoHandle>& focusedWindowHandle =
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500930 getFocusedWindowHandleLocked(mAwaitedApplicationDisplayId);
931 if (focusedWindowHandle != nullptr) {
932 return; // We now have a focused window. No need for ANR.
933 }
934 onAnrLocked(mAwaitedFocusedApplication);
935}
936
937/**
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700938 * Check if any of the connections' wait queues have events that are too old.
939 * If we waited for events to be ack'ed for more than the window timeout, raise an ANR.
940 * Return the time at which we should wake up next.
941 */
942nsecs_t InputDispatcher::processAnrsLocked() {
943 const nsecs_t currentTime = now();
Colin Cross5b799302022-10-18 21:52:41 -0700944 nsecs_t nextAnrCheck = LLONG_MAX;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700945 // Check if we are waiting for a focused window to appear. Raise ANR if waited too long
946 if (mNoFocusedWindowTimeoutTime.has_value() && mAwaitedFocusedApplication != nullptr) {
947 if (currentTime >= *mNoFocusedWindowTimeoutTime) {
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500948 processNoFocusedWindowAnrLocked();
Chris Yea209fde2020-07-22 13:54:51 -0700949 mAwaitedFocusedApplication.reset();
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500950 mNoFocusedWindowTimeoutTime = std::nullopt;
Colin Cross5b799302022-10-18 21:52:41 -0700951 return LLONG_MIN;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700952 } else {
Siarhei Vishniakou38a6d272020-10-20 20:29:33 -0500953 // Keep waiting. We will drop the event when mNoFocusedWindowTimeoutTime comes.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700954 nextAnrCheck = *mNoFocusedWindowTimeoutTime;
955 }
956 }
957
958 // Check if any connection ANRs are due
959 nextAnrCheck = std::min(nextAnrCheck, mAnrTracker.firstTimeout());
960 if (currentTime < nextAnrCheck) { // most likely scenario
961 return nextAnrCheck; // everything is normal. Let's check again at nextAnrCheck
962 }
963
964 // If we reached here, we have an unresponsive connection.
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -0700965 std::shared_ptr<Connection> connection = getConnectionLocked(mAnrTracker.firstToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700966 if (connection == nullptr) {
967 ALOGE("Could not find connection for entry %" PRId64, mAnrTracker.firstTimeout());
968 return nextAnrCheck;
969 }
970 connection->responsive = false;
971 // Stop waking up for this unresponsive connection
972 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000973 onAnrLocked(connection);
Colin Cross5b799302022-10-18 21:52:41 -0700974 return LLONG_MIN;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700975}
976
Prabir Pradhan1376fcd2022-01-21 09:56:35 -0800977std::chrono::nanoseconds InputDispatcher::getDispatchingTimeoutLocked(
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -0700978 const std::shared_ptr<Connection>& connection) {
Prabir Pradhan1376fcd2022-01-21 09:56:35 -0800979 if (connection->monitor) {
980 return mMonitorDispatchingTimeout;
981 }
982 const sp<WindowInfoHandle> window =
983 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700984 if (window != nullptr) {
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500985 return window->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700986 }
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500987 return DEFAULT_INPUT_DISPATCHING_TIMEOUT;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700988}
989
Siarhei Vishniakou69505962023-12-28 12:07:04 -0800990void InputDispatcher::dispatchOnceInnerLocked(nsecs_t& nextWakeupTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800991 nsecs_t currentTime = now();
992
Jeff Browndc5992e2014-04-11 01:27:26 -0700993 // Reset the key repeat timer whenever normal dispatch is suspended while the
994 // device is in a non-interactive state. This is to ensure that we abort a key
995 // repeat if the device is just coming out of sleep.
996 if (!mDispatchEnabled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800997 resetKeyRepeatLocked();
998 }
999
1000 // If dispatching is frozen, do not process timeouts or try to deliver any new events.
1001 if (mDispatchFrozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001002 if (DEBUG_FOCUS) {
1003 ALOGD("Dispatch frozen. Waiting some more.");
1004 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001005 return;
1006 }
1007
Michael Wrightd02c5b62014-02-10 15:10:22 -08001008 // Ready to start a new event.
1009 // If we don't already have a pending event, go grab one.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001010 if (!mPendingEvent) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001011 if (mInboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001012 // Synthesize a key repeat if appropriate.
1013 if (mKeyRepeatState.lastKeyEntry) {
1014 if (currentTime >= mKeyRepeatState.nextRepeatTime) {
1015 mPendingEvent = synthesizeKeyRepeatLocked(currentTime);
1016 } else {
Siarhei Vishniakou69505962023-12-28 12:07:04 -08001017 nextWakeupTime = std::min(nextWakeupTime, mKeyRepeatState.nextRepeatTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001018 }
1019 }
1020
1021 // Nothing to do if there is no pending event.
1022 if (!mPendingEvent) {
1023 return;
1024 }
1025 } else {
1026 // Inbound queue has at least one entry.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001027 mPendingEvent = mInboundQueue.front();
1028 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001029 traceInboundQueueLengthLocked();
1030 }
1031
1032 // Poke user activity for this event.
1033 if (mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001034 pokeUserActivityLocked(*mPendingEvent);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001035 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001036 }
1037
1038 // Now we have an event to dispatch.
1039 // All events are eventually dequeued and processed this way, even if we intend to drop them.
Yi Kong9b14ac62018-07-17 13:48:38 -07001040 ALOG_ASSERT(mPendingEvent != nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001041 bool done = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001042 DropReason dropReason = DropReason::NOT_DROPPED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001043 if (!(mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001044 dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001045 } else if (!mDispatchEnabled) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001046 dropReason = DropReason::DISABLED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001047 }
1048
1049 if (mNextUnblockedEvent == mPendingEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001050 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001051 }
1052
1053 switch (mPendingEvent->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001054 case EventEntry::Type::CONFIGURATION_CHANGED: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001055 const ConfigurationChangedEntry& typedEntry =
1056 static_cast<const ConfigurationChangedEntry&>(*mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001057 done = dispatchConfigurationChangedLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001058 dropReason = DropReason::NOT_DROPPED; // configuration changes are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001059 break;
1060 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001061
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001062 case EventEntry::Type::DEVICE_RESET: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001063 const DeviceResetEntry& typedEntry =
1064 static_cast<const DeviceResetEntry&>(*mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001065 done = dispatchDeviceResetLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001066 dropReason = DropReason::NOT_DROPPED; // device resets are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001067 break;
1068 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001069
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001070 case EventEntry::Type::FOCUS: {
Prabir Pradhan24047542023-11-02 17:14:59 +00001071 std::shared_ptr<const FocusEntry> typedEntry =
1072 std::static_pointer_cast<const FocusEntry>(mPendingEvent);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001073 dispatchFocusLocked(currentTime, typedEntry);
1074 done = true;
1075 dropReason = DropReason::NOT_DROPPED; // focus events are never dropped
1076 break;
1077 }
1078
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001079 case EventEntry::Type::TOUCH_MODE_CHANGED: {
Prabir Pradhan24047542023-11-02 17:14:59 +00001080 const auto typedEntry = std::static_pointer_cast<const TouchModeEntry>(mPendingEvent);
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001081 dispatchTouchModeChangeLocked(currentTime, typedEntry);
1082 done = true;
1083 dropReason = DropReason::NOT_DROPPED; // touch mode events are never dropped
1084 break;
1085 }
1086
Prabir Pradhan99987712020-11-10 18:43:05 -08001087 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
1088 const auto typedEntry =
Prabir Pradhan24047542023-11-02 17:14:59 +00001089 std::static_pointer_cast<const PointerCaptureChangedEntry>(mPendingEvent);
Prabir Pradhan99987712020-11-10 18:43:05 -08001090 dispatchPointerCaptureChangedLocked(currentTime, typedEntry, dropReason);
1091 done = true;
1092 break;
1093 }
1094
arthurhungb89ccb02020-12-30 16:19:01 +08001095 case EventEntry::Type::DRAG: {
Prabir Pradhan24047542023-11-02 17:14:59 +00001096 std::shared_ptr<const DragEntry> typedEntry =
1097 std::static_pointer_cast<const DragEntry>(mPendingEvent);
arthurhungb89ccb02020-12-30 16:19:01 +08001098 dispatchDragLocked(currentTime, typedEntry);
1099 done = true;
1100 break;
1101 }
1102
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001103 case EventEntry::Type::KEY: {
Prabir Pradhan24047542023-11-02 17:14:59 +00001104 std::shared_ptr<const KeyEntry> keyEntry =
1105 std::static_pointer_cast<const KeyEntry>(mPendingEvent);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001106 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *keyEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001107 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001108 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001109 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
1110 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001111 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001112 done = dispatchKeyLocked(currentTime, keyEntry, &dropReason, nextWakeupTime);
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00001113 if (done && mTracer) {
1114 ensureEventTraced(*keyEntry);
1115 mTracer->eventProcessingComplete(*keyEntry->traceTracker);
1116 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001117 break;
1118 }
1119
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001120 case EventEntry::Type::MOTION: {
Prabir Pradhan24047542023-11-02 17:14:59 +00001121 std::shared_ptr<const MotionEntry> motionEntry =
1122 std::static_pointer_cast<const MotionEntry>(mPendingEvent);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001123 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *motionEntry)) {
Siarhei Vishniakou6b71b632023-10-27 21:34:46 -07001124 // The event is stale. However, only drop stale events if there isn't an ongoing
1125 // gesture. That would allow us to complete the processing of the current stroke.
1126 const auto touchStateIt = mTouchStatesByDisplay.find(motionEntry->displayId);
1127 if (touchStateIt != mTouchStatesByDisplay.end()) {
1128 const TouchState& touchState = touchStateIt->second;
1129 if (!touchState.hasTouchingPointers(motionEntry->deviceId) &&
1130 !touchState.hasHoveringPointers(motionEntry->deviceId)) {
1131 dropReason = DropReason::STALE;
1132 }
1133 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001134 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001135 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
Siarhei Vishniakou99e407b2023-12-26 18:09:32 -08001136 if (!isFromSource(motionEntry->source, AINPUT_SOURCE_CLASS_POINTER)) {
1137 // Only drop events that are focus-dispatched.
1138 dropReason = DropReason::BLOCKED;
1139 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001140 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001141 done = dispatchMotionLocked(currentTime, motionEntry, &dropReason, nextWakeupTime);
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00001142 if (done && mTracer) {
1143 ensureEventTraced(*motionEntry);
1144 mTracer->eventProcessingComplete(*motionEntry->traceTracker);
1145 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001146 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001147 }
Chris Yef59a2f42020-10-16 12:55:26 -07001148
1149 case EventEntry::Type::SENSOR: {
Prabir Pradhan24047542023-11-02 17:14:59 +00001150 std::shared_ptr<const SensorEntry> sensorEntry =
1151 std::static_pointer_cast<const SensorEntry>(mPendingEvent);
Siarhei Vishniakoue2404a12024-01-16 18:38:39 -08001152
Chris Yef59a2f42020-10-16 12:55:26 -07001153 // Sensor timestamps use SYSTEM_TIME_BOOTTIME time base, so we can't use
1154 // 'currentTime' here, get SYSTEM_TIME_BOOTTIME instead.
1155 nsecs_t bootTime = systemTime(SYSTEM_TIME_BOOTTIME);
1156 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(bootTime, *sensorEntry)) {
1157 dropReason = DropReason::STALE;
1158 }
1159 dispatchSensorLocked(currentTime, sensorEntry, &dropReason, nextWakeupTime);
1160 done = true;
1161 break;
1162 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001163 }
1164
1165 if (done) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001166 if (dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001167 dropInboundEventLocked(*mPendingEvent, dropReason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001168 }
Michael Wright3a981722015-06-10 15:26:13 +01001169 mLastDropReason = dropReason;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001170
1171 releasePendingEventLocked();
Siarhei Vishniakou69505962023-12-28 12:07:04 -08001172 nextWakeupTime = LLONG_MIN; // force next poll to wake up immediately
Michael Wrightd02c5b62014-02-10 15:10:22 -08001173 }
1174}
1175
Siarhei Vishniakou289e9242022-02-15 14:50:16 -08001176bool InputDispatcher::isStaleEvent(nsecs_t currentTime, const EventEntry& entry) {
Siarhei Vishniakoua7333112023-10-27 13:33:29 -07001177 return mPolicy.isStaleEvent(currentTime, entry.eventTime);
Siarhei Vishniakou289e9242022-02-15 14:50:16 -08001178}
1179
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001180/**
1181 * Return true if the events preceding this incoming motion event should be dropped
1182 * Return false otherwise (the default behaviour)
1183 */
1184bool InputDispatcher::shouldPruneInboundQueueLocked(const MotionEntry& motionEntry) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001185 const bool isPointerDownEvent = motionEntry.action == AMOTION_EVENT_ACTION_DOWN &&
Prabir Pradhanaa561d12021-09-24 06:57:33 -07001186 isFromSource(motionEntry.source, AINPUT_SOURCE_CLASS_POINTER);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001187
1188 // Optimize case where the current application is unresponsive and the user
1189 // decides to touch a window in a different application.
1190 // If the application takes too long to catch up then we drop all events preceding
1191 // the touch into the other window.
1192 if (isPointerDownEvent && mAwaitedFocusedApplication != nullptr) {
Siarhei Vishniakou9306c382022-09-30 15:30:31 -07001193 const int32_t displayId = motionEntry.displayId;
1194 const auto [x, y] = resolveTouchedPosition(motionEntry);
Harry Cutts33476232023-01-30 19:57:29 +00001195 const bool isStylus = isPointerFromStylus(motionEntry, /*pointerIndex=*/0);
Siarhei Vishniakou9306c382022-09-30 15:30:31 -07001196
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07001197 sp<WindowInfoHandle> touchedWindowHandle =
1198 findTouchedWindowAtLocked(displayId, x, y, isStylus);
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001199 if (touchedWindowHandle != nullptr &&
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001200 touchedWindowHandle->getApplicationToken() !=
1201 mAwaitedFocusedApplication->getApplicationToken()) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001202 // User touched a different application than the one we are waiting on.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001203 ALOGI("Pruning input queue because user touched a different application while waiting "
1204 "for %s",
1205 mAwaitedFocusedApplication->getName().c_str());
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001206 return true;
1207 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001208
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08001209 // Alternatively, maybe there's a spy window that could handle this event.
1210 const std::vector<sp<WindowInfoHandle>> touchedSpies =
1211 findTouchedSpyWindowsAtLocked(displayId, x, y, isStylus);
1212 for (const auto& windowHandle : touchedSpies) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07001213 const std::shared_ptr<Connection> connection =
1214 getConnectionLocked(windowHandle->getToken());
Siarhei Vishniakou34ed4d42020-06-18 00:43:02 +00001215 if (connection != nullptr && connection->responsive) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08001216 // This spy window could take more input. Drop all events preceding this
1217 // event, so that the spy window can get a chance to receive the stream.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001218 ALOGW("Pruning the input queue because %s is unresponsive, but we have a "
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08001219 "responsive spy window that may handle the event.",
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001220 mAwaitedFocusedApplication->getName().c_str());
1221 return true;
1222 }
1223 }
1224 }
1225
1226 // Prevent getting stuck: if we have a pending key event, and some motion events that have not
1227 // yet been processed by some connections, the dispatcher will wait for these motion
1228 // events to be processed before dispatching the key event. This is because these motion events
1229 // may cause a new window to be launched, which the user might expect to receive focus.
1230 // To prevent waiting forever for such events, just send the key to the currently focused window
1231 if (isPointerDownEvent && mKeyIsWaitingForEventsTimeout) {
1232 ALOGD("Received a new pointer down event, stop waiting for events to process and "
1233 "just send the pending key event to the focused window.");
1234 mKeyIsWaitingForEventsTimeout = now();
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001235 }
1236 return false;
1237}
1238
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001239bool InputDispatcher::enqueueInboundEventLocked(std::unique_ptr<EventEntry> newEntry) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001240 bool needWake = mInboundQueue.empty();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001241 mInboundQueue.push_back(std::move(newEntry));
Prabir Pradhan24047542023-11-02 17:14:59 +00001242 const EventEntry& entry = *(mInboundQueue.back());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001243 traceInboundQueueLengthLocked();
1244
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001245 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001246 case EventEntry::Type::KEY: {
Prabir Pradhan5735a322022-04-11 17:23:34 +00001247 LOG_ALWAYS_FATAL_IF((entry.policyFlags & POLICY_FLAG_TRUSTED) == 0,
1248 "Unexpected untrusted event.");
Siarhei Vishniakoue2404a12024-01-16 18:38:39 -08001249
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001250 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00001251 if (mTracer) {
1252 ensureEventTraced(keyEntry);
1253 }
Siarhei Vishniakou6520a582023-10-27 21:53:45 -07001254
Arthur Hung2ee6d0b2022-03-03 20:19:38 +08001255 // If a new up event comes in, and the pending event with same key code has been asked
1256 // to try again later because of the policy. We have to reset the intercept key wake up
1257 // time for it may have been handled in the policy and could be dropped.
1258 if (keyEntry.action == AKEY_EVENT_ACTION_UP && mPendingEvent &&
1259 mPendingEvent->type == EventEntry::Type::KEY) {
Prabir Pradhan24047542023-11-02 17:14:59 +00001260 const KeyEntry& pendingKey = static_cast<const KeyEntry&>(*mPendingEvent);
Arthur Hung2ee6d0b2022-03-03 20:19:38 +08001261 if (pendingKey.keyCode == keyEntry.keyCode &&
1262 pendingKey.interceptKeyResult ==
Michael Wright5caf55a2022-11-24 22:31:42 +00001263 KeyEntry::InterceptKeyResult::TRY_AGAIN_LATER) {
1264 pendingKey.interceptKeyResult = KeyEntry::InterceptKeyResult::UNKNOWN;
Arthur Hung2ee6d0b2022-03-03 20:19:38 +08001265 pendingKey.interceptKeyWakeupTime = 0;
1266 needWake = true;
1267 }
1268 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001269 break;
1270 }
1271
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001272 case EventEntry::Type::MOTION: {
Prabir Pradhan5735a322022-04-11 17:23:34 +00001273 LOG_ALWAYS_FATAL_IF((entry.policyFlags & POLICY_FLAG_TRUSTED) == 0,
1274 "Unexpected untrusted event.");
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00001275 const auto& motionEntry = static_cast<const MotionEntry&>(entry);
1276 if (mTracer) {
1277 ensureEventTraced(motionEntry);
1278 }
1279 if (shouldPruneInboundQueueLocked(motionEntry)) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001280 mNextUnblockedEvent = mInboundQueue.back();
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001281 needWake = true;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001282 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001283 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001284 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001285 case EventEntry::Type::FOCUS: {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001286 LOG_ALWAYS_FATAL("Focus events should be inserted using enqueueFocusEventLocked");
1287 break;
1288 }
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001289 case EventEntry::Type::TOUCH_MODE_CHANGED:
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001290 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08001291 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07001292 case EventEntry::Type::SENSOR:
arthurhungb89ccb02020-12-30 16:19:01 +08001293 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
1294 case EventEntry::Type::DRAG: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001295 // nothing to do
1296 break;
1297 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001298 }
1299
1300 return needWake;
1301}
1302
Prabir Pradhan24047542023-11-02 17:14:59 +00001303void InputDispatcher::addRecentEventLocked(std::shared_ptr<const EventEntry> entry) {
Chris Yef59a2f42020-10-16 12:55:26 -07001304 // Do not store sensor event in recent queue to avoid flooding the queue.
1305 if (entry->type != EventEntry::Type::SENSOR) {
1306 mRecentQueue.push_back(entry);
1307 }
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001308 if (mRecentQueue.size() > RECENT_QUEUE_MAX_SIZE) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001309 mRecentQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001310 }
1311}
1312
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07001313sp<WindowInfoHandle> InputDispatcher::findTouchedWindowAtLocked(int32_t displayId, float x, float y,
1314 bool isStylus,
1315 bool ignoreDragWindow) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001316 // Traverse windows from front to back to find touched window.
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001317 const auto& windowHandles = getWindowHandlesLocked(displayId);
chaviw98318de2021-05-19 16:45:23 -05001318 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
arthurhung6d4bed92021-03-17 11:59:33 +08001319 if (ignoreDragWindow && haveSameToken(windowHandle, mDragState->dragWindow)) {
arthurhungb89ccb02020-12-30 16:19:01 +08001320 continue;
1321 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001322
Prabir Pradhan3f90d312021-11-19 03:57:24 -08001323 const WindowInfo& info = *windowHandle->getInfo();
Prabir Pradhan33e3baa2022-12-06 20:30:22 +00001324 if (!info.isSpy() &&
1325 windowAcceptsTouchAt(info, displayId, x, y, isStylus, getTransformLocked(displayId))) {
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07001326 return windowHandle;
1327 }
1328 }
1329 return nullptr;
1330}
1331
1332std::vector<InputTarget> InputDispatcher::findOutsideTargetsLocked(
Siarhei Vishniakou70f3d8c2023-09-19 15:36:52 -07001333 int32_t displayId, const sp<WindowInfoHandle>& touchedWindow, int32_t pointerId) const {
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07001334 if (touchedWindow == nullptr) {
1335 return {};
1336 }
1337 // Traverse windows from front to back until we encounter the touched window.
1338 std::vector<InputTarget> outsideTargets;
1339 const auto& windowHandles = getWindowHandlesLocked(displayId);
1340 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
1341 if (windowHandle == touchedWindow) {
1342 // Stop iterating once we found a touched window. Any WATCH_OUTSIDE_TOUCH window
1343 // below the touched window will not get ACTION_OUTSIDE event.
1344 return outsideTargets;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08001345 }
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001346
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07001347 const WindowInfo& info = *windowHandle->getInfo();
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08001348 if (info.inputConfig.test(WindowInfo::InputConfig::WATCH_OUTSIDE_TOUCH)) {
Siarhei Vishniakou70f3d8c2023-09-19 15:36:52 -07001349 std::bitset<MAX_POINTER_ID + 1> pointerIds;
1350 pointerIds.set(pointerId);
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00001351 addPointerWindowTargetLocked(windowHandle, InputTarget::DispatchMode::OUTSIDE,
1352 ftl::Flags<InputTarget::Flags>(), pointerIds,
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07001353 /*firstDownTimeInTarget=*/std::nullopt, outsideTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001354 }
1355 }
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07001356 return outsideTargets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001357}
1358
Prabir Pradhand65552b2021-10-07 11:23:50 -07001359std::vector<sp<WindowInfoHandle>> InputDispatcher::findTouchedSpyWindowsAtLocked(
Prabir Pradhan82e081e2022-12-06 09:50:09 +00001360 int32_t displayId, float x, float y, bool isStylus) const {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001361 // Traverse windows from front to back and gather the touched spy windows.
1362 std::vector<sp<WindowInfoHandle>> spyWindows;
1363 const auto& windowHandles = getWindowHandlesLocked(displayId);
1364 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
1365 const WindowInfo& info = *windowHandle->getInfo();
1366
Prabir Pradhan33e3baa2022-12-06 20:30:22 +00001367 if (!windowAcceptsTouchAt(info, displayId, x, y, isStylus, getTransformLocked(displayId))) {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001368 continue;
1369 }
1370 if (!info.isSpy()) {
1371 // The first touched non-spy window was found, so return the spy windows touched so far.
1372 return spyWindows;
1373 }
1374 spyWindows.push_back(windowHandle);
1375 }
1376 return spyWindows;
1377}
1378
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001379void InputDispatcher::dropInboundEventLocked(const EventEntry& entry, DropReason dropReason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001380 const char* reason;
1381 switch (dropReason) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001382 case DropReason::POLICY:
Prabir Pradhan65613802023-02-22 23:36:58 +00001383 if (debugInboundEventDetails()) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001384 ALOGD("Dropped event because policy consumed it.");
1385 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001386 reason = "inbound event was dropped because the policy consumed it";
1387 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001388 case DropReason::DISABLED:
1389 if (mLastDropReason != DropReason::DISABLED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001390 ALOGI("Dropped event because input dispatch is disabled.");
1391 }
1392 reason = "inbound event was dropped because input dispatch is disabled";
1393 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001394 case DropReason::BLOCKED:
Siarhei Vishniakou99e407b2023-12-26 18:09:32 -08001395 LOG(INFO) << "Dropping because the current application is not responding and the user "
1396 "has started interacting with a different application: "
1397 << entry.getDescription();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001398 reason = "inbound event was dropped because the current application is not responding "
1399 "and the user has started interacting with a different application";
1400 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001401 case DropReason::STALE:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001402 ALOGI("Dropped event because it is stale.");
1403 reason = "inbound event was dropped because it is stale";
1404 break;
Prabir Pradhan99987712020-11-10 18:43:05 -08001405 case DropReason::NO_POINTER_CAPTURE:
1406 ALOGI("Dropped event because there is no window with Pointer Capture.");
1407 reason = "inbound event was dropped because there is no window with Pointer Capture";
1408 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001409 case DropReason::NOT_DROPPED: {
1410 LOG_ALWAYS_FATAL("Should not be dropping a NOT_DROPPED event");
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001411 return;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001412 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001413 }
1414
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001415 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001416 case EventEntry::Type::KEY: {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001417 CancelationOptions options(CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS, reason);
Hu Guo3cfa7382023-11-15 09:50:04 +00001418 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
1419 options.displayId = keyEntry.displayId;
1420 options.deviceId = keyEntry.deviceId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001421 synthesizeCancelationEventsForAllConnectionsLocked(options);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001422 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001423 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001424 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001425 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
1426 if (motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001427 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS, reason);
Hu Guo3cfa7382023-11-15 09:50:04 +00001428 options.displayId = motionEntry.displayId;
1429 options.deviceId = motionEntry.deviceId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001430 synthesizeCancelationEventsForAllConnectionsLocked(options);
1431 } else {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001432 CancelationOptions options(CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS,
1433 reason);
Hu Guo3cfa7382023-11-15 09:50:04 +00001434 options.displayId = motionEntry.displayId;
1435 options.deviceId = motionEntry.deviceId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001436 synthesizeCancelationEventsForAllConnectionsLocked(options);
1437 }
1438 break;
1439 }
Chris Yef59a2f42020-10-16 12:55:26 -07001440 case EventEntry::Type::SENSOR: {
1441 break;
1442 }
arthurhungb89ccb02020-12-30 16:19:01 +08001443 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
1444 case EventEntry::Type::DRAG: {
Prabir Pradhan99987712020-11-10 18:43:05 -08001445 break;
1446 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001447 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001448 case EventEntry::Type::TOUCH_MODE_CHANGED:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001449 case EventEntry::Type::CONFIGURATION_CHANGED:
1450 case EventEntry::Type::DEVICE_RESET: {
Dominik Laskowski75788452021-02-09 18:51:25 -08001451 LOG_ALWAYS_FATAL("Should not drop %s events", ftl::enum_string(entry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001452 break;
1453 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001454 }
1455}
1456
Michael Wrightd02c5b62014-02-10 15:10:22 -08001457bool InputDispatcher::haveCommandsLocked() const {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001458 return !mCommandQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001459}
1460
Prabir Pradhancef936d2021-07-21 16:17:52 +00001461bool InputDispatcher::runCommandsLockedInterruptable() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001462 if (mCommandQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001463 return false;
1464 }
1465
1466 do {
Prabir Pradhancef936d2021-07-21 16:17:52 +00001467 auto command = std::move(mCommandQueue.front());
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001468 mCommandQueue.pop_front();
Prabir Pradhancef936d2021-07-21 16:17:52 +00001469 // Commands are run with the lock held, but may release and re-acquire the lock from within.
1470 command();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001471 } while (!mCommandQueue.empty());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001472 return true;
1473}
1474
Prabir Pradhancef936d2021-07-21 16:17:52 +00001475void InputDispatcher::postCommandLocked(Command&& command) {
1476 mCommandQueue.push_back(command);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001477}
1478
1479void InputDispatcher::drainInboundQueueLocked() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001480 while (!mInboundQueue.empty()) {
Prabir Pradhan24047542023-11-02 17:14:59 +00001481 std::shared_ptr<const EventEntry> entry = mInboundQueue.front();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001482 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001483 releaseInboundEventLocked(entry);
1484 }
1485 traceInboundQueueLengthLocked();
1486}
1487
1488void InputDispatcher::releasePendingEventLocked() {
1489 if (mPendingEvent) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001490 releaseInboundEventLocked(mPendingEvent);
Yi Kong9b14ac62018-07-17 13:48:38 -07001491 mPendingEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001492 }
1493}
1494
Prabir Pradhan24047542023-11-02 17:14:59 +00001495void InputDispatcher::releaseInboundEventLocked(std::shared_ptr<const EventEntry> entry) {
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00001496 const std::shared_ptr<InjectionState>& injectionState = entry->injectionState;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001497 if (injectionState && injectionState->injectionResult == InputEventInjectionResult::PENDING) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001498 if (DEBUG_DISPATCH_CYCLE) {
1499 ALOGD("Injected inbound event was dropped.");
1500 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001501 setInjectionResult(*entry, InputEventInjectionResult::FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001502 }
1503 if (entry == mNextUnblockedEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001504 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001505 }
1506 addRecentEventLocked(entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001507}
1508
1509void InputDispatcher::resetKeyRepeatLocked() {
1510 if (mKeyRepeatState.lastKeyEntry) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001511 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001512 }
1513}
1514
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001515std::shared_ptr<KeyEntry> InputDispatcher::synthesizeKeyRepeatLocked(nsecs_t currentTime) {
Prabir Pradhan24047542023-11-02 17:14:59 +00001516 std::shared_ptr<const KeyEntry> entry = mKeyRepeatState.lastKeyEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001517
Michael Wright2e732952014-09-24 13:26:59 -07001518 uint32_t policyFlags = entry->policyFlags &
1519 (POLICY_FLAG_RAW_MASK | POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_TRUSTED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001520
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001521 std::shared_ptr<KeyEntry> newEntry =
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00001522 std::make_unique<KeyEntry>(mIdGenerator.nextId(), /*injectionState=*/nullptr,
1523 currentTime, entry->deviceId, entry->source,
1524 entry->displayId, policyFlags, entry->action, entry->flags,
1525 entry->keyCode, entry->scanCode, entry->metaState,
1526 entry->repeatCount + 1, entry->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001527
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001528 newEntry->syntheticRepeat = true;
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00001529 if (mTracer) {
1530 newEntry->traceTracker = mTracer->traceInboundEvent(*newEntry);
1531 }
1532
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001533 mKeyRepeatState.lastKeyEntry = newEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001534 mKeyRepeatState.nextRepeatTime = currentTime + mConfig.keyRepeatDelay;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001535 return newEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001536}
1537
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001538bool InputDispatcher::dispatchConfigurationChangedLocked(nsecs_t currentTime,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001539 const ConfigurationChangedEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001540 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1541 ALOGD("dispatchConfigurationChanged - eventTime=%" PRId64, entry.eventTime);
1542 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001543
1544 // Reset key repeating in case a keyboard device was added or removed or something.
1545 resetKeyRepeatLocked();
1546
1547 // Enqueue a command to run outside the lock to tell the policy that the configuration changed.
Prabir Pradhancef936d2021-07-21 16:17:52 +00001548 auto command = [this, eventTime = entry.eventTime]() REQUIRES(mLock) {
1549 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00001550 mPolicy.notifyConfigurationChanged(eventTime);
Prabir Pradhancef936d2021-07-21 16:17:52 +00001551 };
1552 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001553 return true;
1554}
1555
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001556bool InputDispatcher::dispatchDeviceResetLocked(nsecs_t currentTime,
1557 const DeviceResetEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001558 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1559 ALOGD("dispatchDeviceReset - eventTime=%" PRId64 ", deviceId=%d", entry.eventTime,
1560 entry.deviceId);
1561 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001562
liushenxiang42232912021-05-21 20:24:09 +08001563 // Reset key repeating in case a keyboard device was disabled or enabled.
1564 if (mKeyRepeatState.lastKeyEntry && mKeyRepeatState.lastKeyEntry->deviceId == entry.deviceId) {
1565 resetKeyRepeatLocked();
1566 }
1567
Michael Wrightfb04fd52022-11-24 22:31:11 +00001568 CancelationOptions options(CancelationOptions::Mode::CANCEL_ALL_EVENTS, "device was reset");
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001569 options.deviceId = entry.deviceId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001570 synthesizeCancelationEventsForAllConnectionsLocked(options);
Siarhei Vishniakou0686f0c2023-05-02 11:56:15 -07001571
1572 // Remove all active pointers from this device
1573 for (auto& [_, touchState] : mTouchStatesByDisplay) {
1574 touchState.removeAllPointersForDevice(entry.deviceId);
1575 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001576 return true;
1577}
1578
Vishnu Nairad321cd2020-08-20 16:40:21 -07001579void InputDispatcher::enqueueFocusEventLocked(const sp<IBinder>& windowToken, bool hasFocus,
Vishnu Nairc519ff72021-01-21 08:23:08 -08001580 const std::string& reason) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001581 if (mPendingEvent != nullptr) {
1582 // Move the pending event to the front of the queue. This will give the chance
1583 // for the pending event to get dispatched to the newly focused window
1584 mInboundQueue.push_front(mPendingEvent);
1585 mPendingEvent = nullptr;
1586 }
1587
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001588 std::unique_ptr<FocusEntry> focusEntry =
1589 std::make_unique<FocusEntry>(mIdGenerator.nextId(), now(), windowToken, hasFocus,
1590 reason);
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001591
1592 // This event should go to the front of the queue, but behind all other focus events
1593 // Find the last focus event, and insert right after it
Prabir Pradhan24047542023-11-02 17:14:59 +00001594 auto it = std::find_if(mInboundQueue.rbegin(), mInboundQueue.rend(),
1595 [](const std::shared_ptr<const EventEntry>& event) {
1596 return event->type == EventEntry::Type::FOCUS;
1597 });
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001598
1599 // Maintain the order of focus events. Insert the entry after all other focus events.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001600 mInboundQueue.insert(it.base(), std::move(focusEntry));
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001601}
1602
Prabir Pradhan24047542023-11-02 17:14:59 +00001603void InputDispatcher::dispatchFocusLocked(nsecs_t currentTime,
1604 std::shared_ptr<const FocusEntry> entry) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05001605 std::shared_ptr<InputChannel> channel = getInputChannelLocked(entry->connectionToken);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001606 if (channel == nullptr) {
1607 return; // Window has gone away
1608 }
1609 InputTarget target;
1610 target.inputChannel = channel;
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001611 entry->dispatchInProgress = true;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00001612 std::string message = std::string("Focus ") + (entry->hasFocus ? "entering " : "leaving ") +
1613 channel->getName();
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07001614 std::string reason = std::string("reason=").append(entry->reason);
1615 android_log_event_list(LOGTAG_INPUT_FOCUS) << message << reason << LOG_ID_EVENTS;
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001616 dispatchEventLocked(currentTime, entry, {target});
1617}
1618
Prabir Pradhan99987712020-11-10 18:43:05 -08001619void InputDispatcher::dispatchPointerCaptureChangedLocked(
Prabir Pradhan24047542023-11-02 17:14:59 +00001620 nsecs_t currentTime, const std::shared_ptr<const PointerCaptureChangedEntry>& entry,
Prabir Pradhan99987712020-11-10 18:43:05 -08001621 DropReason& dropReason) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001622 dropReason = DropReason::NOT_DROPPED;
1623
Prabir Pradhan99987712020-11-10 18:43:05 -08001624 const bool haveWindowWithPointerCapture = mWindowTokenWithPointerCapture != nullptr;
Prabir Pradhan99987712020-11-10 18:43:05 -08001625 sp<IBinder> token;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001626
1627 if (entry->pointerCaptureRequest.enable) {
1628 // Enable Pointer Capture.
1629 if (haveWindowWithPointerCapture &&
1630 (entry->pointerCaptureRequest == mCurrentPointerCaptureRequest)) {
Prabir Pradhan7092e262022-05-03 16:51:09 +00001631 // This can happen if pointer capture is disabled and re-enabled before we notify the
1632 // app of the state change, so there is no need to notify the app.
1633 ALOGI("Skipping dispatch of Pointer Capture being enabled: no state change.");
1634 return;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001635 }
1636 if (!mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08001637 // This can happen if a window requests capture and immediately releases capture.
1638 ALOGW("No window requested Pointer Capture.");
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001639 dropReason = DropReason::NO_POINTER_CAPTURE;
Prabir Pradhan99987712020-11-10 18:43:05 -08001640 return;
1641 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001642 if (entry->pointerCaptureRequest.seq != mCurrentPointerCaptureRequest.seq) {
1643 ALOGI("Skipping dispatch of Pointer Capture being enabled: sequence number mismatch.");
1644 return;
1645 }
1646
Vishnu Nairc519ff72021-01-21 08:23:08 -08001647 token = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Prabir Pradhan99987712020-11-10 18:43:05 -08001648 LOG_ALWAYS_FATAL_IF(!token, "Cannot find focused window for Pointer Capture.");
1649 mWindowTokenWithPointerCapture = token;
1650 } else {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001651 // Disable Pointer Capture.
1652 // We do not check if the sequence number matches for requests to disable Pointer Capture
1653 // for two reasons:
1654 // 1. Pointer Capture can be disabled by a focus change, which means we can get two entries
1655 // to disable capture with the same sequence number: one generated by
1656 // disablePointerCaptureForcedLocked() and another as an acknowledgement of Pointer
1657 // Capture being disabled in InputReader.
1658 // 2. We respect any request to disable Pointer Capture generated by InputReader, since the
1659 // actual Pointer Capture state that affects events being generated by input devices is
1660 // in InputReader.
1661 if (!haveWindowWithPointerCapture) {
1662 // Pointer capture was already forcefully disabled because of focus change.
1663 dropReason = DropReason::NOT_DROPPED;
1664 return;
1665 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001666 token = mWindowTokenWithPointerCapture;
1667 mWindowTokenWithPointerCapture = nullptr;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001668 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan7d030382020-12-21 07:58:35 -08001669 setPointerCaptureLocked(false);
1670 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001671 }
1672
1673 auto channel = getInputChannelLocked(token);
1674 if (channel == nullptr) {
1675 // Window has gone away, clean up Pointer Capture state.
1676 mWindowTokenWithPointerCapture = nullptr;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001677 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan7d030382020-12-21 07:58:35 -08001678 setPointerCaptureLocked(false);
1679 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001680 return;
1681 }
1682 InputTarget target;
1683 target.inputChannel = channel;
Prabir Pradhan99987712020-11-10 18:43:05 -08001684 entry->dispatchInProgress = true;
1685 dispatchEventLocked(currentTime, entry, {target});
1686
1687 dropReason = DropReason::NOT_DROPPED;
1688}
1689
Prabir Pradhan24047542023-11-02 17:14:59 +00001690void InputDispatcher::dispatchTouchModeChangeLocked(
1691 nsecs_t currentTime, const std::shared_ptr<const TouchModeEntry>& entry) {
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001692 const std::vector<sp<WindowInfoHandle>>& windowHandles =
Antonio Kantek15beb512022-06-13 22:35:41 +00001693 getWindowHandlesLocked(entry->displayId);
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001694 if (windowHandles.empty()) {
1695 return;
1696 }
1697 const std::vector<InputTarget> inputTargets =
1698 getInputTargetsFromWindowHandlesLocked(windowHandles);
1699 if (inputTargets.empty()) {
1700 return;
1701 }
1702 entry->dispatchInProgress = true;
1703 dispatchEventLocked(currentTime, entry, inputTargets);
1704}
1705
1706std::vector<InputTarget> InputDispatcher::getInputTargetsFromWindowHandlesLocked(
1707 const std::vector<sp<WindowInfoHandle>>& windowHandles) const {
1708 std::vector<InputTarget> inputTargets;
1709 for (const sp<WindowInfoHandle>& handle : windowHandles) {
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001710 const sp<IBinder>& token = handle->getToken();
1711 if (token == nullptr) {
1712 continue;
1713 }
1714 std::shared_ptr<InputChannel> channel = getInputChannelLocked(token);
1715 if (channel == nullptr) {
1716 continue; // Window has gone away
1717 }
1718 InputTarget target;
1719 target.inputChannel = channel;
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001720 inputTargets.push_back(target);
1721 }
1722 return inputTargets;
1723}
1724
Prabir Pradhan24047542023-11-02 17:14:59 +00001725bool InputDispatcher::dispatchKeyLocked(nsecs_t currentTime, std::shared_ptr<const KeyEntry> entry,
Siarhei Vishniakou69505962023-12-28 12:07:04 -08001726 DropReason* dropReason, nsecs_t& nextWakeupTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001727 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001728 if (!entry->dispatchInProgress) {
1729 if (entry->repeatCount == 0 && entry->action == AKEY_EVENT_ACTION_DOWN &&
1730 (entry->policyFlags & POLICY_FLAG_TRUSTED) &&
1731 (!(entry->policyFlags & POLICY_FLAG_DISABLE_KEY_REPEAT))) {
1732 if (mKeyRepeatState.lastKeyEntry &&
Chris Ye2ad95392020-09-01 13:44:44 -07001733 mKeyRepeatState.lastKeyEntry->keyCode == entry->keyCode &&
Michael Wrightd02c5b62014-02-10 15:10:22 -08001734 // We have seen two identical key downs in a row which indicates that the device
1735 // driver is automatically generating key repeats itself. We take note of the
1736 // repeat here, but we disable our own next key repeat timer since it is clear that
1737 // we will not need to synthesize key repeats ourselves.
Chris Ye2ad95392020-09-01 13:44:44 -07001738 mKeyRepeatState.lastKeyEntry->deviceId == entry->deviceId) {
1739 // Make sure we don't get key down from a different device. If a different
1740 // device Id has same key pressed down, the new device Id will replace the
1741 // current one to hold the key repeat with repeat count reset.
1742 // In the future when got a KEY_UP on the device id, drop it and do not
1743 // stop the key repeat on current device.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001744 entry->repeatCount = mKeyRepeatState.lastKeyEntry->repeatCount + 1;
1745 resetKeyRepeatLocked();
Colin Cross5b799302022-10-18 21:52:41 -07001746 mKeyRepeatState.nextRepeatTime = LLONG_MAX; // don't generate repeats ourselves
Michael Wrightd02c5b62014-02-10 15:10:22 -08001747 } else {
1748 // Not a repeat. Save key down state in case we do see a repeat later.
1749 resetKeyRepeatLocked();
1750 mKeyRepeatState.nextRepeatTime = entry->eventTime + mConfig.keyRepeatTimeout;
1751 }
1752 mKeyRepeatState.lastKeyEntry = entry;
Chris Ye2ad95392020-09-01 13:44:44 -07001753 } else if (entry->action == AKEY_EVENT_ACTION_UP && mKeyRepeatState.lastKeyEntry &&
1754 mKeyRepeatState.lastKeyEntry->deviceId != entry->deviceId) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001755 // The key on device 'deviceId' is still down, do not stop key repeat
Prabir Pradhan65613802023-02-22 23:36:58 +00001756 if (debugInboundEventDetails()) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001757 ALOGD("deviceId=%d got KEY_UP as stale", entry->deviceId);
1758 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001759 } else if (!entry->syntheticRepeat) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001760 resetKeyRepeatLocked();
1761 }
1762
1763 if (entry->repeatCount == 1) {
1764 entry->flags |= AKEY_EVENT_FLAG_LONG_PRESS;
1765 } else {
1766 entry->flags &= ~AKEY_EVENT_FLAG_LONG_PRESS;
1767 }
1768
1769 entry->dispatchInProgress = true;
1770
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001771 logOutboundKeyDetails("dispatchKey - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001772 }
1773
1774 // Handle case where the policy asked us to try again later last time.
Michael Wright5caf55a2022-11-24 22:31:42 +00001775 if (entry->interceptKeyResult == KeyEntry::InterceptKeyResult::TRY_AGAIN_LATER) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001776 if (currentTime < entry->interceptKeyWakeupTime) {
Siarhei Vishniakou69505962023-12-28 12:07:04 -08001777 nextWakeupTime = std::min(nextWakeupTime, entry->interceptKeyWakeupTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001778 return false; // wait until next wakeup
1779 }
Michael Wright5caf55a2022-11-24 22:31:42 +00001780 entry->interceptKeyResult = KeyEntry::InterceptKeyResult::UNKNOWN;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001781 entry->interceptKeyWakeupTime = 0;
1782 }
1783
1784 // Give the policy a chance to intercept the key.
Michael Wright5caf55a2022-11-24 22:31:42 +00001785 if (entry->interceptKeyResult == KeyEntry::InterceptKeyResult::UNKNOWN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001786 if (entry->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07001787 sp<IBinder> focusedWindowToken =
Vishnu Nairc519ff72021-01-21 08:23:08 -08001788 mFocusResolver.getFocusedWindowToken(getTargetDisplayId(*entry));
Prabir Pradhancef936d2021-07-21 16:17:52 +00001789
1790 auto command = [this, focusedWindowToken, entry]() REQUIRES(mLock) {
1791 doInterceptKeyBeforeDispatchingCommand(focusedWindowToken, *entry);
1792 };
1793 postCommandLocked(std::move(command));
Josep del Riob3981622023-04-18 15:49:45 +00001794 // Poke user activity for keys not passed to user
1795 pokeUserActivityLocked(*entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001796 return false; // wait for the command to run
1797 } else {
Michael Wright5caf55a2022-11-24 22:31:42 +00001798 entry->interceptKeyResult = KeyEntry::InterceptKeyResult::CONTINUE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001799 }
Michael Wright5caf55a2022-11-24 22:31:42 +00001800 } else if (entry->interceptKeyResult == KeyEntry::InterceptKeyResult::SKIP) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001801 if (*dropReason == DropReason::NOT_DROPPED) {
1802 *dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001803 }
1804 }
1805
1806 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001807 if (*dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001808 setInjectionResult(*entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001809 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
1810 : InputEventInjectionResult::FAILED);
Garfield Tan6a5a14e2020-01-28 13:24:04 -08001811 mReporter->reportDroppedKey(entry->id);
Josep del Riob3981622023-04-18 15:49:45 +00001812 // Poke user activity for undispatched keys
1813 pokeUserActivityLocked(*entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001814 return true;
1815 }
1816
1817 // Identify targets.
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001818 InputEventInjectionResult injectionResult;
1819 sp<WindowInfoHandle> focusedWindow =
1820 findFocusedWindowTargetLocked(currentTime, *entry, nextWakeupTime,
1821 /*byref*/ injectionResult);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001822 if (injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001823 return false;
1824 }
1825
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001826 setInjectionResult(*entry, injectionResult);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001827 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001828 return true;
1829 }
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001830 LOG_ALWAYS_FATAL_IF(focusedWindow == nullptr);
1831
1832 std::vector<InputTarget> inputTargets;
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00001833 addWindowTargetLocked(focusedWindow, InputTarget::DispatchMode::AS_IS,
1834 InputTarget::Flags::FOREGROUND, getDownTime(*entry), inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001835
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001836 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001837 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001838
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00001839 if (mTracer) {
1840 ensureEventTraced(*entry);
1841 for (const auto& target : inputTargets) {
1842 mTracer->dispatchToTargetHint(*entry->traceTracker, target);
1843 }
1844 }
1845
Michael Wrightd02c5b62014-02-10 15:10:22 -08001846 // Dispatch the key.
1847 dispatchEventLocked(currentTime, entry, inputTargets);
1848 return true;
1849}
1850
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001851void InputDispatcher::logOutboundKeyDetails(const char* prefix, const KeyEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001852 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1853 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32 ", "
1854 "policyFlags=0x%x, action=0x%x, flags=0x%x, keyCode=0x%x, scanCode=0x%x, "
1855 "metaState=0x%x, repeatCount=%d, downTime=%" PRId64,
1856 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId,
1857 entry.policyFlags, entry.action, entry.flags, entry.keyCode, entry.scanCode,
1858 entry.metaState, entry.repeatCount, entry.downTime);
1859 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001860}
1861
Prabir Pradhancef936d2021-07-21 16:17:52 +00001862void InputDispatcher::dispatchSensorLocked(nsecs_t currentTime,
Prabir Pradhan24047542023-11-02 17:14:59 +00001863 const std::shared_ptr<const SensorEntry>& entry,
Siarhei Vishniakou69505962023-12-28 12:07:04 -08001864 DropReason* dropReason, nsecs_t& nextWakeupTime) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001865 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1866 ALOGD("notifySensorEvent eventTime=%" PRId64 ", hwTimestamp=%" PRId64 ", deviceId=%d, "
1867 "source=0x%x, sensorType=%s",
1868 entry->eventTime, entry->hwTimestamp, entry->deviceId, entry->source,
Dominik Laskowski75788452021-02-09 18:51:25 -08001869 ftl::enum_string(entry->sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001870 }
Prabir Pradhancef936d2021-07-21 16:17:52 +00001871 auto command = [this, entry]() REQUIRES(mLock) {
1872 scoped_unlock unlock(mLock);
1873
1874 if (entry->accuracyChanged) {
Prabir Pradhana41d2442023-04-20 21:30:40 +00001875 mPolicy.notifySensorAccuracy(entry->deviceId, entry->sensorType, entry->accuracy);
Prabir Pradhancef936d2021-07-21 16:17:52 +00001876 }
Prabir Pradhana41d2442023-04-20 21:30:40 +00001877 mPolicy.notifySensorEvent(entry->deviceId, entry->sensorType, entry->accuracy,
1878 entry->hwTimestamp, entry->values);
Prabir Pradhancef936d2021-07-21 16:17:52 +00001879 };
1880 postCommandLocked(std::move(command));
Chris Yef59a2f42020-10-16 12:55:26 -07001881}
1882
1883bool InputDispatcher::flushSensor(int deviceId, InputDeviceSensorType sensorType) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001884 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1885 ALOGD("flushSensor deviceId=%d, sensorType=%s", deviceId,
Dominik Laskowski75788452021-02-09 18:51:25 -08001886 ftl::enum_string(sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001887 }
Chris Yef59a2f42020-10-16 12:55:26 -07001888 { // acquire lock
1889 std::scoped_lock _l(mLock);
1890
1891 for (auto it = mInboundQueue.begin(); it != mInboundQueue.end(); it++) {
Prabir Pradhan24047542023-11-02 17:14:59 +00001892 std::shared_ptr<const EventEntry> entry = *it;
Chris Yef59a2f42020-10-16 12:55:26 -07001893 if (entry->type == EventEntry::Type::SENSOR) {
1894 it = mInboundQueue.erase(it);
1895 releaseInboundEventLocked(entry);
1896 }
1897 }
1898 }
1899 return true;
1900}
1901
Prabir Pradhan24047542023-11-02 17:14:59 +00001902bool InputDispatcher::dispatchMotionLocked(nsecs_t currentTime,
1903 std::shared_ptr<const MotionEntry> entry,
Siarhei Vishniakou69505962023-12-28 12:07:04 -08001904 DropReason* dropReason, nsecs_t& nextWakeupTime) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001905 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001906 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001907 if (!entry->dispatchInProgress) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001908 entry->dispatchInProgress = true;
1909
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001910 logOutboundMotionDetails("dispatchMotion - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001911 }
1912
1913 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001914 if (*dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001915 setInjectionResult(*entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001916 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
1917 : InputEventInjectionResult::FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001918 return true;
1919 }
1920
Prabir Pradhanaa561d12021-09-24 06:57:33 -07001921 const bool isPointerEvent = isFromSource(entry->source, AINPUT_SOURCE_CLASS_POINTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001922
1923 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001924 std::vector<InputTarget> inputTargets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001925
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001926 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001927 if (isPointerEvent) {
1928 // Pointer event. (eg. touchscreen)
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00001929
1930 if (mDragState &&
1931 (entry->action & AMOTION_EVENT_ACTION_MASK) == AMOTION_EVENT_ACTION_POINTER_DOWN) {
1932 // If drag and drop ongoing and pointer down occur: pilfer drag window pointers
1933 pilferPointersLocked(mDragState->dragWindow->getToken());
1934 }
1935
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08001936 inputTargets =
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07001937 findTouchedWindowTargetsLocked(currentTime, *entry, /*byref*/ injectionResult);
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08001938 LOG_ALWAYS_FATAL_IF(injectionResult != InputEventInjectionResult::SUCCEEDED &&
1939 !inputTargets.empty());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001940 } else {
1941 // Non touch event. (eg. trackball)
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001942 sp<WindowInfoHandle> focusedWindow =
1943 findFocusedWindowTargetLocked(currentTime, *entry, nextWakeupTime, injectionResult);
1944 if (injectionResult == InputEventInjectionResult::SUCCEEDED) {
1945 LOG_ALWAYS_FATAL_IF(focusedWindow == nullptr);
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00001946 addWindowTargetLocked(focusedWindow, InputTarget::DispatchMode::AS_IS,
1947 InputTarget::Flags::FOREGROUND, getDownTime(*entry),
1948 inputTargets);
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001949 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001950 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001951 if (injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001952 return false;
1953 }
1954
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001955 setInjectionResult(*entry, injectionResult);
Prabir Pradhan5735a322022-04-11 17:23:34 +00001956 if (injectionResult == InputEventInjectionResult::TARGET_MISMATCH) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001957 return true;
1958 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001959 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001960 CancelationOptions::Mode mode(
1961 isPointerEvent ? CancelationOptions::Mode::CANCEL_POINTER_EVENTS
1962 : CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS);
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001963 CancelationOptions options(mode, "input event injection failed");
1964 synthesizeCancelationEventsForMonitorsLocked(options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001965 return true;
1966 }
1967
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001968 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001969 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001970
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00001971 if (mTracer) {
1972 ensureEventTraced(*entry);
1973 for (const auto& target : inputTargets) {
1974 mTracer->dispatchToTargetHint(*entry->traceTracker, target);
1975 }
1976 }
1977
Michael Wrightd02c5b62014-02-10 15:10:22 -08001978 // Dispatch the motion.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001979 dispatchEventLocked(currentTime, entry, inputTargets);
1980 return true;
1981}
1982
chaviw98318de2021-05-19 16:45:23 -05001983void InputDispatcher::enqueueDragEventLocked(const sp<WindowInfoHandle>& windowHandle,
Arthur Hung54745652022-04-20 07:17:41 +00001984 bool isExiting, const int32_t rawX,
1985 const int32_t rawY) {
1986 const vec2 xy = windowHandle->getInfo()->transform.transform(vec2(rawX, rawY));
arthurhungb89ccb02020-12-30 16:19:01 +08001987 std::unique_ptr<DragEntry> dragEntry =
Arthur Hung54745652022-04-20 07:17:41 +00001988 std::make_unique<DragEntry>(mIdGenerator.nextId(), now(), windowHandle->getToken(),
1989 isExiting, xy.x, xy.y);
arthurhungb89ccb02020-12-30 16:19:01 +08001990
1991 enqueueInboundEventLocked(std::move(dragEntry));
1992}
1993
Prabir Pradhan24047542023-11-02 17:14:59 +00001994void InputDispatcher::dispatchDragLocked(nsecs_t currentTime,
1995 std::shared_ptr<const DragEntry> entry) {
arthurhungb89ccb02020-12-30 16:19:01 +08001996 std::shared_ptr<InputChannel> channel = getInputChannelLocked(entry->connectionToken);
1997 if (channel == nullptr) {
1998 return; // Window has gone away
1999 }
2000 InputTarget target;
2001 target.inputChannel = channel;
arthurhungb89ccb02020-12-30 16:19:01 +08002002 entry->dispatchInProgress = true;
2003 dispatchEventLocked(currentTime, entry, {target});
2004}
2005
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002006void InputDispatcher::logOutboundMotionDetails(const char* prefix, const MotionEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002007 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -08002008 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=%s, displayId=%" PRId32
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002009 ", policyFlags=0x%x, "
Siarhei Vishniakouca205502021-07-16 21:31:58 +00002010 "action=%s, actionButton=0x%x, flags=0x%x, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002011 "metaState=0x%x, buttonState=0x%x,"
2012 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%" PRId64,
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -08002013 prefix, entry.eventTime, entry.deviceId,
2014 inputEventSourceToString(entry.source).c_str(), entry.displayId, entry.policyFlags,
2015 MotionEvent::actionToString(entry.action).c_str(), entry.actionButton, entry.flags,
2016 entry.metaState, entry.buttonState, entry.edgeFlags, entry.xPrecision,
2017 entry.yPrecision, entry.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002018
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07002019 for (uint32_t i = 0; i < entry.getPointerCount(); i++) {
Siarhei Vishniakou09a8fe42022-07-21 17:27:03 -07002020 ALOGD(" Pointer %d: id=%d, toolType=%s, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002021 "x=%f, y=%f, pressure=%f, size=%f, "
2022 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
2023 "orientation=%f",
Siarhei Vishniakou09a8fe42022-07-21 17:27:03 -07002024 i, entry.pointerProperties[i].id,
2025 ftl::enum_string(entry.pointerProperties[i].toolType).c_str(),
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002026 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
2027 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
2028 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
2029 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
2030 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
2031 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
2032 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
2033 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
2034 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
2035 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002036 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002037}
2038
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002039void InputDispatcher::dispatchEventLocked(nsecs_t currentTime,
Prabir Pradhan24047542023-11-02 17:14:59 +00002040 std::shared_ptr<const EventEntry> eventEntry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002041 const std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002042 ATRACE_CALL();
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002043 if (DEBUG_DISPATCH_CYCLE) {
2044 ALOGD("dispatchEventToCurrentInputTargets");
2045 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002046
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00002047 processInteractionsLocked(*eventEntry, inputTargets);
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00002048
Michael Wrightd02c5b62014-02-10 15:10:22 -08002049 ALOG_ASSERT(eventEntry->dispatchInProgress); // should already have been set to true
2050
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002051 pokeUserActivityLocked(*eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002052
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002053 for (const InputTarget& inputTarget : inputTargets) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07002054 std::shared_ptr<Connection> connection =
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07002055 getConnectionLocked(inputTarget.inputChannel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07002056 if (connection != nullptr) {
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002057 prepareDispatchCycleLocked(currentTime, connection, eventEntry, inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002058 } else {
Siarhei Vishniakou31dd1552023-10-30 18:46:10 -07002059 if (DEBUG_DROPPED_EVENTS_VERBOSE) {
2060 LOG(INFO) << "Dropping event delivery to target with channel "
2061 << inputTarget.inputChannel->getName()
2062 << " because it is no longer registered with the input dispatcher.";
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002063 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002064 }
2065 }
2066}
2067
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07002068void InputDispatcher::cancelEventsForAnrLocked(const std::shared_ptr<Connection>& connection) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002069 // We will not be breaking any connections here, even if the policy wants us to abort dispatch.
2070 // If the policy decides to close the app, we will get a channel removal event via
2071 // unregisterInputChannel, and will clean up the connection that way. We are already not
2072 // sending new pointers to the connection when it blocked, but focused events will continue to
2073 // pile up.
2074 ALOGW("Canceling events for %s because it is unresponsive",
2075 connection->inputChannel->getName().c_str());
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08002076 if (connection->status == Connection::Status::NORMAL) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00002077 CancelationOptions options(CancelationOptions::Mode::CANCEL_ALL_EVENTS,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002078 "application not responding");
2079 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002080 }
2081}
2082
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002083void InputDispatcher::resetNoFocusedWindowTimeoutLocked() {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002084 if (DEBUG_FOCUS) {
2085 ALOGD("Resetting ANR timeouts.");
2086 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002087
2088 // Reset input target wait timeout.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002089 mNoFocusedWindowTimeoutTime = std::nullopt;
Chris Yea209fde2020-07-22 13:54:51 -07002090 mAwaitedFocusedApplication.reset();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002091}
2092
Tiger Huang721e26f2018-07-24 22:26:19 +08002093/**
2094 * Get the display id that the given event should go to. If this event specifies a valid display id,
2095 * then it should be dispatched to that display. Otherwise, the event goes to the focused display.
2096 * Focused display is the display that the user most recently interacted with.
2097 */
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002098int32_t InputDispatcher::getTargetDisplayId(const EventEntry& entry) {
Tiger Huang721e26f2018-07-24 22:26:19 +08002099 int32_t displayId;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002100 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002101 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002102 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
2103 displayId = keyEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002104 break;
2105 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002106 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002107 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
2108 displayId = motionEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002109 break;
2110 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00002111 case EventEntry::Type::TOUCH_MODE_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08002112 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002113 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002114 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07002115 case EventEntry::Type::DEVICE_RESET:
arthurhungb89ccb02020-12-30 16:19:01 +08002116 case EventEntry::Type::SENSOR:
2117 case EventEntry::Type::DRAG: {
Dominik Laskowski75788452021-02-09 18:51:25 -08002118 ALOGE("%s events do not have a target display", ftl::enum_string(entry.type).c_str());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002119 return ADISPLAY_ID_NONE;
2120 }
Tiger Huang721e26f2018-07-24 22:26:19 +08002121 }
2122 return displayId == ADISPLAY_ID_NONE ? mFocusedDisplayId : displayId;
2123}
2124
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002125bool InputDispatcher::shouldWaitToSendKeyLocked(nsecs_t currentTime,
2126 const char* focusedWindowName) {
2127 if (mAnrTracker.empty()) {
2128 // already processed all events that we waited for
2129 mKeyIsWaitingForEventsTimeout = std::nullopt;
2130 return false;
2131 }
2132
2133 if (!mKeyIsWaitingForEventsTimeout.has_value()) {
2134 // Start the timer
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00002135 // Wait to send key because there are unprocessed events that may cause focus to change
Siarhei Vishniakou70622952020-07-30 11:17:23 -05002136 mKeyIsWaitingForEventsTimeout = currentTime +
2137 std::chrono::duration_cast<std::chrono::nanoseconds>(KEY_WAITING_FOR_EVENTS_TIMEOUT)
2138 .count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002139 return true;
2140 }
2141
2142 // We still have pending events, and already started the timer
2143 if (currentTime < *mKeyIsWaitingForEventsTimeout) {
2144 return true; // Still waiting
2145 }
2146
2147 // Waited too long, and some connection still hasn't processed all motions
2148 // Just send the key to the focused window
2149 ALOGW("Dispatching key to %s even though there are other unprocessed events",
2150 focusedWindowName);
2151 mKeyIsWaitingForEventsTimeout = std::nullopt;
2152 return false;
2153}
2154
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002155sp<WindowInfoHandle> InputDispatcher::findFocusedWindowTargetLocked(
Siarhei Vishniakou69505962023-12-28 12:07:04 -08002156 nsecs_t currentTime, const EventEntry& entry, nsecs_t& nextWakeupTime,
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002157 InputEventInjectionResult& outInjectionResult) {
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002158 outInjectionResult = InputEventInjectionResult::FAILED; // Default result
Michael Wrightd02c5b62014-02-10 15:10:22 -08002159
Tiger Huang721e26f2018-07-24 22:26:19 +08002160 int32_t displayId = getTargetDisplayId(entry);
chaviw98318de2021-05-19 16:45:23 -05002161 sp<WindowInfoHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Chris Yea209fde2020-07-22 13:54:51 -07002162 std::shared_ptr<InputApplicationHandle> focusedApplicationHandle =
Tiger Huang721e26f2018-07-24 22:26:19 +08002163 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
2164
Michael Wrightd02c5b62014-02-10 15:10:22 -08002165 // If there is no currently focused window and no focused application
2166 // then drop the event.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002167 if (focusedWindowHandle == nullptr && focusedApplicationHandle == nullptr) {
2168 ALOGI("Dropping %s event because there is no focused window or focused application in "
2169 "display %" PRId32 ".",
Dominik Laskowski75788452021-02-09 18:51:25 -08002170 ftl::enum_string(entry.type).c_str(), displayId);
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002171 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002172 }
2173
Vishnu Nair062a8672021-09-03 16:07:44 -07002174 // Drop key events if requested by input feature
2175 if (focusedWindowHandle != nullptr && shouldDropInput(entry, focusedWindowHandle)) {
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002176 return nullptr;
Vishnu Nair062a8672021-09-03 16:07:44 -07002177 }
2178
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002179 // Compatibility behavior: raise ANR if there is a focused application, but no focused window.
2180 // Only start counting when we have a focused event to dispatch. The ANR is canceled if we
2181 // start interacting with another application via touch (app switch). This code can be removed
2182 // if the "no focused window ANR" is moved to the policy. Input doesn't know whether
2183 // an app is expected to have a focused window.
2184 if (focusedWindowHandle == nullptr && focusedApplicationHandle != nullptr) {
2185 if (!mNoFocusedWindowTimeoutTime.has_value()) {
2186 // We just discovered that there's no focused window. Start the ANR timer
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05002187 std::chrono::nanoseconds timeout = focusedApplicationHandle->getDispatchingTimeout(
2188 DEFAULT_INPUT_DISPATCHING_TIMEOUT);
2189 mNoFocusedWindowTimeoutTime = currentTime + timeout.count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002190 mAwaitedFocusedApplication = focusedApplicationHandle;
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05002191 mAwaitedApplicationDisplayId = displayId;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002192 ALOGW("Waiting because no window has focus but %s may eventually add a "
2193 "window when it finishes starting up. Will wait for %" PRId64 "ms",
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05002194 mAwaitedFocusedApplication->getName().c_str(), millis(timeout));
Siarhei Vishniakou69505962023-12-28 12:07:04 -08002195 nextWakeupTime = std::min(nextWakeupTime, *mNoFocusedWindowTimeoutTime);
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002196 outInjectionResult = InputEventInjectionResult::PENDING;
2197 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002198 } else if (currentTime > *mNoFocusedWindowTimeoutTime) {
2199 // Already raised ANR. Drop the event
2200 ALOGE("Dropping %s event because there is no focused window",
Dominik Laskowski75788452021-02-09 18:51:25 -08002201 ftl::enum_string(entry.type).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002202 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002203 } else {
2204 // Still waiting for the focused window
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002205 outInjectionResult = InputEventInjectionResult::PENDING;
2206 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002207 }
2208 }
2209
2210 // we have a valid, non-null focused window
2211 resetNoFocusedWindowTimeoutLocked();
2212
Prabir Pradhan5735a322022-04-11 17:23:34 +00002213 // Verify targeted injection.
2214 if (const auto err = verifyTargetedInjection(focusedWindowHandle, entry); err) {
2215 ALOGW("Dropping injected event: %s", (*err).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002216 outInjectionResult = InputEventInjectionResult::TARGET_MISMATCH;
2217 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002218 }
2219
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002220 if (focusedWindowHandle->getInfo()->inputConfig.test(
2221 WindowInfo::InputConfig::PAUSE_DISPATCHING)) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002222 ALOGI("Waiting because %s is paused", focusedWindowHandle->getName().c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002223 outInjectionResult = InputEventInjectionResult::PENDING;
2224 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002225 }
2226
2227 // If the event is a key event, then we must wait for all previous events to
2228 // complete before delivering it because previous events may have the
2229 // side-effect of transferring focus to a different window and we want to
2230 // ensure that the following keys are sent to the new window.
2231 //
2232 // Suppose the user touches a button in a window then immediately presses "A".
2233 // If the button causes a pop-up window to appear then we want to ensure that
2234 // the "A" key is delivered to the new pop-up window. This is because users
2235 // often anticipate pending UI changes when typing on a keyboard.
2236 // To obtain this behavior, we must serialize key events with respect to all
2237 // prior input events.
2238 if (entry.type == EventEntry::Type::KEY) {
2239 if (shouldWaitToSendKeyLocked(currentTime, focusedWindowHandle->getName().c_str())) {
Siarhei Vishniakou69505962023-12-28 12:07:04 -08002240 nextWakeupTime = std::min(nextWakeupTime, *mKeyIsWaitingForEventsTimeout);
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002241 outInjectionResult = InputEventInjectionResult::PENDING;
2242 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002243 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002244 }
2245
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002246 outInjectionResult = InputEventInjectionResult::SUCCEEDED;
2247 return focusedWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002248}
2249
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002250/**
2251 * Given a list of monitors, remove the ones we cannot find a connection for, and the ones
2252 * that are currently unresponsive.
2253 */
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002254std::vector<Monitor> InputDispatcher::selectResponsiveMonitorsLocked(
2255 const std::vector<Monitor>& monitors) const {
2256 std::vector<Monitor> responsiveMonitors;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002257 std::copy_if(monitors.begin(), monitors.end(), std::back_inserter(responsiveMonitors),
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002258 [this](const Monitor& monitor) REQUIRES(mLock) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07002259 std::shared_ptr<Connection> connection =
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002260 getConnectionLocked(monitor.inputChannel->getConnectionToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002261 if (connection == nullptr) {
2262 ALOGE("Could not find connection for monitor %s",
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002263 monitor.inputChannel->getName().c_str());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002264 return false;
2265 }
2266 if (!connection->responsive) {
2267 ALOGW("Unresponsive monitor %s will not get the new gesture",
2268 connection->inputChannel->getName().c_str());
2269 return false;
2270 }
2271 return true;
2272 });
2273 return responsiveMonitors;
2274}
2275
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002276std::vector<InputTarget> InputDispatcher::findTouchedWindowTargetsLocked(
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002277 nsecs_t currentTime, const MotionEntry& entry,
Siarhei Vishniakou4fe57392022-10-25 13:44:30 -07002278 InputEventInjectionResult& outInjectionResult) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002279 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002280
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002281 std::vector<InputTarget> targets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002282 // For security reasons, we defer updating the touch state until we are sure that
2283 // event injection will be allowed.
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002284 const int32_t displayId = entry.displayId;
2285 const int32_t action = entry.action;
Siarhei Vishniakoubf880522023-05-01 11:03:22 -07002286 const int32_t maskedAction = MotionEvent::getActionMasked(action);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002287
2288 // Update the touch state as needed based on the properties of the touch event.
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002289 outInjectionResult = InputEventInjectionResult::PENDING;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002290
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002291 // Copy current touch state into tempTouchState.
2292 // This state will be used to update mTouchStatesByDisplay at the end of this function.
2293 // If no state for the specified display exists, then our initial state will be empty.
Yi Kong9b14ac62018-07-17 13:48:38 -07002294 const TouchState* oldState = nullptr;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002295 TouchState tempTouchState;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002296 if (const auto it = mTouchStatesByDisplay.find(displayId); it != mTouchStatesByDisplay.end()) {
2297 oldState = &(it->second);
Prabir Pradhane680f9b2022-02-04 04:24:00 -08002298 tempTouchState = *oldState;
Jeff Brownf086ddb2014-02-11 14:28:48 -08002299 }
2300
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07002301 bool isSplit = shouldSplitTouch(tempTouchState, entry);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002302
2303 const bool isHoverAction = (maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE ||
2304 maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2305 maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT);
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002306 // A DOWN could be generated from POINTER_DOWN if the initial pointers did not land into any
2307 // touchable windows.
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002308 const bool wasDown = oldState != nullptr && oldState->isDown(entry.deviceId);
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002309 const bool isDown = (maskedAction == AMOTION_EVENT_ACTION_DOWN) ||
2310 (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN && !wasDown);
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07002311 const bool newGesture = isDown || maskedAction == AMOTION_EVENT_ACTION_SCROLL ||
2312 maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2313 maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE;
Prabir Pradhanaa561d12021-09-24 06:57:33 -07002314 const bool isFromMouse = isFromSource(entry.source, AINPUT_SOURCE_MOUSE);
Siarhei Vishniakou5cee1e32022-11-29 12:35:39 -08002315
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002316 if (newGesture) {
2317 isSplit = false;
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002318 }
2319
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002320 if (isDown && tempTouchState.hasHoveringPointers(entry.deviceId)) {
2321 // Compatibility behaviour: ACTION_DOWN causes HOVER_EXIT to get generated.
2322 tempTouchState.clearHoveringPointers(entry.deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002323 }
2324
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002325 if (isHoverAction) {
Siarhei Vishniakou7be50c92023-11-17 17:09:08 -08002326 if (wasDown) {
2327 // Started hovering, but the device is already down: reject the hover event
2328 LOG(ERROR) << "Got hover event " << entry.getDescription()
2329 << " but the device is already down " << oldState->dump();
2330 outInjectionResult = InputEventInjectionResult::FAILED;
2331 return {};
2332 }
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002333 // For hover actions, we will treat 'tempTouchState' as a new state, so let's erase
2334 // all of the existing hovering pointers and recompute.
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002335 tempTouchState.clearHoveringPointers(entry.deviceId);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002336 }
2337
Michael Wrightd02c5b62014-02-10 15:10:22 -08002338 if (newGesture || (isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN)) {
2339 /* Case 1: New splittable pointer going down, or need target for hover or scroll. */
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07002340 const auto [x, y] = resolveTouchedPosition(entry);
Siarhei Vishniakou5b9766d2023-07-18 14:06:29 -07002341 const int32_t pointerIndex = MotionEvent::getActionIndex(action);
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002342 const PointerProperties& pointer = entry.pointerProperties[pointerIndex];
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002343 // Outside targets should be added upon first dispatched DOWN event. That means, this should
2344 // be a pointer that would generate ACTION_DOWN, *and* touch should not already be down.
Prabir Pradhand65552b2021-10-07 11:23:50 -07002345 const bool isStylus = isPointerFromStylus(entry, pointerIndex);
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07002346 sp<WindowInfoHandle> newTouchedWindowHandle =
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002347 findTouchedWindowAtLocked(displayId, x, y, isStylus);
Michael Wright3dd60e22019-03-27 22:06:44 +00002348
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002349 if (isDown) {
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002350 targets += findOutsideTargetsLocked(displayId, newTouchedWindowHandle, pointer.id);
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002351 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002352 // Handle the case where we did not find a window.
Yi Kong9b14ac62018-07-17 13:48:38 -07002353 if (newTouchedWindowHandle == nullptr) {
Prabir Pradhan82e081e2022-12-06 09:50:09 +00002354 ALOGD("No new touched window at (%.1f, %.1f) in display %" PRId32, x, y, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002355 // Try to assign the pointer to the first foreground window we find, if there is one.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002356 newTouchedWindowHandle = tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002357 }
2358
Prabir Pradhan5735a322022-04-11 17:23:34 +00002359 // Verify targeted injection.
2360 if (const auto err = verifyTargetedInjection(newTouchedWindowHandle, entry); err) {
2361 ALOGW("Dropping injected touch event: %s", (*err).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002362 outInjectionResult = os::InputEventInjectionResult::TARGET_MISMATCH;
Prabir Pradhan5735a322022-04-11 17:23:34 +00002363 newTouchedWindowHandle = nullptr;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002364 return {};
Prabir Pradhan5735a322022-04-11 17:23:34 +00002365 }
2366
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002367 // Figure out whether splitting will be allowed for this window.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002368 if (newTouchedWindowHandle != nullptr) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002369 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
2370 // New window supports splitting, but we should never split mouse events.
2371 isSplit = !isFromMouse;
2372 } else if (isSplit) {
2373 // New window does not support splitting but we have already split events.
2374 // Ignore the new window.
Siarhei Vishniakou25537f82023-07-18 14:35:47 -07002375 LOG(INFO) << "Skipping " << newTouchedWindowHandle->getName()
2376 << " because it doesn't support split touch";
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002377 newTouchedWindowHandle = nullptr;
2378 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002379 } else {
2380 // No window is touched, so set split to true. This will allow the next pointer down to
Prabir Pradhan713bb3e2021-12-20 02:07:40 -08002381 // be delivered to a new window which supports split touch. Pointers from a mouse device
2382 // should never be split.
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07002383 isSplit = !isFromMouse;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002384 }
2385
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002386 std::vector<sp<WindowInfoHandle>> newTouchedWindows =
Prabir Pradhand65552b2021-10-07 11:23:50 -07002387 findTouchedSpyWindowsAtLocked(displayId, x, y, isStylus);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002388 if (newTouchedWindowHandle != nullptr) {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002389 // Process the foreground window first so that it is the first to receive the event.
2390 newTouchedWindows.insert(newTouchedWindows.begin(), newTouchedWindowHandle);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002391 }
2392
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002393 if (newTouchedWindows.empty()) {
Prabir Pradhan82e081e2022-12-06 09:50:09 +00002394 ALOGI("Dropping event because there is no touchable window at (%.1f, %.1f) on display "
2395 "%d.",
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002396 x, y, displayId);
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002397 outInjectionResult = InputEventInjectionResult::FAILED;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002398 return {};
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002399 }
2400
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002401 for (const sp<WindowInfoHandle>& windowHandle : newTouchedWindows) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07002402 if (!canWindowReceiveMotionLocked(windowHandle, entry)) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002403 continue;
2404 }
2405
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002406 if (isHoverAction) {
Siarhei Vishniakoub681c202023-05-01 11:22:33 -07002407 // The "windowHandle" is the target of this hovering pointer.
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002408 tempTouchState.addHoveringPointerToWindow(windowHandle, entry.deviceId, pointer);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002409 }
2410
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002411 // Set target flags.
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002412 ftl::Flags<InputTarget::Flags> targetFlags;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002413
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002414 if (canReceiveForegroundTouches(*windowHandle->getInfo())) {
2415 // There should only be one touched window that can be "foreground" for the pointer.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002416 targetFlags |= InputTarget::Flags::FOREGROUND;
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002417 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002418
2419 if (isSplit) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002420 targetFlags |= InputTarget::Flags::SPLIT;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002421 }
2422 if (isWindowObscuredAtPointLocked(windowHandle, x, y)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002423 targetFlags |= InputTarget::Flags::WINDOW_IS_OBSCURED;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002424 } else if (isWindowObscuredLocked(windowHandle)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002425 targetFlags |= InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002426 }
Michael Wright3dd60e22019-03-27 22:06:44 +00002427
2428 // Update the temporary touch state.
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002429
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002430 if (!isHoverAction) {
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002431 const bool isDownOrPointerDown = maskedAction == AMOTION_EVENT_ACTION_DOWN ||
2432 maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN;
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002433 tempTouchState.addOrUpdateWindow(windowHandle, InputTarget::DispatchMode::AS_IS,
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002434 targetFlags, entry.deviceId, {pointer},
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002435 isDownOrPointerDown
2436 ? std::make_optional(entry.eventTime)
2437 : std::nullopt);
2438 // If this is the pointer going down and the touched window has a wallpaper
2439 // then also add the touched wallpaper windows so they are locked in for the
2440 // duration of the touch gesture. We do not collect wallpapers during HOVER_MOVE or
2441 // SCROLL because the wallpaper engine only supports touch events. We would need to
2442 // add a mechanism similar to View.onGenericMotionEvent to enable wallpapers to
2443 // handle these events.
2444 if (isDownOrPointerDown && targetFlags.test(InputTarget::Flags::FOREGROUND) &&
Arthur Hungc539dbb2022-12-08 07:45:36 +00002445 windowHandle->getInfo()->inputConfig.test(
2446 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER)) {
2447 sp<WindowInfoHandle> wallpaper = findWallpaperWindowBelow(windowHandle);
2448 if (wallpaper != nullptr) {
2449 ftl::Flags<InputTarget::Flags> wallpaperFlags =
2450 InputTarget::Flags::WINDOW_IS_OBSCURED |
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002451 InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED;
Arthur Hungc539dbb2022-12-08 07:45:36 +00002452 if (isSplit) {
2453 wallpaperFlags |= InputTarget::Flags::SPLIT;
2454 }
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002455 tempTouchState.addOrUpdateWindow(wallpaper,
2456 InputTarget::DispatchMode::AS_IS,
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002457 wallpaperFlags, entry.deviceId, {pointer},
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002458 entry.eventTime);
Arthur Hungc539dbb2022-12-08 07:45:36 +00002459 }
2460 }
2461 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002462 }
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00002463
Siarhei Vishniakou060f82b2023-01-27 06:39:14 -08002464 // If a window is already pilfering some pointers, give it this new pointer as well and
2465 // make it pilfering. This will prevent other non-spy windows from getting this pointer,
2466 // which is a specific behaviour that we want.
Siarhei Vishniakou060f82b2023-01-27 06:39:14 -08002467 for (TouchedWindow& touchedWindow : tempTouchState.windows) {
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002468 if (touchedWindow.hasTouchingPointer(entry.deviceId, pointer.id) &&
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002469 touchedWindow.hasPilferingPointers(entry.deviceId)) {
Siarhei Vishniakou060f82b2023-01-27 06:39:14 -08002470 // This window is already pilfering some pointers, and this new pointer is also
2471 // going to it. Therefore, take over this pointer and don't give it to anyone
2472 // else.
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002473 touchedWindow.addPilferingPointer(entry.deviceId, pointer.id);
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00002474 }
2475 }
Siarhei Vishniakou060f82b2023-01-27 06:39:14 -08002476
2477 // Restrict all pilfered pointers to the pilfering windows.
2478 tempTouchState.cancelPointersForNonPilferingWindows();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002479 } else {
2480 /* Case 2: Pointer move, up, cancel or non-splittable pointer down. */
2481
2482 // If the pointer is not currently down, then ignore the event.
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002483 if (!tempTouchState.isDown(entry.deviceId) &&
2484 maskedAction != AMOTION_EVENT_ACTION_HOVER_EXIT) {
Siarhei Vishniakou31dd1552023-10-30 18:46:10 -07002485 if (DEBUG_DROPPED_EVENTS_VERBOSE) {
2486 LOG(INFO) << "Dropping event because the pointer for device " << entry.deviceId
2487 << " is not down or we previously dropped the pointer down event in "
2488 << "display " << displayId << ": " << entry.getDescription();
2489 }
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002490 outInjectionResult = InputEventInjectionResult::FAILED;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002491 return {};
Michael Wrightd02c5b62014-02-10 15:10:22 -08002492 }
2493
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07002494 // If the pointer is not currently hovering, then ignore the event.
2495 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT) {
2496 const int32_t pointerId = entry.pointerProperties[0].id;
2497 if (oldState == nullptr ||
2498 oldState->getWindowsWithHoveringPointer(entry.deviceId, pointerId).empty()) {
2499 LOG(INFO) << "Dropping event because the hovering pointer is not in any windows in "
2500 "display "
2501 << displayId << ": " << entry.getDescription();
2502 outInjectionResult = InputEventInjectionResult::FAILED;
2503 return {};
2504 }
2505 tempTouchState.removeHoveringPointer(entry.deviceId, pointerId);
2506 }
2507
arthurhung6d4bed92021-03-17 11:59:33 +08002508 addDragEventLocked(entry);
arthurhungb89ccb02020-12-30 16:19:01 +08002509
Michael Wrightd02c5b62014-02-10 15:10:22 -08002510 // Check whether touches should slip outside of the current foreground window.
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07002511 if (maskedAction == AMOTION_EVENT_ACTION_MOVE && entry.getPointerCount() == 1 &&
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002512 tempTouchState.isSlippery()) {
Siarhei Vishniakou9306c382022-09-30 15:30:31 -07002513 const auto [x, y] = resolveTouchedPosition(entry);
Harry Cutts33476232023-01-30 19:57:29 +00002514 const bool isStylus = isPointerFromStylus(entry, /*pointerIndex=*/0);
chaviw98318de2021-05-19 16:45:23 -05002515 sp<WindowInfoHandle> oldTouchedWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002516 tempTouchState.getFirstForegroundWindowHandle();
Siarhei Vishniakou0f6558d2023-04-21 12:05:13 -07002517 LOG_ALWAYS_FATAL_IF(oldTouchedWindowHandle == nullptr);
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07002518 sp<WindowInfoHandle> newTouchedWindowHandle =
2519 findTouchedWindowAtLocked(displayId, x, y, isStylus);
Vishnu Nair062a8672021-09-03 16:07:44 -07002520
Prabir Pradhan5735a322022-04-11 17:23:34 +00002521 // Verify targeted injection.
2522 if (const auto err = verifyTargetedInjection(newTouchedWindowHandle, entry); err) {
2523 ALOGW("Dropping injected event: %s", (*err).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002524 outInjectionResult = os::InputEventInjectionResult::TARGET_MISMATCH;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002525 return {};
Prabir Pradhan5735a322022-04-11 17:23:34 +00002526 }
2527
Vishnu Nair062a8672021-09-03 16:07:44 -07002528 // Drop touch events if requested by input feature
2529 if (newTouchedWindowHandle != nullptr &&
2530 shouldDropInput(entry, newTouchedWindowHandle)) {
2531 newTouchedWindowHandle = nullptr;
2532 }
2533
Siarhei Vishniakouafa08cc2023-05-08 22:35:50 -07002534 if (newTouchedWindowHandle != nullptr &&
2535 !haveSameToken(oldTouchedWindowHandle, newTouchedWindowHandle)) {
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002536 ALOGI("Touch is slipping out of window %s into window %s in display %" PRId32,
Siarhei Vishniakou0f6558d2023-04-21 12:05:13 -07002537 oldTouchedWindowHandle->getName().c_str(),
2538 newTouchedWindowHandle->getName().c_str(), displayId);
2539
Michael Wrightd02c5b62014-02-10 15:10:22 -08002540 // Make a slippery exit from the old window.
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08002541 std::bitset<MAX_POINTER_ID + 1> pointerIds;
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002542 const PointerProperties& pointer = entry.pointerProperties[0];
2543 pointerIds.set(pointer.id);
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002544
2545 const TouchedWindow& touchedWindow =
2546 tempTouchState.getTouchedWindow(oldTouchedWindowHandle);
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002547 addPointerWindowTargetLocked(oldTouchedWindowHandle,
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002548 InputTarget::DispatchMode::SLIPPERY_EXIT,
2549 ftl::Flags<InputTarget::Flags>(), pointerIds,
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002550 touchedWindow.getDownTimeInTarget(entry.deviceId),
2551 targets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002552
2553 // Make a slippery entrance into the new window.
2554 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
Prabir Pradhan713bb3e2021-12-20 02:07:40 -08002555 isSplit = !isFromMouse;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002556 }
2557
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002558 ftl::Flags<InputTarget::Flags> targetFlags;
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002559 if (canReceiveForegroundTouches(*newTouchedWindowHandle->getInfo())) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002560 targetFlags |= InputTarget::Flags::FOREGROUND;
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002561 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002562 if (isSplit) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002563 targetFlags |= InputTarget::Flags::SPLIT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002564 }
2565 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002566 targetFlags |= InputTarget::Flags::WINDOW_IS_OBSCURED;
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002567 } else if (isWindowObscuredLocked(newTouchedWindowHandle)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002568 targetFlags |= InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002569 }
2570
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002571 tempTouchState.addOrUpdateWindow(newTouchedWindowHandle,
2572 InputTarget::DispatchMode::SLIPPERY_ENTER,
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002573 targetFlags, entry.deviceId, {pointer},
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002574 entry.eventTime);
Arthur Hungc539dbb2022-12-08 07:45:36 +00002575
2576 // Check if the wallpaper window should deliver the corresponding event.
2577 slipWallpaperTouch(targetFlags, oldTouchedWindowHandle, newTouchedWindowHandle,
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002578 tempTouchState, entry.deviceId, pointer, targets);
2579 tempTouchState.removeTouchingPointerFromWindow(entry.deviceId, pointer.id,
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002580 oldTouchedWindowHandle);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002581 }
2582 }
Arthur Hung96483742022-11-15 03:30:48 +00002583
2584 // Update the pointerIds for non-splittable when it received pointer down.
2585 if (!isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN) {
2586 // If no split, we suppose all touched windows should receive pointer down.
Siarhei Vishniakou5b9766d2023-07-18 14:06:29 -07002587 const int32_t pointerIndex = MotionEvent::getActionIndex(action);
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002588 std::vector<PointerProperties> touchingPointers{entry.pointerProperties[pointerIndex]};
2589 for (TouchedWindow& touchedWindow : tempTouchState.windows) {
Arthur Hung96483742022-11-15 03:30:48 +00002590 // Ignore drag window for it should just track one pointer.
2591 if (mDragState && mDragState->dragWindow == touchedWindow.windowHandle) {
2592 continue;
2593 }
Siarhei Vishniakou5b9766d2023-07-18 14:06:29 -07002594 touchedWindow.addTouchingPointers(entry.deviceId, touchingPointers);
Arthur Hung96483742022-11-15 03:30:48 +00002595 }
2596 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002597 }
2598
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002599 // Update dispatching for hover enter and exit.
Sam Dubeyf886dec2023-01-27 13:28:19 +00002600 {
2601 std::vector<TouchedWindow> hoveringWindows =
2602 getHoveringWindowsLocked(oldState, tempTouchState, entry);
2603 for (const TouchedWindow& touchedWindow : hoveringWindows) {
Siarhei Vishniakoud5876ba2023-05-15 17:58:34 -07002604 std::optional<InputTarget> target =
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002605 createInputTargetLocked(touchedWindow.windowHandle, touchedWindow.dispatchMode,
2606 touchedWindow.targetFlags,
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002607 touchedWindow.getDownTimeInTarget(entry.deviceId));
Siarhei Vishniakoud5876ba2023-05-15 17:58:34 -07002608 if (!target) {
2609 continue;
2610 }
2611 // Hardcode to single hovering pointer for now.
2612 std::bitset<MAX_POINTER_ID + 1> pointerIds;
2613 pointerIds.set(entry.pointerProperties[0].id);
2614 target->addPointers(pointerIds, touchedWindow.windowHandle->getInfo()->transform);
2615 targets.push_back(*target);
Sam Dubeyf886dec2023-01-27 13:28:19 +00002616 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002617 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002618
Prabir Pradhan5735a322022-04-11 17:23:34 +00002619 // Ensure that all touched windows are valid for injection.
2620 if (entry.injectionState != nullptr) {
2621 std::string errs;
2622 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Prabir Pradhan5735a322022-04-11 17:23:34 +00002623 const auto err = verifyTargetedInjection(touchedWindow.windowHandle, entry);
2624 if (err) errs += "\n - " + *err;
2625 }
2626 if (!errs.empty()) {
2627 ALOGW("Dropping targeted injection: At least one touched window is not owned by uid "
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00002628 "%s:%s",
2629 entry.injectionState->targetUid->toString().c_str(), errs.c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002630 outInjectionResult = InputEventInjectionResult::TARGET_MISMATCH;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002631 return {};
Prabir Pradhan5735a322022-04-11 17:23:34 +00002632 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002633 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002634
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002635 // Check whether windows listening for outside touches are owned by the same UID. If the owner
2636 // has a different UID, then we will not reveal coordinate information to this window.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002637 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
chaviw98318de2021-05-19 16:45:23 -05002638 sp<WindowInfoHandle> foregroundWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002639 tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002640 if (foregroundWindowHandle) {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00002641 const auto foregroundWindowUid = foregroundWindowHandle->getInfo()->ownerUid;
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002642 for (InputTarget& target : targets) {
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002643 if (target.dispatchMode == InputTarget::DispatchMode::OUTSIDE) {
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002644 sp<WindowInfoHandle> targetWindow =
2645 getWindowHandleLocked(target.inputChannel->getConnectionToken());
2646 if (targetWindow->getInfo()->ownerUid != foregroundWindowUid) {
2647 target.flags |= InputTarget::Flags::ZERO_COORDS;
Michael Wright3dd60e22019-03-27 22:06:44 +00002648 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002649 }
2650 }
2651 }
2652 }
2653
Harry Cuttsb166c002023-05-09 13:06:05 +00002654 // If this is a touchpad navigation gesture, it needs to only be sent to trusted targets, as we
2655 // only want the system UI to handle these gestures.
2656 const bool isTouchpadNavGesture = isFromSource(entry.source, AINPUT_SOURCE_MOUSE) &&
2657 entry.classification == MotionClassification::MULTI_FINGER_SWIPE;
2658 if (isTouchpadNavGesture) {
2659 filterUntrustedTargets(/* byref */ tempTouchState, /* byref */ targets);
2660 }
2661
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07002662 // Output targets from the touch state.
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002663 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002664 std::vector<PointerProperties> touchingPointers =
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002665 touchedWindow.getTouchingPointers(entry.deviceId);
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002666 if (touchingPointers.empty()) {
Siarhei Vishniakoue0431e42023-01-28 17:01:39 -08002667 continue;
2668 }
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002669 addPointerWindowTargetLocked(touchedWindow.windowHandle, touchedWindow.dispatchMode,
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002670 touchedWindow.targetFlags, getPointerIds(touchingPointers),
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002671 touchedWindow.getDownTimeInTarget(entry.deviceId), targets);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002672 }
Sam Dubey39d37cf2022-12-07 18:05:35 +00002673
Siarhei Vishniakou580fb3a2023-05-05 15:02:20 -07002674 // During targeted injection, only allow owned targets to receive events
2675 std::erase_if(targets, [&](const InputTarget& target) {
2676 LOG_ALWAYS_FATAL_IF(target.windowHandle == nullptr);
2677 const auto err = verifyTargetedInjection(target.windowHandle, entry);
2678 if (err) {
2679 LOG(WARNING) << "Dropping injected event from " << target.windowHandle->getName()
2680 << ": " << (*err);
2681 return true;
2682 }
2683 return false;
2684 });
2685
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07002686 if (targets.empty()) {
2687 LOG(INFO) << "Dropping event because no targets were found: " << entry.getDescription();
2688 outInjectionResult = InputEventInjectionResult::FAILED;
2689 return {};
2690 }
2691
2692 // If we only have windows getting ACTION_OUTSIDE, then drop the event, because there is no
2693 // window that is actually receiving the entire gesture.
2694 if (std::all_of(targets.begin(), targets.end(), [](const InputTarget& target) {
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002695 return target.dispatchMode == InputTarget::DispatchMode::OUTSIDE;
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07002696 })) {
2697 LOG(INFO) << "Dropping event because all windows would just receive ACTION_OUTSIDE: "
2698 << entry.getDescription();
2699 outInjectionResult = InputEventInjectionResult::FAILED;
2700 return {};
2701 }
2702
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002703 outInjectionResult = InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002704
Prabir Pradhan502a7252023-12-01 16:11:24 +00002705 // Now that we have generated all of the input targets for this event, reset the dispatch
2706 // mode for all touched window to AS_IS.
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002707 for (TouchedWindow& touchedWindow : tempTouchState.windows) {
Prabir Pradhan502a7252023-12-01 16:11:24 +00002708 touchedWindow.dispatchMode = InputTarget::DispatchMode::AS_IS;
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002709 }
2710
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002711 // Update final pieces of touch state if the injector had permission.
Siarhei Vishniakou7be50c92023-11-17 17:09:08 -08002712 if (maskedAction == AMOTION_EVENT_ACTION_UP) {
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002713 // Pointer went up.
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002714 tempTouchState.removeTouchingPointer(entry.deviceId, entry.pointerProperties[0].id);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002715 } else if (maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002716 // All pointers up or canceled.
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002717 tempTouchState.removeAllPointersForDevice(entry.deviceId);
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002718 } else if (maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
2719 // One pointer went up.
Siarhei Vishniakou5b9766d2023-07-18 14:06:29 -07002720 const int32_t pointerIndex = MotionEvent::getActionIndex(action);
2721 const uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
2722 tempTouchState.removeTouchingPointer(entry.deviceId, pointerId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002723 }
2724
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002725 // Save changes unless the action was scroll in which case the temporary touch
2726 // state was only valid for this one action.
2727 if (maskedAction != AMOTION_EVENT_ACTION_SCROLL) {
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07002728 if (displayId >= 0) {
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002729 tempTouchState.clearWindowsWithoutPointers();
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002730 mTouchStatesByDisplay[displayId] = tempTouchState;
2731 } else {
2732 mTouchStatesByDisplay.erase(displayId);
2733 }
2734 }
2735
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -08002736 if (tempTouchState.windows.empty()) {
2737 mTouchStatesByDisplay.erase(displayId);
2738 }
2739
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002740 return targets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002741}
2742
arthurhung6d4bed92021-03-17 11:59:33 +08002743void InputDispatcher::finishDragAndDrop(int32_t displayId, float x, float y) {
Prabir Pradhand65552b2021-10-07 11:23:50 -07002744 // Prevent stylus interceptor windows from affecting drag and drop behavior for now, until we
2745 // have an explicit reason to support it.
2746 constexpr bool isStylus = false;
2747
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07002748 sp<WindowInfoHandle> dropWindow =
Harry Cutts33476232023-01-30 19:57:29 +00002749 findTouchedWindowAtLocked(displayId, x, y, isStylus, /*ignoreDragWindow=*/true);
arthurhung6d4bed92021-03-17 11:59:33 +08002750 if (dropWindow) {
2751 vec2 local = dropWindow->getInfo()->transform.transform(x, y);
Prabir Pradhancef936d2021-07-21 16:17:52 +00002752 sendDropWindowCommandLocked(dropWindow->getToken(), local.x, local.y);
Arthur Hung6d0571e2021-04-09 20:18:16 +08002753 } else {
Arthur Hung54745652022-04-20 07:17:41 +00002754 ALOGW("No window found when drop.");
Prabir Pradhancef936d2021-07-21 16:17:52 +00002755 sendDropWindowCommandLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08002756 }
2757 mDragState.reset();
2758}
2759
2760void InputDispatcher::addDragEventLocked(const MotionEntry& entry) {
Arthur Hung3915c1f2022-05-31 07:17:17 +00002761 if (!mDragState || mDragState->dragWindow->getInfo()->displayId != entry.displayId) {
arthurhungb89ccb02020-12-30 16:19:01 +08002762 return;
2763 }
2764
arthurhung6d4bed92021-03-17 11:59:33 +08002765 if (!mDragState->isStartDrag) {
2766 mDragState->isStartDrag = true;
2767 mDragState->isStylusButtonDownAtStart =
2768 (entry.buttonState & AMOTION_EVENT_BUTTON_STYLUS_PRIMARY) != 0;
2769 }
2770
Arthur Hung54745652022-04-20 07:17:41 +00002771 // Find the pointer index by id.
2772 int32_t pointerIndex = 0;
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07002773 for (; static_cast<uint32_t>(pointerIndex) < entry.getPointerCount(); pointerIndex++) {
Arthur Hung54745652022-04-20 07:17:41 +00002774 const PointerProperties& pointerProperties = entry.pointerProperties[pointerIndex];
2775 if (pointerProperties.id == mDragState->pointerId) {
2776 break;
arthurhung6d4bed92021-03-17 11:59:33 +08002777 }
Arthur Hung54745652022-04-20 07:17:41 +00002778 }
arthurhung6d4bed92021-03-17 11:59:33 +08002779
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07002780 if (uint32_t(pointerIndex) == entry.getPointerCount()) {
Arthur Hung54745652022-04-20 07:17:41 +00002781 LOG_ALWAYS_FATAL("Should find a valid pointer index by id %d", mDragState->pointerId);
Arthur Hung54745652022-04-20 07:17:41 +00002782 }
2783
2784 const int32_t maskedAction = entry.action & AMOTION_EVENT_ACTION_MASK;
2785 const int32_t x = entry.pointerCoords[pointerIndex].getX();
2786 const int32_t y = entry.pointerCoords[pointerIndex].getY();
2787
2788 switch (maskedAction) {
2789 case AMOTION_EVENT_ACTION_MOVE: {
2790 // Handle the special case : stylus button no longer pressed.
2791 bool isStylusButtonDown =
2792 (entry.buttonState & AMOTION_EVENT_BUTTON_STYLUS_PRIMARY) != 0;
2793 if (mDragState->isStylusButtonDownAtStart && !isStylusButtonDown) {
2794 finishDragAndDrop(entry.displayId, x, y);
2795 return;
2796 }
2797
2798 // Prevent stylus interceptor windows from affecting drag and drop behavior for now,
2799 // until we have an explicit reason to support it.
2800 constexpr bool isStylus = false;
2801
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07002802 sp<WindowInfoHandle> hoverWindowHandle =
2803 findTouchedWindowAtLocked(entry.displayId, x, y, isStylus,
2804 /*ignoreDragWindow=*/true);
Arthur Hung54745652022-04-20 07:17:41 +00002805 // enqueue drag exit if needed.
2806 if (hoverWindowHandle != mDragState->dragHoverWindowHandle &&
2807 !haveSameToken(hoverWindowHandle, mDragState->dragHoverWindowHandle)) {
2808 if (mDragState->dragHoverWindowHandle != nullptr) {
Harry Cutts33476232023-01-30 19:57:29 +00002809 enqueueDragEventLocked(mDragState->dragHoverWindowHandle, /*isExiting=*/true, x,
Arthur Hung54745652022-04-20 07:17:41 +00002810 y);
2811 }
2812 mDragState->dragHoverWindowHandle = hoverWindowHandle;
2813 }
2814 // enqueue drag location if needed.
2815 if (hoverWindowHandle != nullptr) {
Harry Cutts33476232023-01-30 19:57:29 +00002816 enqueueDragEventLocked(hoverWindowHandle, /*isExiting=*/false, x, y);
Arthur Hung54745652022-04-20 07:17:41 +00002817 }
2818 break;
2819 }
2820
2821 case AMOTION_EVENT_ACTION_POINTER_UP:
Siarhei Vishniakou5b9766d2023-07-18 14:06:29 -07002822 if (MotionEvent::getActionIndex(entry.action) != pointerIndex) {
Arthur Hung54745652022-04-20 07:17:41 +00002823 break;
2824 }
2825 // The drag pointer is up.
2826 [[fallthrough]];
2827 case AMOTION_EVENT_ACTION_UP:
2828 finishDragAndDrop(entry.displayId, x, y);
2829 break;
2830 case AMOTION_EVENT_ACTION_CANCEL: {
2831 ALOGD("Receiving cancel when drag and drop.");
2832 sendDropWindowCommandLocked(nullptr, 0, 0);
2833 mDragState.reset();
2834 break;
2835 }
arthurhungb89ccb02020-12-30 16:19:01 +08002836 }
2837}
2838
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002839std::optional<InputTarget> InputDispatcher::createInputTargetLocked(
2840 const sp<android::gui::WindowInfoHandle>& windowHandle,
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002841 InputTarget::DispatchMode dispatchMode, ftl::Flags<InputTarget::Flags> targetFlags,
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002842 std::optional<nsecs_t> firstDownTimeInTarget) const {
2843 std::shared_ptr<InputChannel> inputChannel = getInputChannelLocked(windowHandle->getToken());
2844 if (inputChannel == nullptr) {
2845 ALOGW("Not creating InputTarget for %s, no input channel", windowHandle->getName().c_str());
2846 return {};
2847 }
2848 InputTarget inputTarget;
2849 inputTarget.inputChannel = inputChannel;
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00002850 inputTarget.windowHandle = windowHandle;
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002851 inputTarget.dispatchMode = dispatchMode;
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002852 inputTarget.flags = targetFlags;
2853 inputTarget.globalScaleFactor = windowHandle->getInfo()->globalScaleFactor;
2854 inputTarget.firstDownTimeInTarget = firstDownTimeInTarget;
2855 const auto& displayInfoIt = mDisplayInfos.find(windowHandle->getInfo()->displayId);
2856 if (displayInfoIt != mDisplayInfos.end()) {
2857 inputTarget.displayTransform = displayInfoIt->second.transform;
2858 } else {
Siarhei Vishniakou580fb3a2023-05-05 15:02:20 -07002859 // DisplayInfo not found for this window on display windowHandle->getInfo()->displayId.
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002860 // TODO(b/198444055): Make this an error message after 'setInputWindows' API is removed.
2861 }
2862 return inputTarget;
2863}
2864
chaviw98318de2021-05-19 16:45:23 -05002865void InputDispatcher::addWindowTargetLocked(const sp<WindowInfoHandle>& windowHandle,
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002866 InputTarget::DispatchMode dispatchMode,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002867 ftl::Flags<InputTarget::Flags> targetFlags,
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002868 std::optional<nsecs_t> firstDownTimeInTarget,
Siarhei Vishniakouf75cddb2022-10-25 10:42:16 -07002869 std::vector<InputTarget>& inputTargets) const {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002870 std::vector<InputTarget>::iterator it =
2871 std::find_if(inputTargets.begin(), inputTargets.end(),
2872 [&windowHandle](const InputTarget& inputTarget) {
2873 return inputTarget.inputChannel->getConnectionToken() ==
2874 windowHandle->getToken();
2875 });
Chavi Weingarten97b8eec2020-01-09 18:09:08 +00002876
chaviw98318de2021-05-19 16:45:23 -05002877 const WindowInfo* windowInfo = windowHandle->getInfo();
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002878
2879 if (it == inputTargets.end()) {
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002880 std::optional<InputTarget> target =
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002881 createInputTargetLocked(windowHandle, dispatchMode, targetFlags,
2882 firstDownTimeInTarget);
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002883 if (!target) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002884 return;
2885 }
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002886 inputTargets.push_back(*target);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002887 it = inputTargets.end() - 1;
2888 }
2889
Siarhei Vishniakou23d73fb2023-10-29 13:27:46 -07002890 if (it->flags != targetFlags) {
2891 LOG(ERROR) << "Flags don't match! targetFlags=" << targetFlags.string() << ", it=" << *it;
2892 }
2893 if (it->globalScaleFactor != windowInfo->globalScaleFactor) {
2894 LOG(ERROR) << "Mismatch! it->globalScaleFactor=" << it->globalScaleFactor
2895 << ", windowInfo->globalScaleFactor=" << windowInfo->globalScaleFactor;
2896 }
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002897}
2898
2899void InputDispatcher::addPointerWindowTargetLocked(
2900 const sp<android::gui::WindowInfoHandle>& windowHandle,
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002901 InputTarget::DispatchMode dispatchMode, ftl::Flags<InputTarget::Flags> targetFlags,
2902 std::bitset<MAX_POINTER_ID + 1> pointerIds, std::optional<nsecs_t> firstDownTimeInTarget,
2903 std::vector<InputTarget>& inputTargets) const REQUIRES(mLock) {
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002904 if (pointerIds.none()) {
2905 for (const auto& target : inputTargets) {
2906 LOG(INFO) << "Target: " << target;
2907 }
2908 LOG(FATAL) << "No pointers specified for " << windowHandle->getName();
2909 return;
2910 }
2911 std::vector<InputTarget>::iterator it =
2912 std::find_if(inputTargets.begin(), inputTargets.end(),
2913 [&windowHandle](const InputTarget& inputTarget) {
2914 return inputTarget.inputChannel->getConnectionToken() ==
2915 windowHandle->getToken();
2916 });
2917
2918 // This is a hack, because the actual entry could potentially be an ACTION_DOWN event that
2919 // causes a HOVER_EXIT to be generated. That means that the same entry of ACTION_DOWN would
2920 // have DISPATCH_AS_HOVER_EXIT and DISPATCH_AS_IS. And therefore, we have to create separate
2921 // input targets for hovering pointers and for touching pointers.
2922 // If we picked an existing input target above, but it's for HOVER_EXIT - let's use a new
2923 // target instead.
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002924 if (it != inputTargets.end() && it->dispatchMode == InputTarget::DispatchMode::HOVER_EXIT) {
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002925 // Force the code below to create a new input target
2926 it = inputTargets.end();
2927 }
2928
2929 const WindowInfo* windowInfo = windowHandle->getInfo();
2930
2931 if (it == inputTargets.end()) {
2932 std::optional<InputTarget> target =
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002933 createInputTargetLocked(windowHandle, dispatchMode, targetFlags,
2934 firstDownTimeInTarget);
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002935 if (!target) {
2936 return;
2937 }
2938 inputTargets.push_back(*target);
2939 it = inputTargets.end() - 1;
2940 }
2941
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002942 if (it->dispatchMode != dispatchMode) {
2943 LOG(ERROR) << __func__ << ": DispatchMode doesn't match! ignoring new mode="
2944 << ftl::enum_string(dispatchMode) << ", it=" << *it;
2945 }
Siarhei Vishniakou4bd0b7c2023-10-27 00:51:14 -07002946 if (it->flags != targetFlags) {
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002947 LOG(ERROR) << __func__ << ": Flags don't match! new targetFlags=" << targetFlags.string()
2948 << ", it=" << *it;
Siarhei Vishniakou4bd0b7c2023-10-27 00:51:14 -07002949 }
Siarhei Vishniakou23d73fb2023-10-29 13:27:46 -07002950 if (it->globalScaleFactor != windowInfo->globalScaleFactor) {
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002951 LOG(ERROR) << __func__ << ": Mismatch! it->globalScaleFactor=" << it->globalScaleFactor
Siarhei Vishniakou23d73fb2023-10-29 13:27:46 -07002952 << ", windowInfo->globalScaleFactor=" << windowInfo->globalScaleFactor;
2953 }
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002954
chaviw1ff3d1e2020-07-01 15:53:47 -07002955 it->addPointers(pointerIds, windowInfo->transform);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002956}
2957
Michael Wright3dd60e22019-03-27 22:06:44 +00002958void InputDispatcher::addGlobalMonitoringTargetsLocked(std::vector<InputTarget>& inputTargets,
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002959 int32_t displayId) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002960 auto monitorsIt = mGlobalMonitorsByDisplay.find(displayId);
2961 if (monitorsIt == mGlobalMonitorsByDisplay.end()) return;
Michael Wright3dd60e22019-03-27 22:06:44 +00002962
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002963 for (const Monitor& monitor : selectResponsiveMonitorsLocked(monitorsIt->second)) {
2964 InputTarget target;
2965 target.inputChannel = monitor.inputChannel;
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002966 // target.firstDownTimeInTarget is not set for global monitors. It is only required in split
2967 // touch and global monitoring works as intended even without setting firstDownTimeInTarget
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002968 if (const auto& it = mDisplayInfos.find(displayId); it != mDisplayInfos.end()) {
2969 target.displayTransform = it->second.transform;
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002970 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002971 target.setDefaultPointerTransform(target.displayTransform);
2972 inputTargets.push_back(target);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002973 }
2974}
2975
Robert Carrc9bf1d32020-04-13 17:21:08 -07002976/**
2977 * Indicate whether one window handle should be considered as obscuring
2978 * another window handle. We only check a few preconditions. Actually
2979 * checking the bounds is left to the caller.
2980 */
chaviw98318de2021-05-19 16:45:23 -05002981static bool canBeObscuredBy(const sp<WindowInfoHandle>& windowHandle,
2982 const sp<WindowInfoHandle>& otherHandle) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002983 // Compare by token so cloned layers aren't counted
2984 if (haveSameToken(windowHandle, otherHandle)) {
2985 return false;
2986 }
2987 auto info = windowHandle->getInfo();
2988 auto otherInfo = otherHandle->getInfo();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002989 if (otherInfo->inputConfig.test(WindowInfo::InputConfig::NOT_VISIBLE)) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002990 return false;
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002991 } else if (otherInfo->alpha == 0 &&
2992 otherInfo->inputConfig.test(WindowInfo::InputConfig::NOT_TOUCHABLE)) {
Bernardo Rufino653d2e02020-10-20 17:32:40 +00002993 // Those act as if they were invisible, so we don't need to flag them.
2994 // We do want to potentially flag touchable windows even if they have 0
2995 // opacity, since they can consume touches and alter the effects of the
2996 // user interaction (eg. apps that rely on
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002997 // Flags::WINDOW_IS_PARTIALLY_OBSCURED should still be told about those
Bernardo Rufino653d2e02020-10-20 17:32:40 +00002998 // windows), hence we also check for FLAG_NOT_TOUCHABLE.
2999 return false;
Bernardo Rufino8007daf2020-09-22 09:40:01 +00003000 } else if (info->ownerUid == otherInfo->ownerUid) {
3001 // If ownerUid is the same we don't generate occlusion events as there
3002 // is no security boundary within an uid.
Robert Carrc9bf1d32020-04-13 17:21:08 -07003003 return false;
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08003004 } else if (otherInfo->inputConfig.test(gui::WindowInfo::InputConfig::TRUSTED_OVERLAY)) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07003005 return false;
3006 } else if (otherInfo->displayId != info->displayId) {
3007 return false;
3008 }
3009 return true;
3010}
3011
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003012/**
3013 * Returns touch occlusion information in the form of TouchOcclusionInfo. To check if the touch is
3014 * untrusted, one should check:
3015 *
3016 * 1. If result.hasBlockingOcclusion is true.
3017 * If it's, it means the touch should be blocked due to a window with occlusion mode of
3018 * BLOCK_UNTRUSTED.
3019 *
3020 * 2. If result.obscuringOpacity > mMaximumObscuringOpacityForTouch.
3021 * If it is (and 1 is false), then the touch should be blocked because a stack of windows
3022 * (possibly only one) with occlusion mode of USE_OPACITY from one UID resulted in a composed
3023 * obscuring opacity above the threshold. Note that if there was no window of occlusion mode
3024 * USE_OPACITY, result.obscuringOpacity would've been 0 and since
3025 * mMaximumObscuringOpacityForTouch >= 0, the condition above would never be true.
3026 *
3027 * If neither of those is true, then it means the touch can be allowed.
3028 */
3029InputDispatcher::TouchOcclusionInfo InputDispatcher::computeTouchOcclusionInfoLocked(
chaviw98318de2021-05-19 16:45:23 -05003030 const sp<WindowInfoHandle>& windowHandle, int32_t x, int32_t y) const {
3031 const WindowInfo* windowInfo = windowHandle->getInfo();
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00003032 int32_t displayId = windowInfo->displayId;
chaviw98318de2021-05-19 16:45:23 -05003033 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003034 TouchOcclusionInfo info;
3035 info.hasBlockingOcclusion = false;
3036 info.obscuringOpacity = 0;
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003037 info.obscuringUid = gui::Uid::INVALID;
3038 std::map<gui::Uid, float> opacityByUid;
chaviw98318de2021-05-19 16:45:23 -05003039 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003040 if (windowHandle == otherHandle) {
3041 break; // All future windows are below us. Exit early.
3042 }
chaviw98318de2021-05-19 16:45:23 -05003043 const WindowInfo* otherInfo = otherHandle->getInfo();
Bernardo Rufino1ff9d592021-01-18 16:58:57 +00003044 if (canBeObscuredBy(windowHandle, otherHandle) && otherInfo->frameContainsPoint(x, y) &&
3045 !haveSameApplicationToken(windowInfo, otherInfo)) {
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00003046 if (DEBUG_TOUCH_OCCLUSION) {
3047 info.debugInfo.push_back(
Harry Cutts101ee9b2023-07-06 18:04:14 +00003048 dumpWindowForTouchOcclusion(otherInfo, /*isTouchedWindow=*/false));
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00003049 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003050 // canBeObscuredBy() has returned true above, which means this window is untrusted, so
3051 // we perform the checks below to see if the touch can be propagated or not based on the
3052 // window's touch occlusion mode
3053 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::BLOCK_UNTRUSTED) {
3054 info.hasBlockingOcclusion = true;
3055 info.obscuringUid = otherInfo->ownerUid;
3056 info.obscuringPackage = otherInfo->packageName;
3057 break;
3058 }
3059 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::USE_OPACITY) {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003060 const auto uid = otherInfo->ownerUid;
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003061 float opacity =
3062 (opacityByUid.find(uid) == opacityByUid.end()) ? 0 : opacityByUid[uid];
3063 // Given windows A and B:
3064 // opacity(A, B) = 1 - [1 - opacity(A)] * [1 - opacity(B)]
3065 opacity = 1 - (1 - opacity) * (1 - otherInfo->alpha);
3066 opacityByUid[uid] = opacity;
3067 if (opacity > info.obscuringOpacity) {
3068 info.obscuringOpacity = opacity;
3069 info.obscuringUid = uid;
3070 info.obscuringPackage = otherInfo->packageName;
3071 }
3072 }
3073 }
3074 }
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00003075 if (DEBUG_TOUCH_OCCLUSION) {
Harry Cutts101ee9b2023-07-06 18:04:14 +00003076 info.debugInfo.push_back(dumpWindowForTouchOcclusion(windowInfo, /*isTouchedWindow=*/true));
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00003077 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003078 return info;
3079}
3080
chaviw98318de2021-05-19 16:45:23 -05003081std::string InputDispatcher::dumpWindowForTouchOcclusion(const WindowInfo* info,
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00003082 bool isTouchedWindow) const {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003083 return StringPrintf(INDENT2 "* %spackage=%s/%s, id=%" PRId32 ", mode=%s, alpha=%.2f, "
Prabir Pradhan51e7db02022-02-07 06:02:57 -08003084 "frame=[%" PRId32 ",%" PRId32 "][%" PRId32 ",%" PRId32
3085 "], touchableRegion=%s, window={%s}, inputConfig={%s}, "
3086 "hasToken=%s, applicationInfo.name=%s, applicationInfo.token=%s\n",
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08003087 isTouchedWindow ? "[TOUCHED] " : "", info->packageName.c_str(),
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003088 info->ownerUid.toString().c_str(), info->id,
Chavi Weingarten7f019192023-08-08 20:39:01 +00003089 toString(info->touchOcclusionMode).c_str(), info->alpha, info->frame.left,
3090 info->frame.top, info->frame.right, info->frame.bottom,
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003091 dumpRegion(info->touchableRegion).c_str(), info->name.c_str(),
3092 info->inputConfig.string().c_str(), toString(info->token != nullptr),
3093 info->applicationInfo.name.c_str(),
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07003094 binderToString(info->applicationInfo.token).c_str());
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00003095}
3096
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003097bool InputDispatcher::isTouchTrustedLocked(const TouchOcclusionInfo& occlusionInfo) const {
3098 if (occlusionInfo.hasBlockingOcclusion) {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003099 ALOGW("Untrusted touch due to occlusion by %s/%s", occlusionInfo.obscuringPackage.c_str(),
3100 occlusionInfo.obscuringUid.toString().c_str());
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003101 return false;
3102 }
3103 if (occlusionInfo.obscuringOpacity > mMaximumObscuringOpacityForTouch) {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003104 ALOGW("Untrusted touch due to occlusion by %s/%s (obscuring opacity = "
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003105 "%.2f, maximum allowed = %.2f)",
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003106 occlusionInfo.obscuringPackage.c_str(), occlusionInfo.obscuringUid.toString().c_str(),
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003107 occlusionInfo.obscuringOpacity, mMaximumObscuringOpacityForTouch);
3108 return false;
3109 }
3110 return true;
3111}
3112
chaviw98318de2021-05-19 16:45:23 -05003113bool InputDispatcher::isWindowObscuredAtPointLocked(const sp<WindowInfoHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003114 int32_t x, int32_t y) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003115 int32_t displayId = windowHandle->getInfo()->displayId;
chaviw98318de2021-05-19 16:45:23 -05003116 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
3117 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07003118 if (windowHandle == otherHandle) {
3119 break; // All future windows are below us. Exit early.
Michael Wrightd02c5b62014-02-10 15:10:22 -08003120 }
chaviw98318de2021-05-19 16:45:23 -05003121 const WindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07003122 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08003123 otherInfo->frameContainsPoint(x, y)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003124 return true;
3125 }
3126 }
3127 return false;
3128}
3129
chaviw98318de2021-05-19 16:45:23 -05003130bool InputDispatcher::isWindowObscuredLocked(const sp<WindowInfoHandle>& windowHandle) const {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07003131 int32_t displayId = windowHandle->getInfo()->displayId;
chaviw98318de2021-05-19 16:45:23 -05003132 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
3133 const WindowInfo* windowInfo = windowHandle->getInfo();
3134 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07003135 if (windowHandle == otherHandle) {
3136 break; // All future windows are below us. Exit early.
Michael Wrightcdcd8f22016-03-22 16:52:13 -07003137 }
chaviw98318de2021-05-19 16:45:23 -05003138 const WindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07003139 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08003140 otherInfo->overlaps(windowInfo)) {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07003141 return true;
3142 }
3143 }
3144 return false;
3145}
3146
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08003147std::string InputDispatcher::getApplicationWindowLabel(
chaviw98318de2021-05-19 16:45:23 -05003148 const InputApplicationHandle* applicationHandle, const sp<WindowInfoHandle>& windowHandle) {
Yi Kong9b14ac62018-07-17 13:48:38 -07003149 if (applicationHandle != nullptr) {
3150 if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07003151 return applicationHandle->getName() + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003152 } else {
3153 return applicationHandle->getName();
3154 }
Yi Kong9b14ac62018-07-17 13:48:38 -07003155 } else if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07003156 return windowHandle->getInfo()->applicationInfo.name + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003157 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003158 return "<unknown application or window>";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003159 }
3160}
3161
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003162void InputDispatcher::pokeUserActivityLocked(const EventEntry& eventEntry) {
Antonio Kantekf16f2832021-09-28 04:39:20 +00003163 if (!isUserActivityEvent(eventEntry)) {
3164 // Not poking user activity if the event type does not represent a user activity
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003165 return;
3166 }
Yeabkal Wubshitb8aadfa2024-01-17 17:03:42 -08003167
3168 const int32_t eventType = getUserActivityEventType(eventEntry);
3169 if (input_flags::rate_limit_user_activity_poke_in_dispatcher()) {
3170 // Note that we're directly getting the time diff between the current event and the previous
3171 // event. This is assuming that the first user event always happens at a timestamp that is
3172 // greater than `mMinTimeBetweenUserActivityPokes` (otherwise, the first user event will
3173 // wrongly be dropped). In real life, `mMinTimeBetweenUserActivityPokes` is a much smaller
3174 // value than the potential first user activity event time, so this is ok.
3175 std::chrono::nanoseconds timeSinceLastEvent =
3176 std::chrono::nanoseconds(eventEntry.eventTime - mLastUserActivityTimes[eventType]);
3177 if (timeSinceLastEvent < mMinTimeBetweenUserActivityPokes) {
3178 return;
3179 }
3180 }
3181
Tiger Huang721e26f2018-07-24 22:26:19 +08003182 int32_t displayId = getTargetDisplayId(eventEntry);
chaviw98318de2021-05-19 16:45:23 -05003183 sp<WindowInfoHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Josep del Riob3981622023-04-18 15:49:45 +00003184 const WindowInfo* windowDisablingUserActivityInfo = nullptr;
Tiger Huang721e26f2018-07-24 22:26:19 +08003185 if (focusedWindowHandle != nullptr) {
chaviw98318de2021-05-19 16:45:23 -05003186 const WindowInfo* info = focusedWindowHandle->getInfo();
Prabir Pradhan51e7db02022-02-07 06:02:57 -08003187 if (info->inputConfig.test(WindowInfo::InputConfig::DISABLE_USER_ACTIVITY)) {
Josep del Riob3981622023-04-18 15:49:45 +00003188 windowDisablingUserActivityInfo = info;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003189 }
3190 }
3191
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003192 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003193 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003194 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
3195 if (motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003196 return;
3197 }
Josep del Riob3981622023-04-18 15:49:45 +00003198 if (windowDisablingUserActivityInfo != nullptr) {
3199 if (DEBUG_DISPATCH_CYCLE) {
3200 ALOGD("Not poking user activity: disabled by window '%s'.",
3201 windowDisablingUserActivityInfo->name.c_str());
3202 }
3203 return;
3204 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003205 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003206 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003207 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003208 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
3209 if (keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003210 return;
3211 }
Josep del Riob3981622023-04-18 15:49:45 +00003212 // If the key code is unknown, we don't consider it user activity
3213 if (keyEntry.keyCode == AKEYCODE_UNKNOWN) {
3214 return;
3215 }
3216 // Don't inhibit events that were intercepted or are not passed to
3217 // the apps, like system shortcuts
3218 if (windowDisablingUserActivityInfo != nullptr &&
3219 keyEntry.interceptKeyResult != KeyEntry::InterceptKeyResult::SKIP &&
3220 keyEntry.policyFlags & POLICY_FLAG_PASS_TO_USER) {
3221 if (DEBUG_DISPATCH_CYCLE) {
3222 ALOGD("Not poking user activity: disabled by window '%s'.",
3223 windowDisablingUserActivityInfo->name.c_str());
3224 }
3225 return;
3226 }
3227
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003228 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003229 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00003230 default: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003231 LOG_ALWAYS_FATAL("%s events are not user activity",
Dominik Laskowski75788452021-02-09 18:51:25 -08003232 ftl::enum_string(eventEntry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003233 break;
3234 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003235 }
3236
Yeabkal Wubshitb8aadfa2024-01-17 17:03:42 -08003237 mLastUserActivityTimes[eventType] = eventEntry.eventTime;
Prabir Pradhancef936d2021-07-21 16:17:52 +00003238 auto command = [this, eventTime = eventEntry.eventTime, eventType, displayId]()
3239 REQUIRES(mLock) {
3240 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00003241 mPolicy.pokeUserActivity(eventTime, eventType, displayId);
Prabir Pradhancef936d2021-07-21 16:17:52 +00003242 };
3243 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003244}
3245
3246void InputDispatcher::prepareDispatchCycleLocked(nsecs_t currentTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003247 const std::shared_ptr<Connection>& connection,
Prabir Pradhan24047542023-11-02 17:14:59 +00003248 std::shared_ptr<const EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003249 const InputTarget& inputTarget) {
Prabir Pradhan2dac8b82023-09-06 01:11:51 +00003250 ATRACE_NAME_IF(ATRACE_ENABLED(),
3251 StringPrintf("prepareDispatchCycleLocked(inputChannel=%s, id=0x%" PRIx32 ")",
3252 connection->getInputChannelName().c_str(), eventEntry->id));
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003253 if (DEBUG_DISPATCH_CYCLE) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003254 ALOGD("channel '%s' ~ prepareDispatchCycle - flags=%s, "
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08003255 "globalScaleFactor=%f, pointerIds=%s %s",
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003256 connection->getInputChannelName().c_str(), inputTarget.flags.string().c_str(),
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08003257 inputTarget.globalScaleFactor, bitsetToString(inputTarget.pointerIds).c_str(),
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003258 inputTarget.getPointerInfoString().c_str());
3259 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003260
3261 // Skip this event if the connection status is not normal.
3262 // We don't want to enqueue additional outbound events if the connection is broken.
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003263 if (connection->status != Connection::Status::NORMAL) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003264 if (DEBUG_DISPATCH_CYCLE) {
3265 ALOGD("channel '%s' ~ Dropping event because the channel status is %s",
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003266 connection->getInputChannelName().c_str(),
3267 ftl::enum_string(connection->status).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003268 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003269 return;
3270 }
3271
3272 // Split a motion event if needed.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003273 if (inputTarget.flags.test(InputTarget::Flags::SPLIT)) {
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003274 LOG_ALWAYS_FATAL_IF(eventEntry->type != EventEntry::Type::MOTION,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003275 "Entry type %s should not have Flags::SPLIT",
Dominik Laskowski75788452021-02-09 18:51:25 -08003276 ftl::enum_string(eventEntry->type).c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003277
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003278 const MotionEntry& originalMotionEntry = static_cast<const MotionEntry&>(*eventEntry);
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07003279 if (inputTarget.pointerIds.count() != originalMotionEntry.getPointerCount()) {
Siarhei Vishniakou16e4fa02023-02-16 17:48:56 -08003280 if (!inputTarget.firstDownTimeInTarget.has_value()) {
3281 logDispatchStateLocked();
3282 LOG(FATAL) << "Splitting motion events requires a down time to be set for the "
3283 "target on connection "
3284 << connection->getInputChannelName() << " for "
3285 << originalMotionEntry.getDescription();
3286 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003287 std::unique_ptr<MotionEntry> splitMotionEntry =
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00003288 splitMotionEvent(originalMotionEntry, inputTarget.pointerIds,
3289 inputTarget.firstDownTimeInTarget.value());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003290 if (!splitMotionEntry) {
3291 return; // split event was dropped
3292 }
Arthur Hungb3307ee2021-10-14 10:57:37 +00003293 if (splitMotionEntry->action == AMOTION_EVENT_ACTION_CANCEL) {
3294 std::string reason = std::string("reason=pointer cancel on split window");
3295 android_log_event_list(LOGTAG_INPUT_CANCEL)
3296 << connection->getInputChannelName().c_str() << reason << LOG_ID_EVENTS;
3297 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003298 if (DEBUG_FOCUS) {
3299 ALOGD("channel '%s' ~ Split motion event.",
3300 connection->getInputChannelName().c_str());
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003301 logOutboundMotionDetails(" ", *splitMotionEntry);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003302 }
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003303 enqueueDispatchEntryAndStartDispatchCycleLocked(currentTime, connection,
3304 std::move(splitMotionEntry),
3305 inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003306 return;
3307 }
3308 }
3309
3310 // Not splitting. Enqueue dispatch entries for the event as is.
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003311 enqueueDispatchEntryAndStartDispatchCycleLocked(currentTime, connection, eventEntry,
3312 inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003313}
3314
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003315void InputDispatcher::enqueueDispatchEntryAndStartDispatchCycleLocked(
3316 nsecs_t currentTime, const std::shared_ptr<Connection>& connection,
3317 std::shared_ptr<const EventEntry> eventEntry, const InputTarget& inputTarget) {
Prabir Pradhan2dac8b82023-09-06 01:11:51 +00003318 ATRACE_NAME_IF(ATRACE_ENABLED(),
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003319 StringPrintf("enqueueDispatchEntryAndStartDispatchCycleLocked(inputChannel=%s, "
3320 "id=0x%" PRIx32 ")",
Prabir Pradhan2dac8b82023-09-06 01:11:51 +00003321 connection->getInputChannelName().c_str(), eventEntry->id));
Michael Wright3dd60e22019-03-27 22:06:44 +00003322
hongzuo liu95785e22022-09-06 02:51:35 +00003323 const bool wasEmpty = connection->outboundQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003324
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003325 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003326
3327 // If the outbound queue was previously empty, start the dispatch cycle going.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003328 if (wasEmpty && !connection->outboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003329 startDispatchCycleLocked(currentTime, connection);
3330 }
3331}
3332
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003333void InputDispatcher::enqueueDispatchEntryLocked(const std::shared_ptr<Connection>& connection,
Prabir Pradhan24047542023-11-02 17:14:59 +00003334 std::shared_ptr<const EventEntry> eventEntry,
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003335 const InputTarget& inputTarget) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003336 // This is a new event.
3337 // Enqueue a new dispatch entry onto the outbound queue for this connection.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003338 std::unique_ptr<DispatchEntry> dispatchEntry =
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003339 createDispatchEntry(inputTarget, eventEntry, inputTarget.flags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003340
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003341 // Use the eventEntry from dispatchEntry since the entry may have changed and can now be a
3342 // different EventEntry than what was passed in.
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003343 eventEntry = dispatchEntry->eventEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003344 // Apply target flags and update the connection's input state.
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003345 switch (eventEntry->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003346 case EventEntry::Type::KEY: {
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003347 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(*eventEntry);
3348 if (!connection->inputState.trackKey(keyEntry, keyEntry.flags)) {
Siarhei Vishniakouc94dafe2023-05-26 10:24:19 -07003349 LOG(WARNING) << "channel " << connection->getInputChannelName()
3350 << "~ dropping inconsistent event: " << *dispatchEntry;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003351 return; // skip the inconsistent event
3352 }
3353 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003354 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003355
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003356 case EventEntry::Type::MOTION: {
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003357 std::shared_ptr<const MotionEntry> resolvedMotion =
3358 std::static_pointer_cast<const MotionEntry>(eventEntry);
3359 {
3360 // Determine the resolved motion entry.
3361 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(*eventEntry);
3362 int32_t resolvedAction = motionEntry.action;
3363 int32_t resolvedFlags = motionEntry.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003364
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003365 if (inputTarget.dispatchMode == InputTarget::DispatchMode::OUTSIDE) {
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003366 resolvedAction = AMOTION_EVENT_ACTION_OUTSIDE;
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003367 } else if (inputTarget.dispatchMode == InputTarget::DispatchMode::HOVER_EXIT) {
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003368 resolvedAction = AMOTION_EVENT_ACTION_HOVER_EXIT;
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003369 } else if (inputTarget.dispatchMode == InputTarget::DispatchMode::HOVER_ENTER) {
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003370 resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003371 } else if (inputTarget.dispatchMode == InputTarget::DispatchMode::SLIPPERY_EXIT) {
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003372 resolvedAction = AMOTION_EVENT_ACTION_CANCEL;
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003373 } else if (inputTarget.dispatchMode == InputTarget::DispatchMode::SLIPPERY_ENTER) {
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003374 resolvedAction = AMOTION_EVENT_ACTION_DOWN;
3375 }
3376 if (resolvedAction == AMOTION_EVENT_ACTION_HOVER_MOVE &&
3377 !connection->inputState.isHovering(motionEntry.deviceId, motionEntry.source,
3378 motionEntry.displayId)) {
3379 if (DEBUG_DISPATCH_CYCLE) {
3380 LOG(DEBUG) << "channel '" << connection->getInputChannelName().c_str()
3381 << "' ~ enqueueDispatchEntryLocked: filling in missing hover "
3382 "enter event";
3383 }
3384 resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
3385 }
3386
3387 if (resolvedAction == AMOTION_EVENT_ACTION_CANCEL) {
3388 resolvedFlags |= AMOTION_EVENT_FLAG_CANCELED;
3389 }
3390 if (dispatchEntry->targetFlags.test(InputTarget::Flags::WINDOW_IS_OBSCURED)) {
3391 resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED;
3392 }
3393 if (dispatchEntry->targetFlags.test(
3394 InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED)) {
3395 resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
3396 }
3397
3398 dispatchEntry->resolvedFlags = resolvedFlags;
3399 if (resolvedAction != motionEntry.action) {
Siarhei Vishniakoue9ef6bc2023-12-21 19:47:20 -08003400 std::optional<std::vector<PointerProperties>> usingProperties;
3401 std::optional<std::vector<PointerCoords>> usingCoords;
3402 if (resolvedAction == AMOTION_EVENT_ACTION_HOVER_EXIT ||
3403 resolvedAction == AMOTION_EVENT_ACTION_CANCEL) {
3404 // This is a HOVER_EXIT or an ACTION_CANCEL event that was synthesized by
3405 // the dispatcher, and therefore the coordinates of this event are currently
3406 // incorrect. These events should use the coordinates of the last dispatched
3407 // ACTION_MOVE or HOVER_MOVE. We need to query InputState to get this data.
3408 const bool hovering = resolvedAction == AMOTION_EVENT_ACTION_HOVER_EXIT;
3409 std::optional<std::pair<std::vector<PointerProperties>,
3410 std::vector<PointerCoords>>>
3411 pointerInfo =
3412 connection->inputState.getPointersOfLastEvent(motionEntry,
3413 hovering);
3414 if (pointerInfo) {
3415 usingProperties = pointerInfo->first;
3416 usingCoords = pointerInfo->second;
3417 }
3418 }
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003419 // Generate a new MotionEntry with a new eventId using the resolved action and
3420 // flags.
Siarhei Vishniakoue9ef6bc2023-12-21 19:47:20 -08003421 resolvedMotion = std::make_shared<
3422 MotionEntry>(mIdGenerator.nextId(), motionEntry.injectionState,
3423 motionEntry.eventTime, motionEntry.deviceId,
3424 motionEntry.source, motionEntry.displayId,
3425 motionEntry.policyFlags, resolvedAction,
3426 motionEntry.actionButton, resolvedFlags,
3427 motionEntry.metaState, motionEntry.buttonState,
3428 motionEntry.classification, motionEntry.edgeFlags,
3429 motionEntry.xPrecision, motionEntry.yPrecision,
3430 motionEntry.xCursorPosition, motionEntry.yCursorPosition,
3431 motionEntry.downTime,
3432 usingProperties.value_or(motionEntry.pointerProperties),
3433 usingCoords.value_or(motionEntry.pointerCoords));
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003434 if (ATRACE_ENABLED()) {
3435 std::string message = StringPrintf("Transmute MotionEvent(id=0x%" PRIx32
3436 ") to MotionEvent(id=0x%" PRIx32 ").",
3437 motionEntry.id, resolvedMotion->id);
3438 ATRACE_NAME(message.c_str());
3439 }
3440
3441 // Set the resolved motion entry in the DispatchEntry.
3442 dispatchEntry->eventEntry = resolvedMotion;
3443 eventEntry = resolvedMotion;
3444 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003445 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003446
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07003447 // Check if we need to cancel any of the ongoing gestures. We don't support multiple
3448 // devices being active at the same time in the same window, so if a new device is
3449 // active, cancel the gesture from the old device.
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07003450 std::unique_ptr<EventEntry> cancelEvent =
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003451 connection->inputState.cancelConflictingInputStream(*resolvedMotion);
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07003452 if (cancelEvent != nullptr) {
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003453 LOG(INFO) << "Canceling pointers for device " << resolvedMotion->deviceId << " in "
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07003454 << connection->getInputChannelName() << " with event "
3455 << cancelEvent->getDescription();
3456 std::unique_ptr<DispatchEntry> cancelDispatchEntry =
3457 createDispatchEntry(inputTarget, std::move(cancelEvent),
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003458 ftl::Flags<InputTarget::Flags>());
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07003459
3460 // Send these cancel events to the queue before sending the event from the new
3461 // device.
3462 connection->outboundQueue.emplace_back(std::move(cancelDispatchEntry));
3463 }
3464
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003465 if (!connection->inputState.trackMotion(*resolvedMotion,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003466 dispatchEntry->resolvedFlags)) {
Siarhei Vishniakouc94dafe2023-05-26 10:24:19 -07003467 LOG(WARNING) << "channel " << connection->getInputChannelName()
3468 << "~ dropping inconsistent event: " << *dispatchEntry;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003469 return; // skip the inconsistent event
3470 }
3471
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003472 if ((resolvedMotion->flags & AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE) &&
3473 (resolvedMotion->policyFlags & POLICY_FLAG_TRUSTED)) {
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08003474 // Skip reporting pointer down outside focus to the policy.
3475 break;
3476 }
3477
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003478 dispatchPointerDownOutsideFocus(resolvedMotion->source, resolvedMotion->action,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003479 inputTarget.inputChannel->getConnectionToken());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003480
3481 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003482 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003483 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003484 case EventEntry::Type::TOUCH_MODE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08003485 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
3486 case EventEntry::Type::DRAG: {
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003487 break;
3488 }
Chris Yef59a2f42020-10-16 12:55:26 -07003489 case EventEntry::Type::SENSOR: {
3490 LOG_ALWAYS_FATAL("SENSOR events should not go to apps via input channel");
3491 break;
3492 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003493 case EventEntry::Type::CONFIGURATION_CHANGED:
3494 case EventEntry::Type::DEVICE_RESET: {
3495 LOG_ALWAYS_FATAL("%s events should not go to apps",
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003496 ftl::enum_string(eventEntry->type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003497 break;
3498 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003499 }
3500
3501 // Remember that we are waiting for this dispatch to complete.
3502 if (dispatchEntry->hasForegroundTarget()) {
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003503 incrementPendingForegroundDispatches(*eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003504 }
3505
3506 // Enqueue the dispatch entry.
Prabir Pradhan8c90d782023-09-15 21:16:44 +00003507 connection->outboundQueue.emplace_back(std::move(dispatchEntry));
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003508 traceOutboundQueueLength(*connection);
chaviw8c9cf542019-03-25 13:02:48 -07003509}
3510
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003511/**
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003512 * This function is for debugging and metrics collection. It has two roles.
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003513 *
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003514 * The first role is to log input interaction with windows, which helps determine what the user was
3515 * interacting with. For example, if user is touching launcher, we will see an input_interaction log
3516 * that user started interacting with launcher window, as well as any other window that received
3517 * that gesture, such as the wallpaper or other spy windows. A new input_interaction is only logged
3518 * when the set of tokens that received the event changes. It is not logged again as long as the
3519 * user is interacting with the same windows.
3520 *
3521 * The second role is to track input device activity for metrics collection. For each input event,
3522 * we report the set of UIDs that the input device interacted with to the policy. Unlike for the
3523 * input_interaction logs, the device interaction is reported even when the set of interaction
3524 * tokens do not change.
3525 *
3526 * For these purposes, we do not count ACTION_OUTSIDE, ACTION_UP and ACTION_CANCEL actions as
3527 * interaction. This includes up and cancel events for both keys and motions.
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003528 */
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003529void InputDispatcher::processInteractionsLocked(const EventEntry& entry,
3530 const std::vector<InputTarget>& targets) {
3531 int32_t deviceId;
3532 nsecs_t eventTime;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003533 // Skip ACTION_UP events, and all events other than keys and motions
3534 if (entry.type == EventEntry::Type::KEY) {
3535 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
3536 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
3537 return;
3538 }
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003539 deviceId = keyEntry.deviceId;
3540 eventTime = keyEntry.eventTime;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003541 } else if (entry.type == EventEntry::Type::MOTION) {
3542 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
3543 if (motionEntry.action == AMOTION_EVENT_ACTION_UP ||
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003544 motionEntry.action == AMOTION_EVENT_ACTION_CANCEL ||
3545 MotionEvent::getActionMasked(motionEntry.action) == AMOTION_EVENT_ACTION_POINTER_UP) {
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003546 return;
3547 }
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003548 deviceId = motionEntry.deviceId;
3549 eventTime = motionEntry.eventTime;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003550 } else {
3551 return; // Not a key or a motion
3552 }
3553
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003554 std::set<gui::Uid> interactionUids;
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07003555 std::unordered_set<sp<IBinder>, StrongPointerHash<IBinder>> newConnectionTokens;
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003556 std::vector<std::shared_ptr<Connection>> newConnections;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003557 for (const InputTarget& target : targets) {
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003558 if (target.dispatchMode == InputTarget::DispatchMode::OUTSIDE) {
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003559 continue; // Skip windows that receive ACTION_OUTSIDE
3560 }
3561
3562 sp<IBinder> token = target.inputChannel->getConnectionToken();
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003563 std::shared_ptr<Connection> connection = getConnectionLocked(token);
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003564 if (connection == nullptr) {
3565 continue;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003566 }
3567 newConnectionTokens.insert(std::move(token));
3568 newConnections.emplace_back(connection);
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003569 if (target.windowHandle) {
3570 interactionUids.emplace(target.windowHandle->getInfo()->ownerUid);
3571 }
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003572 }
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003573
3574 auto command = [this, deviceId, eventTime, uids = std::move(interactionUids)]()
3575 REQUIRES(mLock) {
3576 scoped_unlock unlock(mLock);
3577 mPolicy.notifyDeviceInteraction(deviceId, eventTime, uids);
3578 };
3579 postCommandLocked(std::move(command));
3580
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003581 if (newConnectionTokens == mInteractionConnectionTokens) {
3582 return; // no change
3583 }
3584 mInteractionConnectionTokens = newConnectionTokens;
3585
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003586 std::string targetList;
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003587 for (const std::shared_ptr<Connection>& connection : newConnections) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003588 targetList += connection->getWindowName() + ", ";
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003589 }
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003590 std::string message = "Interaction with: " + targetList;
3591 if (targetList.empty()) {
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003592 message += "<none>";
3593 }
3594 android_log_event_list(LOGTAG_INPUT_INTERACTION) << message << LOG_ID_EVENTS;
3595}
3596
chaviwfd6d3512019-03-25 13:23:49 -07003597void InputDispatcher::dispatchPointerDownOutsideFocus(uint32_t source, int32_t action,
Vishnu Nairad321cd2020-08-20 16:40:21 -07003598 const sp<IBinder>& token) {
chaviw8c9cf542019-03-25 13:02:48 -07003599 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
chaviwfd6d3512019-03-25 13:23:49 -07003600 uint32_t maskedSource = source & AINPUT_SOURCE_CLASS_MASK;
3601 if (maskedSource != AINPUT_SOURCE_CLASS_POINTER || maskedAction != AMOTION_EVENT_ACTION_DOWN) {
chaviw8c9cf542019-03-25 13:02:48 -07003602 return;
3603 }
3604
Vishnu Nairc519ff72021-01-21 08:23:08 -08003605 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07003606 if (focusedToken == token) {
3607 // ignore since token is focused
chaviw8c9cf542019-03-25 13:02:48 -07003608 return;
3609 }
3610
Prabir Pradhancef936d2021-07-21 16:17:52 +00003611 auto command = [this, token]() REQUIRES(mLock) {
3612 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00003613 mPolicy.onPointerDownOutsideFocus(token);
Prabir Pradhancef936d2021-07-21 16:17:52 +00003614 };
3615 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003616}
3617
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003618status_t InputDispatcher::publishMotionEvent(Connection& connection,
3619 DispatchEntry& dispatchEntry) const {
3620 const EventEntry& eventEntry = *(dispatchEntry.eventEntry);
3621 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
3622
3623 PointerCoords scaledCoords[MAX_POINTERS];
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07003624 const PointerCoords* usingCoords = motionEntry.pointerCoords.data();
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003625
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00003626 // TODO(b/316355518): Do not modify coords before dispatch.
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003627 // Set the X and Y offset and X and Y scale depending on the input source.
3628 if ((motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) &&
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003629 !(dispatchEntry.targetFlags.test(InputTarget::Flags::ZERO_COORDS))) {
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003630 float globalScaleFactor = dispatchEntry.globalScaleFactor;
3631 if (globalScaleFactor != 1.0f) {
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07003632 for (uint32_t i = 0; i < motionEntry.getPointerCount(); i++) {
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003633 scaledCoords[i] = motionEntry.pointerCoords[i];
3634 // Don't apply window scale here since we don't want scale to affect raw
3635 // coordinates. The scale will be sent back to the client and applied
3636 // later when requesting relative coordinates.
Harry Cutts33476232023-01-30 19:57:29 +00003637 scaledCoords[i].scale(globalScaleFactor, /*windowXScale=*/1, /*windowYScale=*/1);
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003638 }
3639 usingCoords = scaledCoords;
3640 }
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003641 } else if (dispatchEntry.targetFlags.test(InputTarget::Flags::ZERO_COORDS)) {
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003642 // We don't want the dispatch target to know the coordinates
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07003643 for (uint32_t i = 0; i < motionEntry.getPointerCount(); i++) {
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003644 scaledCoords[i].clear();
3645 }
3646 usingCoords = scaledCoords;
3647 }
3648
3649 std::array<uint8_t, 32> hmac = getSignature(motionEntry, dispatchEntry);
3650
3651 // Publish the motion event.
3652 return connection.inputPublisher
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003653 .publishMotionEvent(dispatchEntry.seq, motionEntry.id, motionEntry.deviceId,
3654 motionEntry.source, motionEntry.displayId, std::move(hmac),
3655 motionEntry.action, motionEntry.actionButton,
3656 dispatchEntry.resolvedFlags, motionEntry.edgeFlags,
3657 motionEntry.metaState, motionEntry.buttonState,
3658 motionEntry.classification, dispatchEntry.transform,
3659 motionEntry.xPrecision, motionEntry.yPrecision,
3660 motionEntry.xCursorPosition, motionEntry.yCursorPosition,
3661 dispatchEntry.rawTransform, motionEntry.downTime,
3662 motionEntry.eventTime, motionEntry.getPointerCount(),
3663 motionEntry.pointerProperties.data(), usingCoords);
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003664}
3665
Michael Wrightd02c5b62014-02-10 15:10:22 -08003666void InputDispatcher::startDispatchCycleLocked(nsecs_t currentTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003667 const std::shared_ptr<Connection>& connection) {
Prabir Pradhan2dac8b82023-09-06 01:11:51 +00003668 ATRACE_NAME_IF(ATRACE_ENABLED(),
3669 StringPrintf("startDispatchCycleLocked(inputChannel=%s)",
3670 connection->getInputChannelName().c_str()));
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003671 if (DEBUG_DISPATCH_CYCLE) {
3672 ALOGD("channel '%s' ~ startDispatchCycle", connection->getInputChannelName().c_str());
3673 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003674
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003675 while (connection->status == Connection::Status::NORMAL && !connection->outboundQueue.empty()) {
Prabir Pradhan8c90d782023-09-15 21:16:44 +00003676 std::unique_ptr<DispatchEntry>& dispatchEntry = connection->outboundQueue.front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003677 dispatchEntry->deliveryTime = currentTime;
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003678 const std::chrono::nanoseconds timeout = getDispatchingTimeoutLocked(connection);
Siarhei Vishniakou70622952020-07-30 11:17:23 -05003679 dispatchEntry->timeoutTime = currentTime + timeout.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003680
3681 // Publish the event.
3682 status_t status;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003683 const EventEntry& eventEntry = *(dispatchEntry->eventEntry);
3684 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003685 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003686 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
3687 std::array<uint8_t, 32> hmac = getSignature(keyEntry, *dispatchEntry);
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08003688 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07003689 LOG(INFO) << "Publishing " << *dispatchEntry << " to "
3690 << connection->getInputChannelName();
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08003691 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003692
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003693 // Publish the key event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003694 status = connection->inputPublisher
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003695 .publishKeyEvent(dispatchEntry->seq, keyEntry.id,
3696 keyEntry.deviceId, keyEntry.source,
3697 keyEntry.displayId, std::move(hmac),
3698 keyEntry.action, dispatchEntry->resolvedFlags,
3699 keyEntry.keyCode, keyEntry.scanCode,
3700 keyEntry.metaState, keyEntry.repeatCount,
3701 keyEntry.downTime, keyEntry.eventTime);
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00003702 if (mTracer) {
3703 mTracer->traceEventDispatch(*dispatchEntry, keyEntry.traceTracker.get());
3704 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003705 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003706 }
3707
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003708 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08003709 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07003710 LOG(INFO) << "Publishing " << *dispatchEntry << " to "
3711 << connection->getInputChannelName();
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08003712 }
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00003713 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003714 status = publishMotionEvent(*connection, *dispatchEntry);
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00003715 if (mTracer) {
3716 mTracer->traceEventDispatch(*dispatchEntry, motionEntry.traceTracker.get());
3717 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003718 break;
3719 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003720
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003721 case EventEntry::Type::FOCUS: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003722 const FocusEntry& focusEntry = static_cast<const FocusEntry&>(eventEntry);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003723 status = connection->inputPublisher.publishFocusEvent(dispatchEntry->seq,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003724 focusEntry.id,
Antonio Kantek3cfec7b2021-11-05 18:26:17 -07003725 focusEntry.hasFocus);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003726 break;
3727 }
3728
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003729 case EventEntry::Type::TOUCH_MODE_CHANGED: {
3730 const TouchModeEntry& touchModeEntry =
3731 static_cast<const TouchModeEntry&>(eventEntry);
3732 status = connection->inputPublisher
3733 .publishTouchModeEvent(dispatchEntry->seq, touchModeEntry.id,
3734 touchModeEntry.inTouchMode);
3735
3736 break;
3737 }
3738
Prabir Pradhan99987712020-11-10 18:43:05 -08003739 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
3740 const auto& captureEntry =
3741 static_cast<const PointerCaptureChangedEntry&>(eventEntry);
3742 status = connection->inputPublisher
3743 .publishCaptureEvent(dispatchEntry->seq, captureEntry.id,
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00003744 captureEntry.pointerCaptureRequest.enable);
Prabir Pradhan99987712020-11-10 18:43:05 -08003745 break;
3746 }
3747
arthurhungb89ccb02020-12-30 16:19:01 +08003748 case EventEntry::Type::DRAG: {
3749 const DragEntry& dragEntry = static_cast<const DragEntry&>(eventEntry);
3750 status = connection->inputPublisher.publishDragEvent(dispatchEntry->seq,
3751 dragEntry.id, dragEntry.x,
3752 dragEntry.y,
3753 dragEntry.isExiting);
3754 break;
3755 }
3756
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003757 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07003758 case EventEntry::Type::DEVICE_RESET:
3759 case EventEntry::Type::SENSOR: {
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003760 LOG_ALWAYS_FATAL("Should never start dispatch cycles for %s events",
Dominik Laskowski75788452021-02-09 18:51:25 -08003761 ftl::enum_string(eventEntry.type).c_str());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003762 return;
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003763 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003764 }
3765
3766 // Check the result.
3767 if (status) {
3768 if (status == WOULD_BLOCK) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003769 if (connection->waitQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003770 ALOGE("channel '%s' ~ Could not publish event because the pipe is full. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003771 "This is unexpected because the wait queue is empty, so the pipe "
3772 "should be empty and we shouldn't have any problems writing an "
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +00003773 "event to it, status=%s(%d)",
3774 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3775 status);
Harry Cutts33476232023-01-30 19:57:29 +00003776 abortBrokenDispatchCycleLocked(currentTime, connection, /*notify=*/true);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003777 } else {
3778 // Pipe is full and we are waiting for the app to finish process some events
3779 // before sending more events to it.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003780 if (DEBUG_DISPATCH_CYCLE) {
3781 ALOGD("channel '%s' ~ Could not publish event because the pipe is full, "
3782 "waiting for the application to catch up",
3783 connection->getInputChannelName().c_str());
3784 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003785 }
3786 } else {
3787 ALOGE("channel '%s' ~ Could not publish event due to an unexpected error, "
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +00003788 "status=%s(%d)",
3789 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3790 status);
Harry Cutts33476232023-01-30 19:57:29 +00003791 abortBrokenDispatchCycleLocked(currentTime, connection, /*notify=*/true);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003792 }
3793 return;
3794 }
3795
3796 // Re-enqueue the event on the wait queue.
Prabir Pradhan8c90d782023-09-15 21:16:44 +00003797 const nsecs_t timeoutTime = dispatchEntry->timeoutTime;
3798 connection->waitQueue.emplace_back(std::move(dispatchEntry));
3799 connection->outboundQueue.erase(connection->outboundQueue.begin());
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003800 traceOutboundQueueLength(*connection);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003801 if (connection->responsive) {
Prabir Pradhan8c90d782023-09-15 21:16:44 +00003802 mAnrTracker.insert(timeoutTime, connection->inputChannel->getConnectionToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003803 }
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003804 traceWaitQueueLength(*connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003805 }
3806}
3807
chaviw09c8d2d2020-08-24 15:48:26 -07003808std::array<uint8_t, 32> InputDispatcher::sign(const VerifiedInputEvent& event) const {
3809 size_t size;
3810 switch (event.type) {
3811 case VerifiedInputEvent::Type::KEY: {
3812 size = sizeof(VerifiedKeyEvent);
3813 break;
3814 }
3815 case VerifiedInputEvent::Type::MOTION: {
3816 size = sizeof(VerifiedMotionEvent);
3817 break;
3818 }
3819 }
3820 const uint8_t* start = reinterpret_cast<const uint8_t*>(&event);
3821 return mHmacKeyManager.sign(start, size);
3822}
3823
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003824const std::array<uint8_t, 32> InputDispatcher::getSignature(
3825 const MotionEntry& motionEntry, const DispatchEntry& dispatchEntry) const {
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003826 const int32_t actionMasked = MotionEvent::getActionMasked(motionEntry.action);
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003827 if (actionMasked != AMOTION_EVENT_ACTION_UP && actionMasked != AMOTION_EVENT_ACTION_DOWN) {
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003828 // Only sign events up and down events as the purely move events
3829 // are tied to their up/down counterparts so signing would be redundant.
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003830 return INVALID_HMAC;
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003831 }
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003832
3833 VerifiedMotionEvent verifiedEvent =
3834 verifiedMotionEventFromMotionEntry(motionEntry, dispatchEntry.rawTransform);
3835 verifiedEvent.actionMasked = actionMasked;
3836 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_MOTION_EVENT_FLAGS;
3837 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003838}
3839
3840const std::array<uint8_t, 32> InputDispatcher::getSignature(
3841 const KeyEntry& keyEntry, const DispatchEntry& dispatchEntry) const {
3842 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEntry(keyEntry);
3843 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_KEY_EVENT_FLAGS;
chaviw09c8d2d2020-08-24 15:48:26 -07003844 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003845}
3846
Michael Wrightd02c5b62014-02-10 15:10:22 -08003847void InputDispatcher::finishDispatchCycleLocked(nsecs_t currentTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003848 const std::shared_ptr<Connection>& connection,
3849 uint32_t seq, bool handled, nsecs_t consumeTime) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003850 if (DEBUG_DISPATCH_CYCLE) {
3851 ALOGD("channel '%s' ~ finishDispatchCycle - seq=%u, handled=%s",
3852 connection->getInputChannelName().c_str(), seq, toString(handled));
3853 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003854
Prabir Pradhan98ca4a22024-01-09 23:51:50 +00003855 if (connection->status != Connection::Status::NORMAL) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003856 return;
3857 }
3858
3859 // Notify other system components and prepare to start the next dispatch cycle.
Prabir Pradhancef936d2021-07-21 16:17:52 +00003860 auto command = [this, currentTime, connection, seq, handled, consumeTime]() REQUIRES(mLock) {
3861 doDispatchCycleFinishedCommand(currentTime, connection, seq, handled, consumeTime);
3862 };
3863 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003864}
3865
3866void InputDispatcher::abortBrokenDispatchCycleLocked(nsecs_t currentTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003867 const std::shared_ptr<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003868 bool notify) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003869 if (DEBUG_DISPATCH_CYCLE) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07003870 LOG(INFO) << "channel '" << connection->getInputChannelName() << "'~ " << __func__
3871 << " - notify=" << toString(notify);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003872 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003873
3874 // Clear the dispatch queues.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003875 drainDispatchQueue(connection->outboundQueue);
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003876 traceOutboundQueueLength(*connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003877 drainDispatchQueue(connection->waitQueue);
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003878 traceWaitQueueLength(*connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003879
3880 // The connection appears to be unrecoverably broken.
3881 // Ignore already broken or zombie connections.
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003882 if (connection->status == Connection::Status::NORMAL) {
3883 connection->status = Connection::Status::BROKEN;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003884
3885 if (notify) {
3886 // Notify other system components.
Prabir Pradhancef936d2021-07-21 16:17:52 +00003887 ALOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
3888 connection->getInputChannelName().c_str());
3889
3890 auto command = [this, connection]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00003891 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00003892 mPolicy.notifyInputChannelBroken(connection->inputChannel->getConnectionToken());
Prabir Pradhancef936d2021-07-21 16:17:52 +00003893 };
3894 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003895 }
3896 }
3897}
3898
Prabir Pradhan8c90d782023-09-15 21:16:44 +00003899void InputDispatcher::drainDispatchQueue(std::deque<std::unique_ptr<DispatchEntry>>& queue) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003900 while (!queue.empty()) {
Prabir Pradhan8c90d782023-09-15 21:16:44 +00003901 releaseDispatchEntry(std::move(queue.front()));
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003902 queue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003903 }
3904}
3905
Prabir Pradhan8c90d782023-09-15 21:16:44 +00003906void InputDispatcher::releaseDispatchEntry(std::unique_ptr<DispatchEntry> dispatchEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003907 if (dispatchEntry->hasForegroundTarget()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003908 decrementPendingForegroundDispatches(*(dispatchEntry->eventEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003909 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003910}
3911
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003912int InputDispatcher::handleReceiveCallback(int events, sp<IBinder> connectionToken) {
3913 std::scoped_lock _l(mLock);
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003914 std::shared_ptr<Connection> connection = getConnectionLocked(connectionToken);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003915 if (connection == nullptr) {
3916 ALOGW("Received looper callback for unknown input channel token %p. events=0x%x",
3917 connectionToken.get(), events);
3918 return 0; // remove the callback
3919 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003920
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003921 bool notify;
3922 if (!(events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP))) {
3923 if (!(events & ALOOPER_EVENT_INPUT)) {
3924 ALOGW("channel '%s' ~ Received spurious callback for unhandled poll event. "
3925 "events=0x%x",
3926 connection->getInputChannelName().c_str(), events);
3927 return 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003928 }
3929
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003930 nsecs_t currentTime = now();
3931 bool gotOne = false;
3932 status_t status = OK;
3933 for (;;) {
3934 Result<InputPublisher::ConsumerResponse> result =
3935 connection->inputPublisher.receiveConsumerResponse();
3936 if (!result.ok()) {
3937 status = result.error().code();
3938 break;
3939 }
3940
3941 if (std::holds_alternative<InputPublisher::Finished>(*result)) {
3942 const InputPublisher::Finished& finish =
3943 std::get<InputPublisher::Finished>(*result);
3944 finishDispatchCycleLocked(currentTime, connection, finish.seq, finish.handled,
3945 finish.consumeTime);
3946 } else if (std::holds_alternative<InputPublisher::Timeline>(*result)) {
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00003947 if (shouldReportMetricsForConnection(*connection)) {
3948 const InputPublisher::Timeline& timeline =
3949 std::get<InputPublisher::Timeline>(*result);
3950 mLatencyTracker
3951 .trackGraphicsLatency(timeline.inputEventId,
3952 connection->inputChannel->getConnectionToken(),
3953 std::move(timeline.graphicsTimeline));
3954 }
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003955 }
3956 gotOne = true;
3957 }
3958 if (gotOne) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00003959 runCommandsLockedInterruptable();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003960 if (status == WOULD_BLOCK) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003961 return 1;
3962 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003963 }
3964
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003965 notify = status != DEAD_OBJECT || !connection->monitor;
3966 if (notify) {
3967 ALOGE("channel '%s' ~ Failed to receive finished signal. status=%s(%d)",
3968 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3969 status);
3970 }
3971 } else {
3972 // Monitor channels are never explicitly unregistered.
3973 // We do it automatically when the remote endpoint is closed so don't warn about them.
3974 const bool stillHaveWindowHandle =
3975 getWindowHandleLocked(connection->inputChannel->getConnectionToken()) != nullptr;
3976 notify = !connection->monitor && stillHaveWindowHandle;
3977 if (notify) {
3978 ALOGW("channel '%s' ~ Consumer closed input channel or an error occurred. events=0x%x",
3979 connection->getInputChannelName().c_str(), events);
3980 }
3981 }
3982
3983 // Remove the channel.
3984 removeInputChannelLocked(connection->inputChannel->getConnectionToken(), notify);
3985 return 0; // remove the callback
Michael Wrightd02c5b62014-02-10 15:10:22 -08003986}
3987
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003988void InputDispatcher::synthesizeCancelationEventsForAllConnectionsLocked(
Michael Wrightd02c5b62014-02-10 15:10:22 -08003989 const CancelationOptions& options) {
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003990 for (const auto& [token, connection] : mConnectionsByToken) {
Siarhei Vishniakou2e2ea992020-12-15 02:57:19 +00003991 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003992 }
3993}
3994
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003995void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
Michael Wrightfa13dcf2015-06-12 13:25:11 +01003996 const CancelationOptions& options) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08003997 for (const auto& [_, monitors] : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003998 for (const Monitor& monitor : monitors) {
3999 synthesizeCancelationEventsForInputChannelLocked(monitor.inputChannel, options);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004000 }
Michael Wrightfa13dcf2015-06-12 13:25:11 +01004001 }
4002}
4003
Michael Wrightd02c5b62014-02-10 15:10:22 -08004004void InputDispatcher::synthesizeCancelationEventsForInputChannelLocked(
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004005 const std::shared_ptr<InputChannel>& channel, const CancelationOptions& options) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07004006 std::shared_ptr<Connection> connection = getConnectionLocked(channel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004007 if (connection == nullptr) {
4008 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004009 }
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004010
4011 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004012}
4013
4014void InputDispatcher::synthesizeCancelationEventsForConnectionLocked(
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07004015 const std::shared_ptr<Connection>& connection, const CancelationOptions& options) {
Prabir Pradhanb13da8f2024-01-09 23:10:13 +00004016 if (connection->status != Connection::Status::NORMAL) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004017 return;
4018 }
4019
4020 nsecs_t currentTime = now();
4021
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004022 std::vector<std::unique_ptr<EventEntry>> cancelationEvents =
Siarhei Vishniakou00fca7c2019-10-29 13:05:57 -07004023 connection->inputState.synthesizeCancelationEvents(currentTime, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004024
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004025 if (cancelationEvents.empty()) {
4026 return;
4027 }
Vaibhav Devmurari110ba322023-11-17 10:47:16 +00004028
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004029 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
4030 ALOGD("channel '%s' ~ Synthesized %zu cancelation events to bring channel back in sync "
Siarhei Vishniakou2e3e4432023-02-09 18:34:11 -08004031 "with reality: %s, mode=%s.",
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004032 connection->getInputChannelName().c_str(), cancelationEvents.size(), options.reason,
Siarhei Vishniakou2e3e4432023-02-09 18:34:11 -08004033 ftl::enum_string(options.mode).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004034 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08004035
Arthur Hungb3307ee2021-10-14 10:57:37 +00004036 std::string reason = std::string("reason=").append(options.reason);
4037 android_log_event_list(LOGTAG_INPUT_CANCEL)
4038 << connection->getInputChannelName().c_str() << reason << LOG_ID_EVENTS;
4039
hongzuo liu95785e22022-09-06 02:51:35 +00004040 const bool wasEmpty = connection->outboundQueue.empty();
Prabir Pradhan16463382023-10-12 23:03:19 +00004041 // The target to use if we don't find a window associated with the channel.
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00004042 const InputTarget fallbackTarget{.inputChannel = connection->inputChannel};
Prabir Pradhan16463382023-10-12 23:03:19 +00004043 const auto& token = connection->inputChannel->getConnectionToken();
hongzuo liu95785e22022-09-06 02:51:35 +00004044
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004045 for (size_t i = 0; i < cancelationEvents.size(); i++) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004046 std::unique_ptr<EventEntry> cancelationEventEntry = std::move(cancelationEvents[i]);
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00004047 std::vector<InputTarget> targets{};
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00004048
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004049 switch (cancelationEventEntry->type) {
4050 case EventEntry::Type::KEY: {
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00004051 const auto& keyEntry = static_cast<const KeyEntry&>(*cancelationEventEntry);
Prabir Pradhan16463382023-10-12 23:03:19 +00004052 const std::optional<int32_t> targetDisplay = keyEntry.displayId != ADISPLAY_ID_NONE
4053 ? std::make_optional(keyEntry.displayId)
4054 : std::nullopt;
4055 if (const auto& window = getWindowHandleLocked(token, targetDisplay); window) {
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00004056 addWindowTargetLocked(window, InputTarget::DispatchMode::AS_IS,
4057 /*targetFlags=*/{}, keyEntry.downTime, targets);
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00004058 } else {
4059 targets.emplace_back(fallbackTarget);
4060 }
4061 logOutboundKeyDetails("cancel - ", keyEntry);
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004062 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004063 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004064 case EventEntry::Type::MOTION: {
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00004065 const auto& motionEntry = static_cast<const MotionEntry&>(*cancelationEventEntry);
Prabir Pradhan16463382023-10-12 23:03:19 +00004066 const std::optional<int32_t> targetDisplay =
4067 motionEntry.displayId != ADISPLAY_ID_NONE
4068 ? std::make_optional(motionEntry.displayId)
4069 : std::nullopt;
4070 if (const auto& window = getWindowHandleLocked(token, targetDisplay); window) {
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00004071 std::bitset<MAX_POINTER_ID + 1> pointerIds;
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004072 for (uint32_t pointerIndex = 0; pointerIndex < motionEntry.getPointerCount();
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00004073 pointerIndex++) {
4074 pointerIds.set(motionEntry.pointerProperties[pointerIndex].id);
4075 }
Vaibhav Devmurari110ba322023-11-17 10:47:16 +00004076 if (mDragState && mDragState->dragWindow->getToken() == token &&
4077 pointerIds.test(mDragState->pointerId)) {
4078 LOG(INFO) << __func__
4079 << ": Canceling drag and drop because the pointers for the drag "
4080 "window are being canceled.";
4081 sendDropWindowCommandLocked(nullptr, /*x=*/0, /*y=*/0);
4082 mDragState.reset();
4083 }
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00004084 addPointerWindowTargetLocked(window, InputTarget::DispatchMode::AS_IS,
4085 ftl::Flags<InputTarget::Flags>(), pointerIds,
4086 motionEntry.downTime, targets);
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00004087 } else {
4088 targets.emplace_back(fallbackTarget);
4089 const auto it = mDisplayInfos.find(motionEntry.displayId);
4090 if (it != mDisplayInfos.end()) {
4091 targets.back().displayTransform = it->second.transform;
4092 targets.back().setDefaultPointerTransform(it->second.transform);
4093 }
4094 }
4095 logOutboundMotionDetails("cancel - ", motionEntry);
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004096 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004097 }
Prabir Pradhan99987712020-11-10 18:43:05 -08004098 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07004099 case EventEntry::Type::TOUCH_MODE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08004100 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
4101 case EventEntry::Type::DRAG: {
Prabir Pradhan99987712020-11-10 18:43:05 -08004102 LOG_ALWAYS_FATAL("Canceling %s events is not supported",
Dominik Laskowski75788452021-02-09 18:51:25 -08004103 ftl::enum_string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004104 break;
4105 }
4106 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07004107 case EventEntry::Type::DEVICE_RESET:
4108 case EventEntry::Type::SENSOR: {
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004109 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Dominik Laskowski75788452021-02-09 18:51:25 -08004110 ftl::enum_string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004111 break;
4112 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004113 }
4114
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00004115 if (targets.size() != 1) LOG(FATAL) << __func__ << ": InputTarget not created";
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00004116 enqueueDispatchEntryLocked(connection, std::move(cancelationEventEntry), targets[0]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004117 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004118
hongzuo liu95785e22022-09-06 02:51:35 +00004119 // If the outbound queue was previously empty, start the dispatch cycle going.
4120 if (wasEmpty && !connection->outboundQueue.empty()) {
4121 startDispatchCycleLocked(currentTime, connection);
4122 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004123}
4124
Svet Ganov5d3bc372020-01-26 23:11:07 -08004125void InputDispatcher::synthesizePointerDownEventsForConnectionLocked(
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07004126 const nsecs_t downTime, const std::shared_ptr<Connection>& connection,
Arthur Hungc539dbb2022-12-08 07:45:36 +00004127 ftl::Flags<InputTarget::Flags> targetFlags) {
Prabir Pradhan98ca4a22024-01-09 23:51:50 +00004128 if (connection->status != Connection::Status::NORMAL) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08004129 return;
4130 }
4131
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004132 std::vector<std::unique_ptr<EventEntry>> downEvents =
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00004133 connection->inputState.synthesizePointerDownEvents(downTime);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004134
4135 if (downEvents.empty()) {
4136 return;
4137 }
4138
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004139 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08004140 ALOGD("channel '%s' ~ Synthesized %zu down events to ensure consistent event stream.",
4141 connection->getInputChannelName().c_str(), downEvents.size());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004142 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08004143
chaviw98318de2021-05-19 16:45:23 -05004144 sp<WindowInfoHandle> windowHandle =
Svet Ganov5d3bc372020-01-26 23:11:07 -08004145 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
Svet Ganov5d3bc372020-01-26 23:11:07 -08004146
hongzuo liu95785e22022-09-06 02:51:35 +00004147 const bool wasEmpty = connection->outboundQueue.empty();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004148 for (std::unique_ptr<EventEntry>& downEventEntry : downEvents) {
Prabir Pradhan1c29a092023-09-21 10:29:29 +00004149 std::vector<InputTarget> targets{};
Svet Ganov5d3bc372020-01-26 23:11:07 -08004150 switch (downEventEntry->type) {
4151 case EventEntry::Type::MOTION: {
Prabir Pradhan1c29a092023-09-21 10:29:29 +00004152 const auto& motionEntry = static_cast<const MotionEntry&>(*downEventEntry);
4153 if (windowHandle != nullptr) {
4154 std::bitset<MAX_POINTER_ID + 1> pointerIds;
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004155 for (uint32_t pointerIndex = 0; pointerIndex < motionEntry.getPointerCount();
Prabir Pradhan1c29a092023-09-21 10:29:29 +00004156 pointerIndex++) {
4157 pointerIds.set(motionEntry.pointerProperties[pointerIndex].id);
4158 }
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00004159 addPointerWindowTargetLocked(windowHandle, InputTarget::DispatchMode::AS_IS,
4160 targetFlags, pointerIds, motionEntry.downTime,
4161 targets);
Prabir Pradhan1c29a092023-09-21 10:29:29 +00004162 } else {
4163 targets.emplace_back(InputTarget{.inputChannel = connection->inputChannel,
4164 .flags = targetFlags});
4165 const auto it = mDisplayInfos.find(motionEntry.displayId);
4166 if (it != mDisplayInfos.end()) {
4167 targets.back().displayTransform = it->second.transform;
4168 targets.back().setDefaultPointerTransform(it->second.transform);
4169 }
4170 }
4171 logOutboundMotionDetails("down - ", motionEntry);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004172 break;
4173 }
4174
4175 case EventEntry::Type::KEY:
4176 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07004177 case EventEntry::Type::TOUCH_MODE_CHANGED:
Svet Ganov5d3bc372020-01-26 23:11:07 -08004178 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08004179 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07004180 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08004181 case EventEntry::Type::SENSOR:
4182 case EventEntry::Type::DRAG: {
Svet Ganov5d3bc372020-01-26 23:11:07 -08004183 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Dominik Laskowski75788452021-02-09 18:51:25 -08004184 ftl::enum_string(downEventEntry->type).c_str());
Svet Ganov5d3bc372020-01-26 23:11:07 -08004185 break;
4186 }
4187 }
4188
Prabir Pradhan1c29a092023-09-21 10:29:29 +00004189 if (targets.size() != 1) LOG(FATAL) << __func__ << ": InputTarget not created";
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00004190 enqueueDispatchEntryLocked(connection, std::move(downEventEntry), targets[0]);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004191 }
4192
hongzuo liu95785e22022-09-06 02:51:35 +00004193 // If the outbound queue was previously empty, start the dispatch cycle going.
4194 if (wasEmpty && !connection->outboundQueue.empty()) {
4195 startDispatchCycleLocked(downTime, connection);
4196 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08004197}
4198
Arthur Hungc539dbb2022-12-08 07:45:36 +00004199void InputDispatcher::synthesizeCancelationEventsForWindowLocked(
4200 const sp<WindowInfoHandle>& windowHandle, const CancelationOptions& options) {
4201 if (windowHandle != nullptr) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07004202 std::shared_ptr<Connection> wallpaperConnection =
4203 getConnectionLocked(windowHandle->getToken());
Arthur Hungc539dbb2022-12-08 07:45:36 +00004204 if (wallpaperConnection != nullptr) {
4205 synthesizeCancelationEventsForConnectionLocked(wallpaperConnection, options);
4206 }
4207 }
4208}
4209
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004210std::unique_ptr<MotionEntry> InputDispatcher::splitMotionEvent(
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08004211 const MotionEntry& originalMotionEntry, std::bitset<MAX_POINTER_ID + 1> pointerIds,
4212 nsecs_t splitDownTime) {
4213 ALOG_ASSERT(pointerIds.any());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004214
4215 uint32_t splitPointerIndexMap[MAX_POINTERS];
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004216 std::vector<PointerProperties> splitPointerProperties;
4217 std::vector<PointerCoords> splitPointerCoords;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004218
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004219 uint32_t originalPointerCount = originalMotionEntry.getPointerCount();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004220 uint32_t splitPointerCount = 0;
4221
4222 for (uint32_t originalPointerIndex = 0; originalPointerIndex < originalPointerCount;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004223 originalPointerIndex++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004224 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07004225 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08004226 uint32_t pointerId = uint32_t(pointerProperties.id);
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08004227 if (pointerIds.test(pointerId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004228 splitPointerIndexMap[splitPointerCount] = originalPointerIndex;
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004229 splitPointerProperties.push_back(pointerProperties);
4230 splitPointerCoords.push_back(originalMotionEntry.pointerCoords[originalPointerIndex]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004231 splitPointerCount += 1;
4232 }
4233 }
4234
4235 if (splitPointerCount != pointerIds.count()) {
4236 // This is bad. We are missing some of the pointers that we expected to deliver.
4237 // Most likely this indicates that we received an ACTION_MOVE events that has
4238 // different pointer ids than we expected based on the previous ACTION_DOWN
4239 // or ACTION_POINTER_DOWN events that caused us to decide to split the pointers
4240 // in this way.
4241 ALOGW("Dropping split motion event because the pointer count is %d but "
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08004242 "we expected there to be %zu pointers. This probably means we received "
Siarhei Vishniakou16e4fa02023-02-16 17:48:56 -08004243 "a broken sequence of pointer ids from the input device: %s",
4244 splitPointerCount, pointerIds.count(), originalMotionEntry.getDescription().c_str());
Yi Kong9b14ac62018-07-17 13:48:38 -07004245 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004246 }
4247
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07004248 int32_t action = originalMotionEntry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004249 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004250 if (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN ||
4251 maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
Siarhei Vishniakou5b9766d2023-07-18 14:06:29 -07004252 int32_t originalPointerIndex = MotionEvent::getActionIndex(action);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004253 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07004254 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08004255 uint32_t pointerId = uint32_t(pointerProperties.id);
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08004256 if (pointerIds.test(pointerId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004257 if (pointerIds.count() == 1) {
4258 // The first/last pointer went down/up.
4259 action = maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004260 ? AMOTION_EVENT_ACTION_DOWN
arthurhungea3f4fc2020-12-21 23:18:53 +08004261 : (originalMotionEntry.flags & AMOTION_EVENT_FLAG_CANCELED) != 0
4262 ? AMOTION_EVENT_ACTION_CANCEL
4263 : AMOTION_EVENT_ACTION_UP;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004264 } else {
4265 // A secondary pointer went down/up.
4266 uint32_t splitPointerIndex = 0;
4267 while (pointerId != uint32_t(splitPointerProperties[splitPointerIndex].id)) {
4268 splitPointerIndex += 1;
4269 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004270 action = maskedAction |
4271 (splitPointerIndex << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004272 }
4273 } else {
4274 // An unrelated pointer changed.
4275 action = AMOTION_EVENT_ACTION_MOVE;
4276 }
4277 }
4278
Siarhei Vishniakou59e302b2023-06-05 08:04:53 -07004279 if (action == AMOTION_EVENT_ACTION_DOWN && splitDownTime != originalMotionEntry.eventTime) {
4280 logDispatchStateLocked();
4281 LOG_ALWAYS_FATAL("Split motion event has mismatching downTime and eventTime for "
4282 "ACTION_DOWN, motionEntry=%s, splitDownTime=%" PRId64,
4283 originalMotionEntry.getDescription().c_str(), splitDownTime);
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00004284 }
4285
Garfield Tanff1f1bb2020-01-28 13:24:04 -08004286 int32_t newId = mIdGenerator.nextId();
Prabir Pradhan2dac8b82023-09-06 01:11:51 +00004287 ATRACE_NAME_IF(ATRACE_ENABLED(),
4288 StringPrintf("Split MotionEvent(id=0x%" PRIx32 ") to MotionEvent(id=0x%" PRIx32
4289 ").",
4290 originalMotionEntry.id, newId));
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004291 std::unique_ptr<MotionEntry> splitMotionEntry =
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00004292 std::make_unique<MotionEntry>(newId, originalMotionEntry.injectionState,
4293 originalMotionEntry.eventTime,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004294 originalMotionEntry.deviceId, originalMotionEntry.source,
4295 originalMotionEntry.displayId,
4296 originalMotionEntry.policyFlags, action,
4297 originalMotionEntry.actionButton,
4298 originalMotionEntry.flags, originalMotionEntry.metaState,
4299 originalMotionEntry.buttonState,
4300 originalMotionEntry.classification,
4301 originalMotionEntry.edgeFlags,
4302 originalMotionEntry.xPrecision,
4303 originalMotionEntry.yPrecision,
4304 originalMotionEntry.xCursorPosition,
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00004305 originalMotionEntry.yCursorPosition, splitDownTime,
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004306 splitPointerProperties, splitPointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004307
Michael Wrightd02c5b62014-02-10 15:10:22 -08004308 return splitMotionEntry;
4309}
4310
Asmita Poddardd9a6cd2023-09-26 15:35:12 +00004311void InputDispatcher::notifyInputDevicesChanged(const NotifyInputDevicesChangedArgs& args) {
4312 std::scoped_lock _l(mLock);
4313 mLatencyTracker.setInputDevices(args.inputDeviceInfos);
4314}
4315
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004316void InputDispatcher::notifyConfigurationChanged(const NotifyConfigurationChangedArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004317 if (debugInboundEventDetails()) {
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004318 ALOGD("notifyConfigurationChanged - eventTime=%" PRId64, args.eventTime);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004319 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004320
Antonio Kantekf16f2832021-09-28 04:39:20 +00004321 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004322 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004323 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004324
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004325 std::unique_ptr<ConfigurationChangedEntry> newEntry =
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004326 std::make_unique<ConfigurationChangedEntry>(args.id, args.eventTime);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004327 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004328 } // release lock
4329
4330 if (needWake) {
4331 mLooper->wake();
4332 }
4333}
4334
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004335void InputDispatcher::notifyKey(const NotifyKeyArgs& args) {
Prabir Pradhan96282b02023-02-24 22:36:17 +00004336 ALOGD_IF(debugInboundEventDetails(),
4337 "notifyKey - id=%" PRIx32 ", eventTime=%" PRId64
4338 ", deviceId=%d, source=%s, displayId=%" PRId32
4339 "policyFlags=0x%x, action=%s, flags=0x%x, keyCode=%s, scanCode=0x%x, metaState=0x%x, "
4340 "downTime=%" PRId64,
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004341 args.id, args.eventTime, args.deviceId, inputEventSourceToString(args.source).c_str(),
4342 args.displayId, args.policyFlags, KeyEvent::actionToString(args.action), args.flags,
4343 KeyEvent::getLabel(args.keyCode), args.scanCode, args.metaState, args.downTime);
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004344 Result<void> keyCheck = validateKeyEvent(args.action);
4345 if (!keyCheck.ok()) {
4346 LOG(ERROR) << "invalid key event: " << keyCheck.error();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004347 return;
4348 }
4349
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004350 uint32_t policyFlags = args.policyFlags;
4351 int32_t flags = args.flags;
4352 int32_t metaState = args.metaState;
Siarhei Vishniakou622bd322018-10-29 18:02:27 -07004353 // InputDispatcher tracks and generates key repeats on behalf of
4354 // whatever notifies it, so repeatCount should always be set to 0
4355 constexpr int32_t repeatCount = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004356 if ((policyFlags & POLICY_FLAG_VIRTUAL) || (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY)) {
4357 policyFlags |= POLICY_FLAG_VIRTUAL;
4358 flags |= AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
4359 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004360 if (policyFlags & POLICY_FLAG_FUNCTION) {
4361 metaState |= AMETA_FUNCTION_ON;
4362 }
4363
4364 policyFlags |= POLICY_FLAG_TRUSTED;
4365
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004366 int32_t keyCode = args.keyCode;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004367 KeyEvent event;
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004368 event.initialize(args.id, args.deviceId, args.source, args.displayId, INVALID_HMAC, args.action,
4369 flags, keyCode, args.scanCode, metaState, repeatCount, args.downTime,
4370 args.eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004371
Michael Wright2b3c3302018-03-02 17:19:13 +00004372 android::base::Timer t;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004373 mPolicy.interceptKeyBeforeQueueing(event, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00004374 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4375 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004376 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00004377 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004378
Antonio Kantekf16f2832021-09-28 04:39:20 +00004379 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004380 { // acquire lock
4381 mLock.lock();
4382
4383 if (shouldSendKeyToInputFilterLocked(args)) {
4384 mLock.unlock();
4385
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004386 policyFlags |= POLICY_FLAG_FILTERED;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004387 if (!mPolicy.filterInputEvent(event, policyFlags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004388 return; // event was consumed by the filter
4389 }
4390
4391 mLock.lock();
4392 }
4393
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004394 std::unique_ptr<KeyEntry> newEntry =
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00004395 std::make_unique<KeyEntry>(args.id, /*injectionState=*/nullptr, args.eventTime,
4396 args.deviceId, args.source, args.displayId, policyFlags,
4397 args.action, flags, keyCode, args.scanCode, metaState,
4398 repeatCount, args.downTime);
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00004399 if (mTracer) {
4400 newEntry->traceTracker = mTracer->traceInboundEvent(*newEntry);
4401 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004402
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004403 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004404 mLock.unlock();
4405 } // release lock
4406
4407 if (needWake) {
4408 mLooper->wake();
4409 }
4410}
4411
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004412bool InputDispatcher::shouldSendKeyToInputFilterLocked(const NotifyKeyArgs& args) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004413 return mInputFilterEnabled;
4414}
4415
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004416void InputDispatcher::notifyMotion(const NotifyMotionArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004417 if (debugInboundEventDetails()) {
Prabir Pradhan96282b02023-02-24 22:36:17 +00004418 ALOGD("notifyMotion - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=%s, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004419 "displayId=%" PRId32 ", policyFlags=0x%x, "
Siarhei Vishniakou6ebd0692022-10-20 15:05:45 -07004420 "action=%s, actionButton=0x%x, flags=0x%x, metaState=0x%x, buttonState=0x%x, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004421 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, xCursorPosition=%f, "
4422 "yCursorPosition=%f, downTime=%" PRId64,
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004423 args.id, args.eventTime, args.deviceId, inputEventSourceToString(args.source).c_str(),
4424 args.displayId, args.policyFlags, MotionEvent::actionToString(args.action).c_str(),
4425 args.actionButton, args.flags, args.metaState, args.buttonState, args.edgeFlags,
4426 args.xPrecision, args.yPrecision, args.xCursorPosition, args.yCursorPosition,
4427 args.downTime);
Siarhei Vishniakou3218fc02023-06-15 20:41:02 -07004428 for (uint32_t i = 0; i < args.getPointerCount(); i++) {
Prabir Pradhan96282b02023-02-24 22:36:17 +00004429 ALOGD(" Pointer %d: id=%d, toolType=%s, x=%f, y=%f, pressure=%f, size=%f, "
4430 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, orientation=%f",
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004431 i, args.pointerProperties[i].id,
4432 ftl::enum_string(args.pointerProperties[i].toolType).c_str(),
4433 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
4434 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
4435 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
4436 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
4437 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
4438 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
4439 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
4440 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
4441 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004442 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004443 }
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004444
Siarhei Vishniakou3218fc02023-06-15 20:41:02 -07004445 Result<void> motionCheck =
4446 validateMotionEvent(args.action, args.actionButton, args.getPointerCount(),
4447 args.pointerProperties.data());
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004448 if (!motionCheck.ok()) {
4449 LOG(FATAL) << "Invalid event: " << args.dump() << "; reason: " << motionCheck.error();
4450 return;
4451 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004452
Siarhei Vishniakou5c02a712023-05-15 15:45:02 -07004453 if (DEBUG_VERIFY_EVENTS) {
4454 auto [it, _] =
4455 mVerifiersByDisplay.try_emplace(args.displayId,
4456 StringPrintf("display %" PRId32, args.displayId));
4457 Result<void> result =
Siarhei Vishniakou2d151ac2023-09-19 13:30:24 -07004458 it->second.processMovement(args.deviceId, args.source, args.action,
4459 args.getPointerCount(), args.pointerProperties.data(),
4460 args.pointerCoords.data(), args.flags);
Siarhei Vishniakou5c02a712023-05-15 15:45:02 -07004461 if (!result.ok()) {
4462 LOG(FATAL) << "Bad stream: " << result.error() << " caused by " << args.dump();
4463 }
4464 }
4465
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004466 uint32_t policyFlags = args.policyFlags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004467 policyFlags |= POLICY_FLAG_TRUSTED;
Michael Wright2b3c3302018-03-02 17:19:13 +00004468
4469 android::base::Timer t;
Yeabkal Wubshit88a90412023-12-21 18:23:04 -08004470 mPolicy.interceptMotionBeforeQueueing(args.displayId, args.source, args.action, args.eventTime,
4471 policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00004472 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4473 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004474 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00004475 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004476
Antonio Kantekf16f2832021-09-28 04:39:20 +00004477 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004478 { // acquire lock
4479 mLock.lock();
Siarhei Vishniakou5bf25d92023-02-08 15:43:38 -08004480 if (!(policyFlags & POLICY_FLAG_PASS_TO_USER)) {
4481 // Set the flag anyway if we already have an ongoing gesture. That would allow us to
4482 // complete the processing of the current stroke.
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004483 const auto touchStateIt = mTouchStatesByDisplay.find(args.displayId);
Siarhei Vishniakou5bf25d92023-02-08 15:43:38 -08004484 if (touchStateIt != mTouchStatesByDisplay.end()) {
4485 const TouchState& touchState = touchStateIt->second;
Linnan Li907ae732023-09-05 17:14:21 +08004486 if (touchState.hasTouchingPointers(args.deviceId) ||
4487 touchState.hasHoveringPointers(args.deviceId)) {
Siarhei Vishniakou5bf25d92023-02-08 15:43:38 -08004488 policyFlags |= POLICY_FLAG_PASS_TO_USER;
4489 }
4490 }
4491 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004492
4493 if (shouldSendMotionToInputFilterLocked(args)) {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004494 ui::Transform displayTransform;
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004495 if (const auto it = mDisplayInfos.find(args.displayId); it != mDisplayInfos.end()) {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004496 displayTransform = it->second.transform;
4497 }
4498
Michael Wrightd02c5b62014-02-10 15:10:22 -08004499 mLock.unlock();
4500
4501 MotionEvent event;
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004502 event.initialize(args.id, args.deviceId, args.source, args.displayId, INVALID_HMAC,
4503 args.action, args.actionButton, args.flags, args.edgeFlags,
4504 args.metaState, args.buttonState, args.classification,
4505 displayTransform, args.xPrecision, args.yPrecision,
4506 args.xCursorPosition, args.yCursorPosition, displayTransform,
Siarhei Vishniakou3218fc02023-06-15 20:41:02 -07004507 args.downTime, args.eventTime, args.getPointerCount(),
4508 args.pointerProperties.data(), args.pointerCoords.data());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004509
4510 policyFlags |= POLICY_FLAG_FILTERED;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004511 if (!mPolicy.filterInputEvent(event, policyFlags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004512 return; // event was consumed by the filter
4513 }
4514
4515 mLock.lock();
4516 }
4517
4518 // Just enqueue a new motion event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004519 std::unique_ptr<MotionEntry> newEntry =
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00004520 std::make_unique<MotionEntry>(args.id, /*injectionState=*/nullptr, args.eventTime,
4521 args.deviceId, args.source, args.displayId,
4522 policyFlags, args.action, args.actionButton,
4523 args.flags, args.metaState, args.buttonState,
4524 args.classification, args.edgeFlags, args.xPrecision,
4525 args.yPrecision, args.xCursorPosition,
4526 args.yCursorPosition, args.downTime,
4527 args.pointerProperties, args.pointerCoords);
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00004528 if (mTracer) {
4529 newEntry->traceTracker = mTracer->traceInboundEvent(*newEntry);
4530 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004531
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004532 if (args.id != android::os::IInputConstants::INVALID_INPUT_EVENT_ID &&
4533 IdGenerator::getSource(args.id) == IdGenerator::Source::INPUT_READER &&
Siarhei Vishniakou363e7292021-07-09 03:22:42 +00004534 !mInputFilterEnabled) {
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004535 const bool isDown = args.action == AMOTION_EVENT_ACTION_DOWN;
Asmita Poddardd9a6cd2023-09-26 15:35:12 +00004536 std::set<InputDeviceUsageSource> sources = getUsageSourcesForMotionArgs(args);
4537 mLatencyTracker.trackListener(args.id, isDown, args.eventTime, args.readTime,
4538 args.deviceId, sources);
Siarhei Vishniakou363e7292021-07-09 03:22:42 +00004539 }
4540
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004541 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004542 mLock.unlock();
4543 } // release lock
4544
4545 if (needWake) {
4546 mLooper->wake();
4547 }
4548}
4549
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004550void InputDispatcher::notifySensor(const NotifySensorArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004551 if (debugInboundEventDetails()) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004552 ALOGD("notifySensor - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=0x%x, "
4553 " sensorType=%s",
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004554 args.id, args.eventTime, args.deviceId, args.source,
4555 ftl::enum_string(args.sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004556 }
Chris Yef59a2f42020-10-16 12:55:26 -07004557
Antonio Kantekf16f2832021-09-28 04:39:20 +00004558 bool needWake = false;
Chris Yef59a2f42020-10-16 12:55:26 -07004559 { // acquire lock
4560 mLock.lock();
4561
4562 // Just enqueue a new sensor event.
4563 std::unique_ptr<SensorEntry> newEntry =
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004564 std::make_unique<SensorEntry>(args.id, args.eventTime, args.deviceId, args.source,
4565 /* policyFlags=*/0, args.hwTimestamp, args.sensorType,
4566 args.accuracy, args.accuracyChanged, args.values);
Chris Yef59a2f42020-10-16 12:55:26 -07004567
4568 needWake = enqueueInboundEventLocked(std::move(newEntry));
4569 mLock.unlock();
4570 } // release lock
4571
4572 if (needWake) {
4573 mLooper->wake();
4574 }
4575}
4576
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004577void InputDispatcher::notifyVibratorState(const NotifyVibratorStateArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004578 if (debugInboundEventDetails()) {
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004579 ALOGD("notifyVibratorState - eventTime=%" PRId64 ", device=%d, isOn=%d", args.eventTime,
4580 args.deviceId, args.isOn);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004581 }
Prabir Pradhana41d2442023-04-20 21:30:40 +00004582 mPolicy.notifyVibratorState(args.deviceId, args.isOn);
Chris Yefb552902021-02-03 17:18:37 -08004583}
4584
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004585bool InputDispatcher::shouldSendMotionToInputFilterLocked(const NotifyMotionArgs& args) {
Jackal Guof9696682018-10-05 12:23:23 +08004586 return mInputFilterEnabled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004587}
4588
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004589void InputDispatcher::notifySwitch(const NotifySwitchArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004590 if (debugInboundEventDetails()) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004591 ALOGD("notifySwitch - eventTime=%" PRId64 ", policyFlags=0x%x, switchValues=0x%08x, "
4592 "switchMask=0x%08x",
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004593 args.eventTime, args.policyFlags, args.switchValues, args.switchMask);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004594 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004595
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004596 uint32_t policyFlags = args.policyFlags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004597 policyFlags |= POLICY_FLAG_TRUSTED;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004598 mPolicy.notifySwitch(args.eventTime, args.switchValues, args.switchMask, policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004599}
4600
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004601void InputDispatcher::notifyDeviceReset(const NotifyDeviceResetArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004602 if (debugInboundEventDetails()) {
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004603 ALOGD("notifyDeviceReset - eventTime=%" PRId64 ", deviceId=%d", args.eventTime,
4604 args.deviceId);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004605 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004606
Antonio Kantekf16f2832021-09-28 04:39:20 +00004607 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004608 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004609 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004610
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004611 std::unique_ptr<DeviceResetEntry> newEntry =
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004612 std::make_unique<DeviceResetEntry>(args.id, args.eventTime, args.deviceId);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004613 needWake = enqueueInboundEventLocked(std::move(newEntry));
Siarhei Vishniakou1160ecd2023-06-28 15:57:47 -07004614
4615 for (auto& [_, verifier] : mVerifiersByDisplay) {
4616 verifier.resetDevice(args.deviceId);
4617 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004618 } // release lock
4619
4620 if (needWake) {
4621 mLooper->wake();
4622 }
4623}
4624
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004625void InputDispatcher::notifyPointerCaptureChanged(const NotifyPointerCaptureChangedArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004626 if (debugInboundEventDetails()) {
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004627 ALOGD("notifyPointerCaptureChanged - eventTime=%" PRId64 ", enabled=%s", args.eventTime,
4628 args.request.enable ? "true" : "false");
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004629 }
Prabir Pradhan7e186182020-11-10 13:56:45 -08004630
Antonio Kantekf16f2832021-09-28 04:39:20 +00004631 bool needWake = false;
Prabir Pradhan99987712020-11-10 18:43:05 -08004632 { // acquire lock
4633 std::scoped_lock _l(mLock);
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004634 auto entry =
4635 std::make_unique<PointerCaptureChangedEntry>(args.id, args.eventTime, args.request);
Prabir Pradhan99987712020-11-10 18:43:05 -08004636 needWake = enqueueInboundEventLocked(std::move(entry));
4637 } // release lock
4638
4639 if (needWake) {
4640 mLooper->wake();
4641 }
Prabir Pradhan7e186182020-11-10 13:56:45 -08004642}
4643
Prabir Pradhan5735a322022-04-11 17:23:34 +00004644InputEventInjectionResult InputDispatcher::injectInputEvent(const InputEvent* event,
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00004645 std::optional<gui::Uid> targetUid,
Prabir Pradhan5735a322022-04-11 17:23:34 +00004646 InputEventInjectionSync syncMode,
4647 std::chrono::milliseconds timeout,
4648 uint32_t policyFlags) {
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004649 Result<void> eventValidation = validateInputEvent(*event);
4650 if (!eventValidation.ok()) {
4651 LOG(INFO) << "Injection failed: invalid event: " << eventValidation.error();
4652 return InputEventInjectionResult::FAILED;
4653 }
4654
Prabir Pradhan65613802023-02-22 23:36:58 +00004655 if (debugInboundEventDetails()) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07004656 LOG(INFO) << __func__ << ": targetUid=" << toString(targetUid, &uidString)
4657 << ", syncMode=" << ftl::enum_string(syncMode) << ", timeout=" << timeout.count()
4658 << "ms, policyFlags=0x" << std::hex << policyFlags << std::dec
4659 << ", event=" << *event;
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004660 }
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07004661 nsecs_t endTime = now() + std::chrono::duration_cast<std::chrono::nanoseconds>(timeout).count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004662
Prabir Pradhan5735a322022-04-11 17:23:34 +00004663 policyFlags |= POLICY_FLAG_INJECTED | POLICY_FLAG_TRUSTED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004664
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004665 // For all injected events, set device id = VIRTUAL_KEYBOARD_ID. The only exception is events
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004666 // that have gone through the InputFilter. If the event passed through the InputFilter, assign
4667 // the provided device id. If the InputFilter is accessibility, and it modifies or synthesizes
4668 // the injected event, it is responsible for setting POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY.
4669 // For those events, we will set FLAG_IS_ACCESSIBILITY_EVENT to allow apps to distinguish them
4670 // from events that originate from actual hardware.
Siarhei Vishniakouf4043212023-09-18 19:33:03 -07004671 DeviceId resolvedDeviceId = VIRTUAL_KEYBOARD_ID;
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004672 if (policyFlags & POLICY_FLAG_FILTERED) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004673 resolvedDeviceId = event->getDeviceId();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004674 }
4675
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00004676 const bool isAsync = syncMode == InputEventInjectionSync::NONE;
4677 auto injectionState = std::make_shared<InjectionState>(targetUid, isAsync);
4678
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004679 std::queue<std::unique_ptr<EventEntry>> injectedEntries;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004680 switch (event->getType()) {
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004681 case InputEventType::KEY: {
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004682 const KeyEvent& incomingKey = static_cast<const KeyEvent&>(*event);
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004683 const int32_t action = incomingKey.getAction();
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004684 int32_t flags = incomingKey.getFlags();
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004685 if (policyFlags & POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY) {
4686 flags |= AKEY_EVENT_FLAG_IS_ACCESSIBILITY_EVENT;
4687 }
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004688 int32_t keyCode = incomingKey.getKeyCode();
4689 int32_t metaState = incomingKey.getMetaState();
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004690 KeyEvent keyEvent;
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004691 keyEvent.initialize(incomingKey.getId(), resolvedDeviceId, incomingKey.getSource(),
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004692 incomingKey.getDisplayId(), INVALID_HMAC, action, flags, keyCode,
4693 incomingKey.getScanCode(), metaState, incomingKey.getRepeatCount(),
4694 incomingKey.getDownTime(), incomingKey.getEventTime());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004695
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004696 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
4697 policyFlags |= POLICY_FLAG_VIRTUAL;
Michael Wright2b3c3302018-03-02 17:19:13 +00004698 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004699
4700 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
4701 android::base::Timer t;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004702 mPolicy.interceptKeyBeforeQueueing(keyEvent, /*byref*/ policyFlags);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004703 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4704 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
4705 std::to_string(t.duration().count()).c_str());
4706 }
4707 }
4708
4709 mLock.lock();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004710 std::unique_ptr<KeyEntry> injectedEntry =
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00004711 std::make_unique<KeyEntry>(incomingKey.getId(), injectionState,
4712 incomingKey.getEventTime(), resolvedDeviceId,
4713 incomingKey.getSource(), incomingKey.getDisplayId(),
4714 policyFlags, action, flags, keyCode,
4715 incomingKey.getScanCode(), metaState,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004716 incomingKey.getRepeatCount(),
4717 incomingKey.getDownTime());
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00004718 if (mTracer) {
4719 injectedEntry->traceTracker = mTracer->traceInboundEvent(*injectedEntry);
4720 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004721 injectedEntries.push(std::move(injectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004722 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004723 }
4724
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004725 case InputEventType::MOTION: {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004726 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(*event);
Prabir Pradhanaa561d12021-09-24 06:57:33 -07004727 const bool isPointerEvent =
4728 isFromSource(event->getSource(), AINPUT_SOURCE_CLASS_POINTER);
4729 // If a pointer event has no displayId specified, inject it to the default display.
4730 const uint32_t displayId = isPointerEvent && (event->getDisplayId() == ADISPLAY_ID_NONE)
4731 ? ADISPLAY_ID_DEFAULT
4732 : event->getDisplayId();
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004733 int32_t flags = motionEvent.getFlags();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004734
4735 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004736 nsecs_t eventTime = motionEvent.getEventTime();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004737 android::base::Timer t;
Yeabkal Wubshit88a90412023-12-21 18:23:04 -08004738 mPolicy.interceptMotionBeforeQueueing(displayId, motionEvent.getSource(),
4739 motionEvent.getAction(), eventTime,
4740 /*byref*/ policyFlags);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004741 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4742 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
4743 std::to_string(t.duration().count()).c_str());
4744 }
4745 }
4746
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004747 if (policyFlags & POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY) {
4748 flags |= AMOTION_EVENT_FLAG_IS_ACCESSIBILITY_EVENT;
4749 }
4750
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004751 mLock.lock();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004752 const nsecs_t* sampleEventTimes = motionEvent.getSampleEventTimes();
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004753 const size_t pointerCount = motionEvent.getPointerCount();
4754 const std::vector<PointerProperties>
4755 pointerProperties(motionEvent.getPointerProperties(),
4756 motionEvent.getPointerProperties() + pointerCount);
4757
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004758 const PointerCoords* samplePointerCoords = motionEvent.getSamplePointerCoords();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004759 std::unique_ptr<MotionEntry> injectedEntry =
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00004760 std::make_unique<MotionEntry>(motionEvent.getId(), injectionState,
4761 *sampleEventTimes, resolvedDeviceId,
4762 motionEvent.getSource(), displayId, policyFlags,
4763 motionEvent.getAction(),
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004764 motionEvent.getActionButton(), flags,
4765 motionEvent.getMetaState(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004766 motionEvent.getButtonState(),
4767 motionEvent.getClassification(),
4768 motionEvent.getEdgeFlags(),
4769 motionEvent.getXPrecision(),
4770 motionEvent.getYPrecision(),
4771 motionEvent.getRawXCursorPosition(),
4772 motionEvent.getRawYCursorPosition(),
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004773 motionEvent.getDownTime(), pointerProperties,
4774 std::vector<PointerCoords>(samplePointerCoords,
4775 samplePointerCoords +
4776 pointerCount));
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004777 transformMotionEntryForInjectionLocked(*injectedEntry, motionEvent.getTransform());
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00004778 if (mTracer) {
4779 injectedEntry->traceTracker = mTracer->traceInboundEvent(*injectedEntry);
4780 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004781 injectedEntries.push(std::move(injectedEntry));
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004782 for (size_t i = motionEvent.getHistorySize(); i > 0; i--) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004783 sampleEventTimes += 1;
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004784 samplePointerCoords += motionEvent.getPointerCount();
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004785 std::unique_ptr<MotionEntry> nextInjectedEntry = std::make_unique<
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00004786 MotionEntry>(motionEvent.getId(), injectionState, *sampleEventTimes,
4787 resolvedDeviceId, motionEvent.getSource(), displayId,
4788 policyFlags, motionEvent.getAction(),
4789 motionEvent.getActionButton(), flags,
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004790 motionEvent.getMetaState(), motionEvent.getButtonState(),
4791 motionEvent.getClassification(), motionEvent.getEdgeFlags(),
4792 motionEvent.getXPrecision(), motionEvent.getYPrecision(),
4793 motionEvent.getRawXCursorPosition(),
4794 motionEvent.getRawYCursorPosition(), motionEvent.getDownTime(),
4795 pointerProperties,
4796 std::vector<PointerCoords>(samplePointerCoords,
4797 samplePointerCoords +
4798 pointerCount));
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004799 transformMotionEntryForInjectionLocked(*nextInjectedEntry,
4800 motionEvent.getTransform());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004801 injectedEntries.push(std::move(nextInjectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004802 }
4803 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004804 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004805
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004806 default:
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004807 LOG(WARNING) << "Cannot inject " << ftl::enum_string(event->getType()) << " events";
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004808 return InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004809 }
4810
Michael Wrightd02c5b62014-02-10 15:10:22 -08004811 bool needWake = false;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004812 while (!injectedEntries.empty()) {
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08004813 if (DEBUG_INJECTION) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07004814 LOG(INFO) << "Injecting " << injectedEntries.front()->getDescription();
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08004815 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004816 needWake |= enqueueInboundEventLocked(std::move(injectedEntries.front()));
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004817 injectedEntries.pop();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004818 }
4819
4820 mLock.unlock();
4821
4822 if (needWake) {
4823 mLooper->wake();
4824 }
4825
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004826 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004827 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004828 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004829
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004830 if (syncMode == InputEventInjectionSync::NONE) {
4831 injectionResult = InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004832 } else {
4833 for (;;) {
4834 injectionResult = injectionState->injectionResult;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004835 if (injectionResult != InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004836 break;
4837 }
4838
4839 nsecs_t remainingTimeout = endTime - now();
4840 if (remainingTimeout <= 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004841 if (DEBUG_INJECTION) {
4842 ALOGD("injectInputEvent - Timed out waiting for injection result "
4843 "to become available.");
4844 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004845 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004846 break;
4847 }
4848
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004849 mInjectionResultAvailable.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004850 }
4851
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004852 if (injectionResult == InputEventInjectionResult::SUCCEEDED &&
4853 syncMode == InputEventInjectionSync::WAIT_FOR_FINISHED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004854 while (injectionState->pendingForegroundDispatches != 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004855 if (DEBUG_INJECTION) {
4856 ALOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
4857 injectionState->pendingForegroundDispatches);
4858 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004859 nsecs_t remainingTimeout = endTime - now();
4860 if (remainingTimeout <= 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004861 if (DEBUG_INJECTION) {
4862 ALOGD("injectInputEvent - Timed out waiting for pending foreground "
4863 "dispatches to finish.");
4864 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004865 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004866 break;
4867 }
4868
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004869 mInjectionSyncFinished.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004870 }
4871 }
4872 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004873 } // release lock
4874
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004875 if (DEBUG_INJECTION) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07004876 LOG(INFO) << "injectInputEvent - Finished with result "
4877 << ftl::enum_string(injectionResult);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004878 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004879
4880 return injectionResult;
4881}
4882
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004883std::unique_ptr<VerifiedInputEvent> InputDispatcher::verifyInputEvent(const InputEvent& event) {
Gang Wange9087892020-01-07 12:17:14 -05004884 std::array<uint8_t, 32> calculatedHmac;
4885 std::unique_ptr<VerifiedInputEvent> result;
4886 switch (event.getType()) {
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004887 case InputEventType::KEY: {
Gang Wange9087892020-01-07 12:17:14 -05004888 const KeyEvent& keyEvent = static_cast<const KeyEvent&>(event);
4889 VerifiedKeyEvent verifiedKeyEvent = verifiedKeyEventFromKeyEvent(keyEvent);
4890 result = std::make_unique<VerifiedKeyEvent>(verifiedKeyEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004891 calculatedHmac = sign(verifiedKeyEvent);
Gang Wange9087892020-01-07 12:17:14 -05004892 break;
4893 }
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004894 case InputEventType::MOTION: {
Gang Wange9087892020-01-07 12:17:14 -05004895 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(event);
4896 VerifiedMotionEvent verifiedMotionEvent =
4897 verifiedMotionEventFromMotionEvent(motionEvent);
4898 result = std::make_unique<VerifiedMotionEvent>(verifiedMotionEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004899 calculatedHmac = sign(verifiedMotionEvent);
Gang Wange9087892020-01-07 12:17:14 -05004900 break;
4901 }
4902 default: {
4903 ALOGE("Cannot verify events of type %" PRId32, event.getType());
4904 return nullptr;
4905 }
4906 }
4907 if (calculatedHmac == INVALID_HMAC) {
4908 return nullptr;
4909 }
tyiu1573a672023-02-21 22:38:32 +00004910 if (0 != CRYPTO_memcmp(calculatedHmac.data(), event.getHmac().data(), calculatedHmac.size())) {
Gang Wange9087892020-01-07 12:17:14 -05004911 return nullptr;
4912 }
4913 return result;
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004914}
4915
Prabir Pradhan24047542023-11-02 17:14:59 +00004916void InputDispatcher::setInjectionResult(const EventEntry& entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004917 InputEventInjectionResult injectionResult) {
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00004918 if (!entry.injectionState) {
4919 // Not an injected event.
4920 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004921 }
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00004922
4923 InjectionState& injectionState = *entry.injectionState;
4924 if (DEBUG_INJECTION) {
4925 LOG(INFO) << "Setting input event injection result to "
4926 << ftl::enum_string(injectionResult);
4927 }
4928
4929 if (injectionState.injectionIsAsync && !(entry.policyFlags & POLICY_FLAG_FILTERED)) {
4930 // Log the outcome since the injector did not wait for the injection result.
4931 switch (injectionResult) {
4932 case InputEventInjectionResult::SUCCEEDED:
4933 ALOGV("Asynchronous input event injection succeeded.");
4934 break;
4935 case InputEventInjectionResult::TARGET_MISMATCH:
4936 ALOGV("Asynchronous input event injection target mismatch.");
4937 break;
4938 case InputEventInjectionResult::FAILED:
4939 ALOGW("Asynchronous input event injection failed.");
4940 break;
4941 case InputEventInjectionResult::TIMED_OUT:
4942 ALOGW("Asynchronous input event injection timed out.");
4943 break;
4944 case InputEventInjectionResult::PENDING:
4945 ALOGE("Setting result to 'PENDING' for asynchronous injection");
4946 break;
4947 }
4948 }
4949
4950 injectionState.injectionResult = injectionResult;
4951 mInjectionResultAvailable.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004952}
4953
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004954void InputDispatcher::transformMotionEntryForInjectionLocked(
4955 MotionEntry& entry, const ui::Transform& injectedTransform) const {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004956 // Input injection works in the logical display coordinate space, but the input pipeline works
4957 // display space, so we need to transform the injected events accordingly.
4958 const auto it = mDisplayInfos.find(entry.displayId);
4959 if (it == mDisplayInfos.end()) return;
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004960 const auto& transformToDisplay = it->second.transform.inverse() * injectedTransform;
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004961
Prabir Pradhand9a2ebe2022-07-20 19:25:13 +00004962 if (entry.xCursorPosition != AMOTION_EVENT_INVALID_CURSOR_POSITION &&
4963 entry.yCursorPosition != AMOTION_EVENT_INVALID_CURSOR_POSITION) {
4964 const vec2 cursor =
4965 MotionEvent::calculateTransformedXY(entry.source, transformToDisplay,
4966 {entry.xCursorPosition, entry.yCursorPosition});
4967 entry.xCursorPosition = cursor.x;
4968 entry.yCursorPosition = cursor.y;
4969 }
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004970 for (uint32_t i = 0; i < entry.getPointerCount(); i++) {
Prabir Pradhan8e6ce222022-02-24 09:08:54 -08004971 entry.pointerCoords[i] =
4972 MotionEvent::calculateTransformedCoords(entry.source, transformToDisplay,
4973 entry.pointerCoords[i]);
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004974 }
4975}
4976
Prabir Pradhan24047542023-11-02 17:14:59 +00004977void InputDispatcher::incrementPendingForegroundDispatches(const EventEntry& entry) {
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00004978 if (entry.injectionState) {
4979 entry.injectionState->pendingForegroundDispatches += 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004980 }
4981}
4982
Prabir Pradhan24047542023-11-02 17:14:59 +00004983void InputDispatcher::decrementPendingForegroundDispatches(const EventEntry& entry) {
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00004984 if (entry.injectionState) {
4985 entry.injectionState->pendingForegroundDispatches -= 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004986
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00004987 if (entry.injectionState->pendingForegroundDispatches == 0) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004988 mInjectionSyncFinished.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004989 }
4990 }
4991}
4992
chaviw98318de2021-05-19 16:45:23 -05004993const std::vector<sp<WindowInfoHandle>>& InputDispatcher::getWindowHandlesLocked(
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004994 int32_t displayId) const {
chaviw98318de2021-05-19 16:45:23 -05004995 static const std::vector<sp<WindowInfoHandle>> EMPTY_WINDOW_HANDLES;
Vishnu Nairad321cd2020-08-20 16:40:21 -07004996 auto it = mWindowHandlesByDisplay.find(displayId);
4997 return it != mWindowHandlesByDisplay.end() ? it->second : EMPTY_WINDOW_HANDLES;
Arthur Hungb92218b2018-08-14 12:00:21 +08004998}
4999
chaviw98318de2021-05-19 16:45:23 -05005000sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(
Prabir Pradhan16463382023-10-12 23:03:19 +00005001 const sp<IBinder>& windowHandleToken, std::optional<int32_t> displayId) const {
arthurhungbe737672020-06-24 12:29:21 +08005002 if (windowHandleToken == nullptr) {
5003 return nullptr;
5004 }
5005
Prabir Pradhan16463382023-10-12 23:03:19 +00005006 if (!displayId) {
5007 // Look through all displays.
5008 for (auto& it : mWindowHandlesByDisplay) {
5009 const std::vector<sp<WindowInfoHandle>>& windowHandles = it.second;
5010 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
5011 if (windowHandle->getToken() == windowHandleToken) {
5012 return windowHandle;
5013 }
Arthur Hungb92218b2018-08-14 12:00:21 +08005014 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005015 }
Vishnu Nairad321cd2020-08-20 16:40:21 -07005016 return nullptr;
5017 }
5018
Prabir Pradhan16463382023-10-12 23:03:19 +00005019 // Only look through the requested display.
5020 for (const sp<WindowInfoHandle>& windowHandle : getWindowHandlesLocked(*displayId)) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07005021 if (windowHandle->getToken() == windowHandleToken) {
5022 return windowHandle;
5023 }
5024 }
5025 return nullptr;
5026}
5027
chaviw98318de2021-05-19 16:45:23 -05005028sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(
5029 const sp<WindowInfoHandle>& windowHandle) const {
Mady Mellor017bcd12020-06-23 19:12:00 +00005030 for (auto& it : mWindowHandlesByDisplay) {
chaviw98318de2021-05-19 16:45:23 -05005031 const std::vector<sp<WindowInfoHandle>>& windowHandles = it.second;
5032 for (const sp<WindowInfoHandle>& handle : windowHandles) {
arthurhungbe737672020-06-24 12:29:21 +08005033 if (handle->getId() == windowHandle->getId() &&
5034 handle->getToken() == windowHandle->getToken()) {
Mady Mellor017bcd12020-06-23 19:12:00 +00005035 if (windowHandle->getInfo()->displayId != it.first) {
5036 ALOGE("Found window %s in display %" PRId32
5037 ", but it should belong to display %" PRId32,
5038 windowHandle->getName().c_str(), it.first,
5039 windowHandle->getInfo()->displayId);
5040 }
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07005041 return handle;
Arthur Hungb92218b2018-08-14 12:00:21 +08005042 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005043 }
5044 }
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07005045 return nullptr;
5046}
5047
chaviw98318de2021-05-19 16:45:23 -05005048sp<WindowInfoHandle> InputDispatcher::getFocusedWindowHandleLocked(int displayId) const {
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07005049 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(displayId);
5050 return getWindowHandleLocked(focusedToken, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005051}
5052
Prabir Pradhan33e3baa2022-12-06 20:30:22 +00005053ui::Transform InputDispatcher::getTransformLocked(int32_t displayId) const {
5054 auto displayInfoIt = mDisplayInfos.find(displayId);
5055 return displayInfoIt != mDisplayInfos.end() ? displayInfoIt->second.transform
5056 : kIdentityTransform;
5057}
5058
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07005059bool InputDispatcher::canWindowReceiveMotionLocked(const sp<WindowInfoHandle>& window,
5060 const MotionEntry& motionEntry) const {
5061 const WindowInfo& info = *window->getInfo();
5062
5063 // Skip spy window targets that are not valid for targeted injection.
5064 if (const auto err = verifyTargetedInjection(window, motionEntry); err) {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005065 return false;
5066 }
5067
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07005068 if (info.inputConfig.test(WindowInfo::InputConfig::PAUSE_DISPATCHING)) {
5069 ALOGI("Not sending touch event to %s because it is paused", window->getName().c_str());
5070 return false;
5071 }
5072
5073 if (info.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL)) {
5074 ALOGW("Not sending touch gesture to %s because it has config NO_INPUT_CHANNEL",
5075 window->getName().c_str());
5076 return false;
5077 }
5078
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07005079 std::shared_ptr<Connection> connection = getConnectionLocked(window->getToken());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005080 if (connection == nullptr) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07005081 ALOGW("Not sending touch to %s because there's no corresponding connection",
5082 window->getName().c_str());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005083 return false;
5084 }
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07005085
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005086 if (!connection->responsive) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07005087 ALOGW("Not sending touch to %s because it is not responsive", window->getName().c_str());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005088 return false;
5089 }
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07005090
5091 // Drop events that can't be trusted due to occlusion
5092 const auto [x, y] = resolveTouchedPosition(motionEntry);
5093 TouchOcclusionInfo occlusionInfo = computeTouchOcclusionInfoLocked(window, x, y);
5094 if (!isTouchTrustedLocked(occlusionInfo)) {
5095 if (DEBUG_TOUCH_OCCLUSION) {
Prabir Pradhan82e081e2022-12-06 09:50:09 +00005096 ALOGD("Stack of obscuring windows during untrusted touch (%.1f, %.1f):", x, y);
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07005097 for (const auto& log : occlusionInfo.debugInfo) {
5098 ALOGD("%s", log.c_str());
5099 }
5100 }
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00005101 ALOGW("Dropping untrusted touch event due to %s/%s", occlusionInfo.obscuringPackage.c_str(),
5102 occlusionInfo.obscuringUid.toString().c_str());
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07005103 return false;
5104 }
5105
5106 // Drop touch events if requested by input feature
5107 if (shouldDropInput(motionEntry, window)) {
5108 return false;
5109 }
5110
Siarhei Vishniakouf77f60a2023-10-23 17:26:05 -07005111 // Ignore touches if stylus is down anywhere on screen
5112 if (info.inputConfig.test(WindowInfo::InputConfig::GLOBAL_STYLUS_BLOCKS_TOUCH) &&
5113 isStylusActiveInDisplay(info.displayId, mTouchStatesByDisplay)) {
5114 LOG(INFO) << "Dropping touch from " << window->getName() << " because stylus is active";
5115 return false;
5116 }
5117
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005118 return true;
5119}
5120
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005121std::shared_ptr<InputChannel> InputDispatcher::getInputChannelLocked(
5122 const sp<IBinder>& token) const {
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005123 auto connectionIt = mConnectionsByToken.find(token);
5124 if (connectionIt == mConnectionsByToken.end()) {
Robert Carr5c8a0262018-10-03 16:30:44 -07005125 return nullptr;
5126 }
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005127 return connectionIt->second->inputChannel;
Robert Carr5c8a0262018-10-03 16:30:44 -07005128}
5129
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005130void InputDispatcher::updateWindowHandlesForDisplayLocked(
chaviw98318de2021-05-19 16:45:23 -05005131 const std::vector<sp<WindowInfoHandle>>& windowInfoHandles, int32_t displayId) {
5132 if (windowInfoHandles.empty()) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005133 // Remove all handles on a display if there are no windows left.
5134 mWindowHandlesByDisplay.erase(displayId);
5135 return;
5136 }
5137
5138 // Since we compare the pointer of input window handles across window updates, we need
5139 // to make sure the handle object for the same window stays unchanged across updates.
chaviw98318de2021-05-19 16:45:23 -05005140 const std::vector<sp<WindowInfoHandle>>& oldHandles = getWindowHandlesLocked(displayId);
5141 std::unordered_map<int32_t /*id*/, sp<WindowInfoHandle>> oldHandlesById;
5142 for (const sp<WindowInfoHandle>& handle : oldHandles) {
chaviwaf87b3e2019-10-01 16:59:28 -07005143 oldHandlesById[handle->getId()] = handle;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005144 }
5145
chaviw98318de2021-05-19 16:45:23 -05005146 std::vector<sp<WindowInfoHandle>> newHandles;
5147 for (const sp<WindowInfoHandle>& handle : windowInfoHandles) {
chaviw98318de2021-05-19 16:45:23 -05005148 const WindowInfo* info = handle->getInfo();
Siarhei Vishniakou64452932020-11-06 17:51:32 -06005149 if (getInputChannelLocked(handle->getToken()) == nullptr) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005150 const bool noInputChannel =
Prabir Pradhan51e7db02022-02-07 06:02:57 -08005151 info->inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005152 const bool canReceiveInput =
5153 !info->inputConfig.test(WindowInfo::InputConfig::NOT_TOUCHABLE) ||
5154 !info->inputConfig.test(WindowInfo::InputConfig::NOT_FOCUSABLE);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005155 if (canReceiveInput && !noInputChannel) {
John Recke0710582019-09-26 13:46:12 -07005156 ALOGV("Window handle %s has no registered input channel",
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005157 handle->getName().c_str());
Robert Carr2984b7a2020-04-13 17:06:45 -07005158 continue;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005159 }
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005160 }
5161
5162 if (info->displayId != displayId) {
5163 ALOGE("Window %s updated by wrong display %d, should belong to display %d",
5164 handle->getName().c_str(), displayId, info->displayId);
5165 continue;
5166 }
5167
Robert Carredd13602020-04-13 17:24:34 -07005168 if ((oldHandlesById.find(handle->getId()) != oldHandlesById.end()) &&
5169 (oldHandlesById.at(handle->getId())->getToken() == handle->getToken())) {
chaviw98318de2021-05-19 16:45:23 -05005170 const sp<WindowInfoHandle>& oldHandle = oldHandlesById.at(handle->getId());
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005171 oldHandle->updateFrom(handle);
5172 newHandles.push_back(oldHandle);
5173 } else {
5174 newHandles.push_back(handle);
5175 }
5176 }
5177
5178 // Insert or replace
5179 mWindowHandlesByDisplay[displayId] = newHandles;
5180}
5181
Arthur Hungb92218b2018-08-14 12:00:21 +08005182/**
5183 * Called from InputManagerService, update window handle list by displayId that can receive input.
5184 * A window handle contains information about InputChannel, Touch Region, Types, Focused,...
5185 * If set an empty list, remove all handles from the specific display.
5186 * For focused handle, check if need to change and send a cancel event to previous one.
5187 * For removed handle, check if need to send a cancel event if already in touch.
5188 */
Arthur Hung72d8dc32020-03-28 00:48:39 +00005189void InputDispatcher::setInputWindowsLocked(
chaviw98318de2021-05-19 16:45:23 -05005190 const std::vector<sp<WindowInfoHandle>>& windowInfoHandles, int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005191 if (DEBUG_FOCUS) {
5192 std::string windowList;
chaviw98318de2021-05-19 16:45:23 -05005193 for (const sp<WindowInfoHandle>& iwh : windowInfoHandles) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005194 windowList += iwh->getName() + " ";
5195 }
Siarhei Vishniakou366fb5b2023-12-06 11:23:41 -08005196 LOG(INFO) << "setInputWindows displayId=" << displayId << " " << windowList;
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005197 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005198
Prabir Pradhand65552b2021-10-07 11:23:50 -07005199 // Check preconditions for new input windows
chaviw98318de2021-05-19 16:45:23 -05005200 for (const sp<WindowInfoHandle>& window : windowInfoHandles) {
Prabir Pradhand65552b2021-10-07 11:23:50 -07005201 const WindowInfo& info = *window->getInfo();
5202
5203 // Ensure all tokens are null if the window has feature NO_INPUT_CHANNEL
Prabir Pradhan51e7db02022-02-07 06:02:57 -08005204 const bool noInputWindow = info.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005205 if (noInputWindow && window->getToken() != nullptr) {
5206 ALOGE("%s has feature NO_INPUT_WINDOW, but a non-null token. Clearing",
5207 window->getName().c_str());
5208 window->releaseChannel();
5209 }
Prabir Pradhand65552b2021-10-07 11:23:50 -07005210
Prabir Pradhan5c85e052021-12-22 02:27:12 -08005211 // Ensure all spy windows are trusted overlays
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005212 LOG_ALWAYS_FATAL_IF(info.isSpy() &&
5213 !info.inputConfig.test(
5214 WindowInfo::InputConfig::TRUSTED_OVERLAY),
Prabir Pradhan5c85e052021-12-22 02:27:12 -08005215 "%s has feature SPY, but is not a trusted overlay.",
5216 window->getName().c_str());
5217
Prabir Pradhand65552b2021-10-07 11:23:50 -07005218 // Ensure all stylus interceptors are trusted overlays
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005219 LOG_ALWAYS_FATAL_IF(info.interceptsStylus() &&
5220 !info.inputConfig.test(
5221 WindowInfo::InputConfig::TRUSTED_OVERLAY),
Prabir Pradhand65552b2021-10-07 11:23:50 -07005222 "%s has feature INTERCEPTS_STYLUS, but is not a trusted overlay.",
5223 window->getName().c_str());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005224 }
5225
Arthur Hung72d8dc32020-03-28 00:48:39 +00005226 // Copy old handles for release if they are no longer present.
chaviw98318de2021-05-19 16:45:23 -05005227 const std::vector<sp<WindowInfoHandle>> oldWindowHandles = getWindowHandlesLocked(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005228
chaviw98318de2021-05-19 16:45:23 -05005229 updateWindowHandlesForDisplayLocked(windowInfoHandles, displayId);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005230
chaviw98318de2021-05-19 16:45:23 -05005231 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Arthur Hung72d8dc32020-03-28 00:48:39 +00005232
Vishnu Nairc519ff72021-01-21 08:23:08 -08005233 std::optional<FocusResolver::FocusChanges> changes =
5234 mFocusResolver.setInputWindows(displayId, windowHandles);
5235 if (changes) {
5236 onFocusChangedLocked(*changes);
Arthur Hung72d8dc32020-03-28 00:48:39 +00005237 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005238
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005239 std::unordered_map<int32_t, TouchState>::iterator stateIt =
5240 mTouchStatesByDisplay.find(displayId);
5241 if (stateIt != mTouchStatesByDisplay.end()) {
5242 TouchState& state = stateIt->second;
Arthur Hung72d8dc32020-03-28 00:48:39 +00005243 for (size_t i = 0; i < state.windows.size();) {
5244 TouchedWindow& touchedWindow = state.windows[i];
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07005245 if (getWindowHandleLocked(touchedWindow.windowHandle) == nullptr) {
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07005246 LOG(INFO) << "Touched window was removed: " << touchedWindow.windowHandle->getName()
5247 << " in display %" << displayId;
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005248 std::shared_ptr<InputChannel> touchedInputChannel =
Arthur Hung72d8dc32020-03-28 00:48:39 +00005249 getInputChannelLocked(touchedWindow.windowHandle->getToken());
5250 if (touchedInputChannel != nullptr) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00005251 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
Arthur Hung72d8dc32020-03-28 00:48:39 +00005252 "touched window was removed");
5253 synthesizeCancelationEventsForInputChannelLocked(touchedInputChannel, options);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00005254 // Since we are about to drop the touch, cancel the events for the wallpaper as
5255 // well.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005256 if (touchedWindow.targetFlags.test(InputTarget::Flags::FOREGROUND) &&
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005257 touchedWindow.windowHandle->getInfo()->inputConfig.test(
5258 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER)) {
Siarhei Vishniakouca205502021-07-16 21:31:58 +00005259 sp<WindowInfoHandle> wallpaper = state.getWallpaperWindow();
Arthur Hungc539dbb2022-12-08 07:45:36 +00005260 synthesizeCancelationEventsForWindowLocked(wallpaper, options);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00005261 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005262 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00005263 state.windows.erase(state.windows.begin() + i);
5264 } else {
5265 ++i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005266 }
5267 }
arthurhungb89ccb02020-12-30 16:19:01 +08005268
arthurhung6d4bed92021-03-17 11:59:33 +08005269 // If drag window is gone, it would receive a cancel event and broadcast the DRAG_END. We
arthurhungb89ccb02020-12-30 16:19:01 +08005270 // could just clear the state here.
Arthur Hung3915c1f2022-05-31 07:17:17 +00005271 if (mDragState && mDragState->dragWindow->getInfo()->displayId == displayId &&
arthurhung6d4bed92021-03-17 11:59:33 +08005272 std::find(windowHandles.begin(), windowHandles.end(), mDragState->dragWindow) ==
arthurhungb89ccb02020-12-30 16:19:01 +08005273 windowHandles.end()) {
Arthur Hung3915c1f2022-05-31 07:17:17 +00005274 ALOGI("Drag window went away: %s", mDragState->dragWindow->getName().c_str());
5275 sendDropWindowCommandLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08005276 mDragState.reset();
arthurhungb89ccb02020-12-30 16:19:01 +08005277 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00005278 }
Arthur Hung25e2af12020-03-26 12:58:37 +00005279
Arthur Hung72d8dc32020-03-28 00:48:39 +00005280 // Release information for windows that are no longer present.
5281 // This ensures that unused input channels are released promptly.
5282 // Otherwise, they might stick around until the window handle is destroyed
5283 // which might not happen until the next GC.
chaviw98318de2021-05-19 16:45:23 -05005284 for (const sp<WindowInfoHandle>& oldWindowHandle : oldWindowHandles) {
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07005285 if (getWindowHandleLocked(oldWindowHandle) == nullptr) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00005286 if (DEBUG_FOCUS) {
5287 ALOGD("Window went away: %s", oldWindowHandle->getName().c_str());
Arthur Hung25e2af12020-03-26 12:58:37 +00005288 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00005289 oldWindowHandle->releaseChannel();
Arthur Hung25e2af12020-03-26 12:58:37 +00005290 }
chaviw291d88a2019-02-14 10:33:58 -08005291 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005292}
5293
5294void InputDispatcher::setFocusedApplication(
Chris Yea209fde2020-07-22 13:54:51 -07005295 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005296 if (DEBUG_FOCUS) {
5297 ALOGD("setFocusedApplication displayId=%" PRId32 " %s", displayId,
5298 inputApplicationHandle ? inputApplicationHandle->getName().c_str() : "<nullptr>");
5299 }
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05005300 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005301 std::scoped_lock _l(mLock);
Vishnu Nair599f1412021-06-21 10:39:58 -07005302 setFocusedApplicationLocked(displayId, inputApplicationHandle);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005303 } // release lock
5304
5305 // Wake up poll loop since it may need to make new input dispatching choices.
5306 mLooper->wake();
5307}
5308
Vishnu Nair599f1412021-06-21 10:39:58 -07005309void InputDispatcher::setFocusedApplicationLocked(
5310 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
5311 std::shared_ptr<InputApplicationHandle> oldFocusedApplicationHandle =
5312 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
5313
5314 if (sharedPointersEqual(oldFocusedApplicationHandle, inputApplicationHandle)) {
5315 return; // This application is already focused. No need to wake up or change anything.
5316 }
5317
5318 // Set the new application handle.
5319 if (inputApplicationHandle != nullptr) {
5320 mFocusedApplicationHandlesByDisplay[displayId] = inputApplicationHandle;
5321 } else {
5322 mFocusedApplicationHandlesByDisplay.erase(displayId);
5323 }
5324
5325 // No matter what the old focused application was, stop waiting on it because it is
5326 // no longer focused.
5327 resetNoFocusedWindowTimeoutLocked();
5328}
5329
Yeabkal Wubshitb8aadfa2024-01-17 17:03:42 -08005330void InputDispatcher::setMinTimeBetweenUserActivityPokes(std::chrono::milliseconds interval) {
5331 if (interval.count() < 0) {
5332 LOG_ALWAYS_FATAL("Minimum time between user activity pokes should be >= 0");
5333 }
5334 std::scoped_lock _l(mLock);
5335 mMinTimeBetweenUserActivityPokes = interval;
5336}
5337
Tiger Huang721e26f2018-07-24 22:26:19 +08005338/**
5339 * Sets the focused display, which is responsible for receiving focus-dispatched input events where
5340 * the display not specified.
5341 *
5342 * We track any unreleased events for each window. If a window loses the ability to receive the
5343 * released event, we will send a cancel event to it. So when the focused display is changed, we
5344 * cancel all the unreleased display-unspecified events for the focused window on the old focused
5345 * display. The display-specified events won't be affected.
5346 */
5347void InputDispatcher::setFocusedDisplay(int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005348 if (DEBUG_FOCUS) {
5349 ALOGD("setFocusedDisplay displayId=%" PRId32, displayId);
5350 }
Tiger Huang721e26f2018-07-24 22:26:19 +08005351 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005352 std::scoped_lock _l(mLock);
Tiger Huang721e26f2018-07-24 22:26:19 +08005353
5354 if (mFocusedDisplayId != displayId) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07005355 sp<IBinder> oldFocusedWindowToken =
Vishnu Nairc519ff72021-01-21 08:23:08 -08005356 mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07005357 if (oldFocusedWindowToken != nullptr) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005358 std::shared_ptr<InputChannel> inputChannel =
Vishnu Nairad321cd2020-08-20 16:40:21 -07005359 getInputChannelLocked(oldFocusedWindowToken);
Tiger Huang721e26f2018-07-24 22:26:19 +08005360 if (inputChannel != nullptr) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005361 CancelationOptions
Michael Wrightfb04fd52022-11-24 22:31:11 +00005362 options(CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005363 "The display which contains this window no longer has focus.");
Michael Wright3dd60e22019-03-27 22:06:44 +00005364 options.displayId = ADISPLAY_ID_NONE;
Tiger Huang721e26f2018-07-24 22:26:19 +08005365 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
5366 }
5367 }
5368 mFocusedDisplayId = displayId;
5369
Chris Ye3c2d6f52020-08-09 10:39:48 -07005370 // Find new focused window and validate
Vishnu Nairc519ff72021-01-21 08:23:08 -08005371 sp<IBinder> newFocusedWindowToken = mFocusResolver.getFocusedWindowToken(displayId);
Prabir Pradhancef936d2021-07-21 16:17:52 +00005372 sendFocusChangedCommandLocked(oldFocusedWindowToken, newFocusedWindowToken);
Robert Carrf759f162018-11-13 12:57:11 -08005373
Vishnu Nairad321cd2020-08-20 16:40:21 -07005374 if (newFocusedWindowToken == nullptr) {
Tiger Huang721e26f2018-07-24 22:26:19 +08005375 ALOGW("Focused display #%" PRId32 " does not have a focused window.", displayId);
Vishnu Nairc519ff72021-01-21 08:23:08 -08005376 if (mFocusResolver.hasFocusedWindowTokens()) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07005377 ALOGE("But another display has a focused window\n%s",
Vishnu Nairc519ff72021-01-21 08:23:08 -08005378 mFocusResolver.dumpFocusedWindows().c_str());
Tiger Huang721e26f2018-07-24 22:26:19 +08005379 }
5380 }
5381 }
Tiger Huang721e26f2018-07-24 22:26:19 +08005382 } // release lock
5383
5384 // Wake up poll loop since it may need to make new input dispatching choices.
5385 mLooper->wake();
5386}
5387
Michael Wrightd02c5b62014-02-10 15:10:22 -08005388void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005389 if (DEBUG_FOCUS) {
5390 ALOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
5391 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005392
5393 bool changed;
5394 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005395 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005396
5397 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
5398 if (mDispatchFrozen && !frozen) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005399 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005400 }
5401
5402 if (mDispatchEnabled && !enabled) {
5403 resetAndDropEverythingLocked("dispatcher is being disabled");
5404 }
5405
5406 mDispatchEnabled = enabled;
5407 mDispatchFrozen = frozen;
5408 changed = true;
5409 } else {
5410 changed = false;
5411 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005412 } // release lock
5413
5414 if (changed) {
5415 // Wake up poll loop since it may need to make new input dispatching choices.
5416 mLooper->wake();
5417 }
5418}
5419
5420void InputDispatcher::setInputFilterEnabled(bool enabled) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005421 if (DEBUG_FOCUS) {
5422 ALOGD("setInputFilterEnabled: enabled=%d", enabled);
5423 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005424
5425 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005426 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005427
5428 if (mInputFilterEnabled == enabled) {
5429 return;
5430 }
5431
5432 mInputFilterEnabled = enabled;
5433 resetAndDropEverythingLocked("input filter is being enabled or disabled");
5434 } // release lock
5435
5436 // Wake up poll loop since there might be work to do to drop everything.
5437 mLooper->wake();
5438}
5439
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005440bool InputDispatcher::setInTouchMode(bool inTouchMode, gui::Pid pid, gui::Uid uid,
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00005441 bool hasPermission, int32_t displayId) {
Antonio Kantekf16f2832021-09-28 04:39:20 +00005442 bool needWake = false;
5443 {
5444 std::scoped_lock lock(mLock);
Antonio Kantek15beb512022-06-13 22:35:41 +00005445 ALOGD_IF(DEBUG_TOUCH_MODE,
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005446 "Request to change touch mode to %s (calling pid=%s, uid=%s, "
Antonio Kantek15beb512022-06-13 22:35:41 +00005447 "hasPermission=%s, target displayId=%d, mTouchModePerDisplay[displayId]=%s)",
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005448 toString(inTouchMode), pid.toString().c_str(), uid.toString().c_str(),
5449 toString(hasPermission), displayId,
Antonio Kantek15beb512022-06-13 22:35:41 +00005450 mTouchModePerDisplay.count(displayId) == 0
5451 ? "not set"
5452 : std::to_string(mTouchModePerDisplay[displayId]).c_str());
5453
Antonio Kantek15beb512022-06-13 22:35:41 +00005454 auto touchModeIt = mTouchModePerDisplay.find(displayId);
5455 if (touchModeIt != mTouchModePerDisplay.end() && touchModeIt->second == inTouchMode) {
Antonio Kantekea47acb2021-12-23 12:41:25 -08005456 return false;
Antonio Kantekf16f2832021-09-28 04:39:20 +00005457 }
Antonio Kantekea47acb2021-12-23 12:41:25 -08005458 if (!hasPermission) {
Antonio Kantek48710e42022-03-24 14:19:30 -07005459 if (!focusedWindowIsOwnedByLocked(pid, uid) &&
5460 !recentWindowsAreOwnedByLocked(pid, uid)) {
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005461 ALOGD("Touch mode switch rejected, caller (pid=%s, uid=%s) doesn't own the focused "
Antonio Kantek48710e42022-03-24 14:19:30 -07005462 "window nor none of the previously interacted window",
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005463 pid.toString().c_str(), uid.toString().c_str());
Antonio Kantekea47acb2021-12-23 12:41:25 -08005464 return false;
5465 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00005466 }
Antonio Kantek15beb512022-06-13 22:35:41 +00005467 mTouchModePerDisplay[displayId] = inTouchMode;
5468 auto entry = std::make_unique<TouchModeEntry>(mIdGenerator.nextId(), now(), inTouchMode,
5469 displayId);
Antonio Kantekf16f2832021-09-28 04:39:20 +00005470 needWake = enqueueInboundEventLocked(std::move(entry));
5471 } // release lock
5472
5473 if (needWake) {
5474 mLooper->wake();
5475 }
Antonio Kantekea47acb2021-12-23 12:41:25 -08005476 return true;
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -08005477}
5478
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005479bool InputDispatcher::focusedWindowIsOwnedByLocked(gui::Pid pid, gui::Uid uid) {
Antonio Kantek48710e42022-03-24 14:19:30 -07005480 const sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
5481 if (focusedToken == nullptr) {
5482 return false;
5483 }
5484 sp<WindowInfoHandle> windowHandle = getWindowHandleLocked(focusedToken);
5485 return isWindowOwnedBy(windowHandle, pid, uid);
5486}
5487
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005488bool InputDispatcher::recentWindowsAreOwnedByLocked(gui::Pid pid, gui::Uid uid) {
Antonio Kantek48710e42022-03-24 14:19:30 -07005489 return std::find_if(mInteractionConnectionTokens.begin(), mInteractionConnectionTokens.end(),
5490 [&](const sp<IBinder>& connectionToken) REQUIRES(mLock) {
5491 const sp<WindowInfoHandle> windowHandle =
5492 getWindowHandleLocked(connectionToken);
5493 return isWindowOwnedBy(windowHandle, pid, uid);
5494 }) != mInteractionConnectionTokens.end();
5495}
5496
Bernardo Rufinoea97d182020-08-19 14:43:14 +01005497void InputDispatcher::setMaximumObscuringOpacityForTouch(float opacity) {
5498 if (opacity < 0 || opacity > 1) {
5499 LOG_ALWAYS_FATAL("Maximum obscuring opacity for touch should be >= 0 and <= 1");
5500 return;
5501 }
5502
5503 std::scoped_lock lock(mLock);
5504 mMaximumObscuringOpacityForTouch = opacity;
5505}
5506
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005507std::tuple<TouchState*, TouchedWindow*, int32_t /*displayId*/>
5508InputDispatcher::findTouchStateWindowAndDisplayLocked(const sp<IBinder>& token) {
Arthur Hungabbb9d82021-09-01 14:52:30 +00005509 for (auto& [displayId, state] : mTouchStatesByDisplay) {
5510 for (TouchedWindow& w : state.windows) {
5511 if (w.windowHandle->getToken() == token) {
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005512 return std::make_tuple(&state, &w, displayId);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005513 }
5514 }
5515 }
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005516 return std::make_tuple(nullptr, nullptr, ADISPLAY_ID_DEFAULT);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005517}
5518
arthurhungb89ccb02020-12-30 16:19:01 +08005519bool InputDispatcher::transferTouchFocus(const sp<IBinder>& fromToken, const sp<IBinder>& toToken,
5520 bool isDragDrop) {
chaviwfbe5d9c2018-12-26 12:23:37 -08005521 if (fromToken == toToken) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005522 if (DEBUG_FOCUS) {
5523 ALOGD("Trivial transfer to same window.");
5524 }
chaviwfbe5d9c2018-12-26 12:23:37 -08005525 return true;
5526 }
5527
Michael Wrightd02c5b62014-02-10 15:10:22 -08005528 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005529 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005530
Arthur Hungabbb9d82021-09-01 14:52:30 +00005531 // Find the target touch state and touched window by fromToken.
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005532 auto [state, touchedWindow, displayId] = findTouchStateWindowAndDisplayLocked(fromToken);
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005533
Arthur Hungabbb9d82021-09-01 14:52:30 +00005534 if (state == nullptr || touchedWindow == nullptr) {
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005535 ALOGD("Touch transfer failed because from window is not being touched.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005536 return false;
5537 }
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005538 std::set<int32_t> deviceIds = touchedWindow->getTouchingDeviceIds();
5539 if (deviceIds.size() != 1) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07005540 LOG(INFO) << "Can't transfer touch. Currently touching devices: " << dumpSet(deviceIds)
5541 << " for window: " << touchedWindow->dump();
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005542 return false;
5543 }
5544 const int32_t deviceId = *deviceIds.begin();
Arthur Hungabbb9d82021-09-01 14:52:30 +00005545
Arthur Hungabbb9d82021-09-01 14:52:30 +00005546 sp<WindowInfoHandle> toWindowHandle = getWindowHandleLocked(toToken, displayId);
5547 if (toWindowHandle == nullptr) {
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005548 ALOGW("Cannot transfer touch because to window not found.");
Arthur Hungabbb9d82021-09-01 14:52:30 +00005549 return false;
5550 }
5551
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005552 if (DEBUG_FOCUS) {
5553 ALOGD("transferTouchFocus: fromWindowHandle=%s, toWindowHandle=%s",
Arthur Hungabbb9d82021-09-01 14:52:30 +00005554 touchedWindow->windowHandle->getName().c_str(),
5555 toWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005556 }
5557
Arthur Hungabbb9d82021-09-01 14:52:30 +00005558 // Erase old window.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005559 ftl::Flags<InputTarget::Flags> oldTargetFlags = touchedWindow->targetFlags;
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08005560 std::vector<PointerProperties> pointers = touchedWindow->getTouchingPointers(deviceId);
Arthur Hungc539dbb2022-12-08 07:45:36 +00005561 sp<WindowInfoHandle> fromWindowHandle = touchedWindow->windowHandle;
Arthur Hungabbb9d82021-09-01 14:52:30 +00005562 state->removeWindowByToken(fromToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005563
Arthur Hungabbb9d82021-09-01 14:52:30 +00005564 // Add new window.
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00005565 nsecs_t downTimeInTarget = now();
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005566 ftl::Flags<InputTarget::Flags> newTargetFlags =
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00005567 oldTargetFlags & (InputTarget::Flags::SPLIT);
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00005568 if (canReceiveForegroundTouches(*toWindowHandle->getInfo())) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005569 newTargetFlags |= InputTarget::Flags::FOREGROUND;
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00005570 }
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00005571 state->addOrUpdateWindow(toWindowHandle, InputTarget::DispatchMode::AS_IS, newTargetFlags,
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08005572 deviceId, pointers, downTimeInTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005573
Arthur Hungabbb9d82021-09-01 14:52:30 +00005574 // Store the dragging window.
5575 if (isDragDrop) {
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08005576 if (pointers.size() != 1) {
Arthur Hungb75c2aa2022-07-15 09:35:36 +00005577 ALOGW("The drag and drop cannot be started when there is no pointer or more than 1"
5578 " pointer on the window.");
Arthur Hung54745652022-04-20 07:17:41 +00005579 return false;
5580 }
Arthur Hungb75c2aa2022-07-15 09:35:36 +00005581 // Track the pointer id for drag window and generate the drag state.
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08005582 const size_t id = pointers.begin()->id;
Arthur Hung54745652022-04-20 07:17:41 +00005583 mDragState = std::make_unique<DragState>(toWindowHandle, id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005584 }
5585
Arthur Hungabbb9d82021-09-01 14:52:30 +00005586 // Synthesize cancel for old window and down for new window.
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07005587 std::shared_ptr<Connection> fromConnection = getConnectionLocked(fromToken);
5588 std::shared_ptr<Connection> toConnection = getConnectionLocked(toToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005589 if (fromConnection != nullptr && toConnection != nullptr) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08005590 fromConnection->inputState.mergePointerStateTo(toConnection->inputState);
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005591 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
5592 "transferring touch from this window to another window");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005593 synthesizeCancelationEventsForConnectionLocked(fromConnection, options);
Arthur Hungc539dbb2022-12-08 07:45:36 +00005594 synthesizePointerDownEventsForConnectionLocked(downTimeInTarget, toConnection,
5595 newTargetFlags);
5596
5597 // Check if the wallpaper window should deliver the corresponding event.
5598 transferWallpaperTouch(oldTargetFlags, newTargetFlags, fromWindowHandle, toWindowHandle,
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08005599 *state, deviceId, pointers);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005600 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005601 } // release lock
5602
5603 // Wake up poll loop since it may need to make new input dispatching choices.
5604 mLooper->wake();
5605 return true;
5606}
5607
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005608/**
5609 * Get the touched foreground window on the given display.
5610 * Return null if there are no windows touched on that display, or if more than one foreground
5611 * window is being touched.
5612 */
5613sp<WindowInfoHandle> InputDispatcher::findTouchedForegroundWindowLocked(int32_t displayId) const {
5614 auto stateIt = mTouchStatesByDisplay.find(displayId);
5615 if (stateIt == mTouchStatesByDisplay.end()) {
5616 ALOGI("No touch state on display %" PRId32, displayId);
5617 return nullptr;
5618 }
5619
5620 const TouchState& state = stateIt->second;
5621 sp<WindowInfoHandle> touchedForegroundWindow;
5622 // If multiple foreground windows are touched, return nullptr
5623 for (const TouchedWindow& window : state.windows) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005624 if (window.targetFlags.test(InputTarget::Flags::FOREGROUND)) {
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005625 if (touchedForegroundWindow != nullptr) {
5626 ALOGI("Two or more foreground windows: %s and %s",
5627 touchedForegroundWindow->getName().c_str(),
5628 window.windowHandle->getName().c_str());
5629 return nullptr;
5630 }
5631 touchedForegroundWindow = window.windowHandle;
5632 }
5633 }
5634 return touchedForegroundWindow;
5635}
5636
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005637// Binder call
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005638bool InputDispatcher::transferTouch(const sp<IBinder>& destChannelToken, int32_t displayId) {
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005639 sp<IBinder> fromToken;
5640 { // acquire lock
5641 std::scoped_lock _l(mLock);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005642 sp<WindowInfoHandle> toWindowHandle = getWindowHandleLocked(destChannelToken, displayId);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005643 if (toWindowHandle == nullptr) {
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005644 ALOGW("Could not find window associated with token=%p on display %" PRId32,
5645 destChannelToken.get(), displayId);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005646 return false;
5647 }
5648
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005649 sp<WindowInfoHandle> from = findTouchedForegroundWindowLocked(displayId);
5650 if (from == nullptr) {
5651 ALOGE("Could not find a source window in %s for %p", __func__, destChannelToken.get());
5652 return false;
5653 }
5654
5655 fromToken = from->getToken();
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005656 } // release lock
5657
5658 return transferTouchFocus(fromToken, destChannelToken);
5659}
5660
Michael Wrightd02c5b62014-02-10 15:10:22 -08005661void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005662 if (DEBUG_FOCUS) {
5663 ALOGD("Resetting and dropping all events (%s).", reason);
5664 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005665
Michael Wrightfb04fd52022-11-24 22:31:11 +00005666 CancelationOptions options(CancelationOptions::Mode::CANCEL_ALL_EVENTS, reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005667 synthesizeCancelationEventsForAllConnectionsLocked(options);
5668
5669 resetKeyRepeatLocked();
5670 releasePendingEventLocked();
5671 drainInboundQueueLocked();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005672 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005673
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005674 mAnrTracker.clear();
Jeff Brownf086ddb2014-02-11 14:28:48 -08005675 mTouchStatesByDisplay.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005676}
5677
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005678void InputDispatcher::logDispatchStateLocked() const {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005679 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005680 dumpDispatchStateLocked(dump);
5681
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005682 std::istringstream stream(dump);
5683 std::string line;
5684
5685 while (std::getline(stream, line, '\n')) {
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07005686 ALOGI("%s", line.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005687 }
5688}
5689
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005690std::string InputDispatcher::dumpPointerCaptureStateLocked() const {
Prabir Pradhan99987712020-11-10 18:43:05 -08005691 std::string dump;
5692
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005693 dump += StringPrintf(INDENT "Pointer Capture Requested: %s\n",
5694 toString(mCurrentPointerCaptureRequest.enable));
Prabir Pradhan99987712020-11-10 18:43:05 -08005695
5696 std::string windowName = "None";
5697 if (mWindowTokenWithPointerCapture) {
chaviw98318de2021-05-19 16:45:23 -05005698 const sp<WindowInfoHandle> captureWindowHandle =
Prabir Pradhan99987712020-11-10 18:43:05 -08005699 getWindowHandleLocked(mWindowTokenWithPointerCapture);
5700 windowName = captureWindowHandle ? captureWindowHandle->getName().c_str()
5701 : "token has capture without window";
5702 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005703 dump += StringPrintf(INDENT "Current Window with Pointer Capture: %s\n", windowName.c_str());
Prabir Pradhan99987712020-11-10 18:43:05 -08005704
5705 return dump;
5706}
5707
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005708void InputDispatcher::dumpDispatchStateLocked(std::string& dump) const {
Siarhei Vishniakou043a3ec2019-05-01 11:30:46 -07005709 dump += StringPrintf(INDENT "DispatchEnabled: %s\n", toString(mDispatchEnabled));
5710 dump += StringPrintf(INDENT "DispatchFrozen: %s\n", toString(mDispatchFrozen));
5711 dump += StringPrintf(INDENT "InputFilterEnabled: %s\n", toString(mInputFilterEnabled));
Tiger Huang721e26f2018-07-24 22:26:19 +08005712 dump += StringPrintf(INDENT "FocusedDisplayId: %" PRId32 "\n", mFocusedDisplayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005713
Tiger Huang721e26f2018-07-24 22:26:19 +08005714 if (!mFocusedApplicationHandlesByDisplay.empty()) {
5715 dump += StringPrintf(INDENT "FocusedApplications:\n");
5716 for (auto& it : mFocusedApplicationHandlesByDisplay) {
5717 const int32_t displayId = it.first;
Chris Yea209fde2020-07-22 13:54:51 -07005718 const std::shared_ptr<InputApplicationHandle>& applicationHandle = it.second;
Siarhei Vishniakou70622952020-07-30 11:17:23 -05005719 const std::chrono::duration timeout =
5720 applicationHandle->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005721 dump += StringPrintf(INDENT2 "displayId=%" PRId32
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005722 ", name='%s', dispatchingTimeout=%" PRId64 "ms\n",
Siarhei Vishniakou70622952020-07-30 11:17:23 -05005723 displayId, applicationHandle->getName().c_str(), millis(timeout));
Tiger Huang721e26f2018-07-24 22:26:19 +08005724 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005725 } else {
Tiger Huang721e26f2018-07-24 22:26:19 +08005726 dump += StringPrintf(INDENT "FocusedApplications: <none>\n");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005727 }
Tiger Huang721e26f2018-07-24 22:26:19 +08005728
Vishnu Nairc519ff72021-01-21 08:23:08 -08005729 dump += mFocusResolver.dump();
Prabir Pradhan99987712020-11-10 18:43:05 -08005730 dump += dumpPointerCaptureStateLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005731
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005732 if (!mTouchStatesByDisplay.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005733 dump += StringPrintf(INDENT "TouchStatesByDisplay:\n");
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005734 for (const auto& [displayId, state] : mTouchStatesByDisplay) {
Siarhei Vishniakou6e1e9872022-11-08 17:51:35 -08005735 std::string touchStateDump = addLinePrefix(state.dump(), INDENT2);
5736 dump += INDENT2 + std::to_string(displayId) + " : " + touchStateDump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005737 }
5738 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005739 dump += INDENT "TouchStates: <no displays touched>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005740 }
5741
arthurhung6d4bed92021-03-17 11:59:33 +08005742 if (mDragState) {
5743 dump += StringPrintf(INDENT "DragState:\n");
5744 mDragState->dump(dump, INDENT2);
5745 }
5746
Arthur Hungb92218b2018-08-14 12:00:21 +08005747 if (!mWindowHandlesByDisplay.empty()) {
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005748 for (const auto& [displayId, windowHandles] : mWindowHandlesByDisplay) {
5749 dump += StringPrintf(INDENT "Display: %" PRId32 "\n", displayId);
5750 if (const auto& it = mDisplayInfos.find(displayId); it != mDisplayInfos.end()) {
5751 const auto& displayInfo = it->second;
5752 dump += StringPrintf(INDENT2 "logicalSize=%dx%d\n", displayInfo.logicalWidth,
5753 displayInfo.logicalHeight);
5754 displayInfo.transform.dump(dump, "transform", INDENT4);
5755 } else {
5756 dump += INDENT2 "No DisplayInfo found!\n";
5757 }
5758
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08005759 if (!windowHandles.empty()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08005760 dump += INDENT2 "Windows:\n";
5761 for (size_t i = 0; i < windowHandles.size(); i++) {
Siarhei Vishniakou366fb5b2023-12-06 11:23:41 -08005762 dump += StringPrintf(INDENT3 "%zu: %s", i,
5763 streamableToString(*windowHandles[i]).c_str());
Arthur Hungb92218b2018-08-14 12:00:21 +08005764 }
5765 } else {
5766 dump += INDENT2 "Windows: <none>\n";
5767 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005768 }
5769 } else {
Arthur Hungb92218b2018-08-14 12:00:21 +08005770 dump += INDENT "Displays: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005771 }
5772
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005773 if (!mGlobalMonitorsByDisplay.empty()) {
5774 for (const auto& [displayId, monitors] : mGlobalMonitorsByDisplay) {
5775 dump += StringPrintf(INDENT "Global monitors on display %d:\n", displayId);
Michael Wright3dd60e22019-03-27 22:06:44 +00005776 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005777 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005778 } else {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005779 dump += INDENT "Global Monitors: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005780 }
5781
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005782 const nsecs_t currentTime = now();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005783
5784 // Dump recently dispatched or dropped events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005785 if (!mRecentQueue.empty()) {
5786 dump += StringPrintf(INDENT "RecentQueue: length=%zu\n", mRecentQueue.size());
Prabir Pradhan24047542023-11-02 17:14:59 +00005787 for (const std::shared_ptr<const EventEntry>& entry : mRecentQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005788 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005789 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005790 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005791 }
5792 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005793 dump += INDENT "RecentQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005794 }
5795
5796 // Dump event currently being dispatched.
5797 if (mPendingEvent) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005798 dump += INDENT "PendingEvent:\n";
5799 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005800 dump += mPendingEvent->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005801 dump += StringPrintf(", age=%" PRId64 "ms\n",
5802 ns2ms(currentTime - mPendingEvent->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005803 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005804 dump += INDENT "PendingEvent: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005805 }
5806
5807 // Dump inbound events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005808 if (!mInboundQueue.empty()) {
5809 dump += StringPrintf(INDENT "InboundQueue: length=%zu\n", mInboundQueue.size());
Prabir Pradhan24047542023-11-02 17:14:59 +00005810 for (const std::shared_ptr<const EventEntry>& entry : mInboundQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005811 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005812 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005813 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005814 }
5815 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005816 dump += INDENT "InboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005817 }
5818
Prabir Pradhancef936d2021-07-21 16:17:52 +00005819 if (!mCommandQueue.empty()) {
5820 dump += StringPrintf(INDENT "CommandQueue: size=%zu\n", mCommandQueue.size());
5821 } else {
5822 dump += INDENT "CommandQueue: <empty>\n";
5823 }
5824
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005825 if (!mConnectionsByToken.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005826 dump += INDENT "Connections:\n";
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005827 for (const auto& [token, connection] : mConnectionsByToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005828 dump += StringPrintf(INDENT2 "%i: channelName='%s', windowName='%s', "
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005829 "status=%s, monitor=%s, responsive=%s\n",
Siarhei Vishniakou8d660132024-01-11 16:48:44 -08005830 connection->inputChannel->getFd(),
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005831 connection->getInputChannelName().c_str(),
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08005832 connection->getWindowName().c_str(),
5833 ftl::enum_string(connection->status).c_str(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005834 toString(connection->monitor), toString(connection->responsive));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005835
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005836 if (!connection->outboundQueue.empty()) {
5837 dump += StringPrintf(INDENT3 "OutboundQueue: length=%zu\n",
5838 connection->outboundQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005839 dump += dumpQueue(connection->outboundQueue, currentTime);
5840
Michael Wrightd02c5b62014-02-10 15:10:22 -08005841 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005842 dump += INDENT3 "OutboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005843 }
5844
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005845 if (!connection->waitQueue.empty()) {
5846 dump += StringPrintf(INDENT3 "WaitQueue: length=%zu\n",
5847 connection->waitQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005848 dump += dumpQueue(connection->waitQueue, currentTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005849 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005850 dump += INDENT3 "WaitQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005851 }
Siarhei Vishniakou366fb5b2023-12-06 11:23:41 -08005852 std::string inputStateDump = streamableToString(connection->inputState);
5853 if (!inputStateDump.empty()) {
Siarhei Vishniakoud38a1e02023-07-18 11:55:17 -07005854 dump += INDENT3 "InputState: ";
Siarhei Vishniakou366fb5b2023-12-06 11:23:41 -08005855 dump += inputStateDump + "\n";
Siarhei Vishniakoud38a1e02023-07-18 11:55:17 -07005856 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005857 }
5858 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005859 dump += INDENT "Connections: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005860 }
5861
Antonio Kantek15beb512022-06-13 22:35:41 +00005862 if (!mTouchModePerDisplay.empty()) {
5863 dump += INDENT "TouchModePerDisplay:\n";
5864 for (const auto& [displayId, touchMode] : mTouchModePerDisplay) {
5865 dump += StringPrintf(INDENT2 "Display: %" PRId32 " TouchMode: %s\n", displayId,
5866 std::to_string(touchMode).c_str());
5867 }
5868 } else {
5869 dump += INDENT "TouchModePerDisplay: <none>\n";
5870 }
5871
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005872 dump += INDENT "Configuration:\n";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005873 dump += StringPrintf(INDENT2 "KeyRepeatDelay: %" PRId64 "ms\n", ns2ms(mConfig.keyRepeatDelay));
5874 dump += StringPrintf(INDENT2 "KeyRepeatTimeout: %" PRId64 "ms\n",
5875 ns2ms(mConfig.keyRepeatTimeout));
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00005876 dump += mLatencyTracker.dump(INDENT2);
Siarhei Vishniakoua04181f2021-03-26 05:56:49 +00005877 dump += mLatencyAggregator.dump(INDENT2);
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00005878 dump += INDENT "InputTracer: ";
5879 dump += mTracer == nullptr ? "Disabled" : "Enabled";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005880}
5881
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005882void InputDispatcher::dumpMonitors(std::string& dump, const std::vector<Monitor>& monitors) const {
Michael Wright3dd60e22019-03-27 22:06:44 +00005883 const size_t numMonitors = monitors.size();
5884 for (size_t i = 0; i < numMonitors; i++) {
5885 const Monitor& monitor = monitors[i];
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005886 const std::shared_ptr<InputChannel>& channel = monitor.inputChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005887 dump += StringPrintf(INDENT2 "%zu: '%s', ", i, channel->getName().c_str());
5888 dump += "\n";
5889 }
5890}
5891
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005892class LooperEventCallback : public LooperCallback {
5893public:
5894 LooperEventCallback(std::function<int(int events)> callback) : mCallback(callback) {}
5895 int handleEvent(int /*fd*/, int events, void* /*data*/) override { return mCallback(events); }
5896
5897private:
5898 std::function<int(int events)> mCallback;
5899};
5900
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005901Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputChannel(const std::string& name) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00005902 if (DEBUG_CHANNEL_CREATION) {
5903 ALOGD("channel '%s' ~ createInputChannel", name.c_str());
5904 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005905
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005906 std::unique_ptr<InputChannel> serverChannel;
Garfield Tan15601662020-09-22 15:32:38 -07005907 std::unique_ptr<InputChannel> clientChannel;
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005908 status_t result = InputChannel::openInputChannelPair(name, serverChannel, clientChannel);
Garfield Tan15601662020-09-22 15:32:38 -07005909
5910 if (result) {
5911 return base::Error(result) << "Failed to open input channel pair with name " << name;
5912 }
5913
Michael Wrightd02c5b62014-02-10 15:10:22 -08005914 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005915 std::scoped_lock _l(mLock);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005916 const sp<IBinder>& token = serverChannel->getConnectionToken();
Siarhei Vishniakou8d660132024-01-11 16:48:44 -08005917 const int fd = serverChannel->getFd();
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07005918 std::shared_ptr<Connection> connection =
5919 std::make_shared<Connection>(std::move(serverChannel), /*monitor=*/false,
5920 mIdGenerator);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005921
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005922 if (mConnectionsByToken.find(token) != mConnectionsByToken.end()) {
5923 ALOGE("Created a new connection, but the token %p is already known", token.get());
5924 }
5925 mConnectionsByToken.emplace(token, connection);
5926
5927 std::function<int(int events)> callback = std::bind(&InputDispatcher::handleReceiveCallback,
5928 this, std::placeholders::_1, token);
5929
Siarhei Vishniakou8d660132024-01-11 16:48:44 -08005930 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, sp<LooperEventCallback>::make(callback),
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005931 nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005932 } // release lock
5933
5934 // Wake the looper because some connections have changed.
5935 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07005936 return clientChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005937}
5938
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005939Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputMonitor(int32_t displayId,
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005940 const std::string& name,
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005941 gui::Pid pid) {
Garfield Tan15601662020-09-22 15:32:38 -07005942 std::shared_ptr<InputChannel> serverChannel;
5943 std::unique_ptr<InputChannel> clientChannel;
5944 status_t result = openInputChannelPair(name, serverChannel, clientChannel);
5945 if (result) {
5946 return base::Error(result) << "Failed to open input channel pair with name " << name;
5947 }
5948
Michael Wright3dd60e22019-03-27 22:06:44 +00005949 { // acquire lock
5950 std::scoped_lock _l(mLock);
5951
5952 if (displayId < 0) {
Garfield Tan15601662020-09-22 15:32:38 -07005953 return base::Error(BAD_VALUE) << "Attempted to create input monitor with name " << name
5954 << " without a specified display.";
Michael Wright3dd60e22019-03-27 22:06:44 +00005955 }
5956
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07005957 std::shared_ptr<Connection> connection =
5958 std::make_shared<Connection>(serverChannel, /*monitor=*/true, mIdGenerator);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005959 const sp<IBinder>& token = serverChannel->getConnectionToken();
Siarhei Vishniakou8d660132024-01-11 16:48:44 -08005960 const int fd = serverChannel->getFd();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005961
5962 if (mConnectionsByToken.find(token) != mConnectionsByToken.end()) {
5963 ALOGE("Created a new connection, but the token %p is already known", token.get());
5964 }
5965 mConnectionsByToken.emplace(token, connection);
5966 std::function<int(int events)> callback = std::bind(&InputDispatcher::handleReceiveCallback,
5967 this, std::placeholders::_1, token);
Michael Wright3dd60e22019-03-27 22:06:44 +00005968
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005969 mGlobalMonitorsByDisplay[displayId].emplace_back(serverChannel, pid);
Michael Wright3dd60e22019-03-27 22:06:44 +00005970
Siarhei Vishniakou8d660132024-01-11 16:48:44 -08005971 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, sp<LooperEventCallback>::make(callback),
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005972 nullptr);
Michael Wright3dd60e22019-03-27 22:06:44 +00005973 }
Garfield Tan15601662020-09-22 15:32:38 -07005974
Michael Wright3dd60e22019-03-27 22:06:44 +00005975 // Wake the looper because some connections have changed.
5976 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07005977 return clientChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005978}
5979
Garfield Tan15601662020-09-22 15:32:38 -07005980status_t InputDispatcher::removeInputChannel(const sp<IBinder>& connectionToken) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005981 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005982 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005983
Harry Cutts33476232023-01-30 19:57:29 +00005984 status_t status = removeInputChannelLocked(connectionToken, /*notify=*/false);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005985 if (status) {
5986 return status;
5987 }
5988 } // release lock
5989
5990 // Wake the poll loop because removing the connection may have changed the current
5991 // synchronization state.
5992 mLooper->wake();
5993 return OK;
5994}
5995
Garfield Tan15601662020-09-22 15:32:38 -07005996status_t InputDispatcher::removeInputChannelLocked(const sp<IBinder>& connectionToken,
5997 bool notify) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07005998 std::shared_ptr<Connection> connection = getConnectionLocked(connectionToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005999 if (connection == nullptr) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00006000 // Connection can be removed via socket hang up or an explicit call to 'removeInputChannel'
Michael Wrightd02c5b62014-02-10 15:10:22 -08006001 return BAD_VALUE;
6002 }
6003
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07006004 removeConnectionLocked(connection);
Robert Carr5c8a0262018-10-03 16:30:44 -07006005
Michael Wrightd02c5b62014-02-10 15:10:22 -08006006 if (connection->monitor) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05006007 removeMonitorChannelLocked(connectionToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006008 }
6009
Siarhei Vishniakou8d660132024-01-11 16:48:44 -08006010 mLooper->removeFd(connection->inputChannel->getFd());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006011
6012 nsecs_t currentTime = now();
6013 abortBrokenDispatchCycleLocked(currentTime, connection, notify);
6014
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08006015 connection->status = Connection::Status::ZOMBIE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006016 return OK;
6017}
6018
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05006019void InputDispatcher::removeMonitorChannelLocked(const sp<IBinder>& connectionToken) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006020 for (auto it = mGlobalMonitorsByDisplay.begin(); it != mGlobalMonitorsByDisplay.end();) {
6021 auto& [displayId, monitors] = *it;
6022 std::erase_if(monitors, [connectionToken](const Monitor& monitor) {
6023 return monitor.inputChannel->getConnectionToken() == connectionToken;
6024 });
Michael Wright3dd60e22019-03-27 22:06:44 +00006025
Michael Wright3dd60e22019-03-27 22:06:44 +00006026 if (monitors.empty()) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006027 it = mGlobalMonitorsByDisplay.erase(it);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08006028 } else {
6029 ++it;
6030 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006031 }
6032}
6033
Michael Wright3dd60e22019-03-27 22:06:44 +00006034status_t InputDispatcher::pilferPointers(const sp<IBinder>& token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006035 std::scoped_lock _l(mLock);
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00006036 return pilferPointersLocked(token);
6037}
Michael Wright3dd60e22019-03-27 22:06:44 +00006038
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00006039status_t InputDispatcher::pilferPointersLocked(const sp<IBinder>& token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006040 const std::shared_ptr<InputChannel> requestingChannel = getInputChannelLocked(token);
6041 if (!requestingChannel) {
Siarhei Vishniakou8384e0d2023-09-18 18:48:27 -07006042 LOG(WARNING)
6043 << "Attempted to pilfer pointers from an un-registered channel or invalid token";
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006044 return BAD_VALUE;
Michael Wright3dd60e22019-03-27 22:06:44 +00006045 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006046
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07006047 auto [statePtr, windowPtr, displayId] = findTouchStateWindowAndDisplayLocked(token);
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07006048 if (statePtr == nullptr || windowPtr == nullptr) {
Siarhei Vishniakou8384e0d2023-09-18 18:48:27 -07006049 LOG(WARNING)
6050 << "Attempted to pilfer points from a channel without any on-going pointer streams."
6051 " Ignoring.";
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006052 return BAD_VALUE;
6053 }
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07006054 std::set<int32_t> deviceIds = windowPtr->getTouchingDeviceIds();
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07006055 if (deviceIds.empty()) {
6056 LOG(WARNING) << "Can't pilfer: no touching devices in window: " << windowPtr->dump();
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07006057 return BAD_VALUE;
6058 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006059
Siarhei Vishniakou8384e0d2023-09-18 18:48:27 -07006060 for (const DeviceId deviceId : deviceIds) {
6061 TouchState& state = *statePtr;
6062 TouchedWindow& window = *windowPtr;
6063 // Send cancel events to all the input channels we're stealing from.
6064 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
6065 "input channel stole pointer stream");
6066 options.deviceId = deviceId;
6067 options.displayId = displayId;
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08006068 std::vector<PointerProperties> pointers = window.getTouchingPointers(deviceId);
6069 std::bitset<MAX_POINTER_ID + 1> pointerIds = getPointerIds(pointers);
Siarhei Vishniakou8384e0d2023-09-18 18:48:27 -07006070 options.pointerIds = pointerIds;
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08006071
Siarhei Vishniakou8384e0d2023-09-18 18:48:27 -07006072 std::string canceledWindows;
6073 for (const TouchedWindow& w : state.windows) {
6074 const std::shared_ptr<InputChannel> channel =
6075 getInputChannelLocked(w.windowHandle->getToken());
6076 if (channel != nullptr && channel->getConnectionToken() != token) {
6077 synthesizeCancelationEventsForInputChannelLocked(channel, options);
6078 canceledWindows += canceledWindows.empty() ? "[" : ", ";
6079 canceledWindows += channel->getName();
6080 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006081 }
Siarhei Vishniakou8384e0d2023-09-18 18:48:27 -07006082 canceledWindows += canceledWindows.empty() ? "[]" : "]";
6083 LOG(INFO) << "Channel " << requestingChannel->getName()
6084 << " is stealing input gesture for device " << deviceId << " from "
6085 << canceledWindows;
6086
6087 // Prevent the gesture from being sent to any other windows.
6088 // This only blocks relevant pointers to be sent to other windows
6089 window.addPilferingPointers(deviceId, pointerIds);
6090
6091 state.cancelPointersForWindowsExcept(deviceId, pointerIds, token);
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006092 }
Michael Wright3dd60e22019-03-27 22:06:44 +00006093 return OK;
6094}
6095
Prabir Pradhan99987712020-11-10 18:43:05 -08006096void InputDispatcher::requestPointerCapture(const sp<IBinder>& windowToken, bool enabled) {
6097 { // acquire lock
6098 std::scoped_lock _l(mLock);
6099 if (DEBUG_FOCUS) {
chaviw98318de2021-05-19 16:45:23 -05006100 const sp<WindowInfoHandle> windowHandle = getWindowHandleLocked(windowToken);
Prabir Pradhan99987712020-11-10 18:43:05 -08006101 ALOGI("Request to %s Pointer Capture from: %s.", enabled ? "enable" : "disable",
6102 windowHandle != nullptr ? windowHandle->getName().c_str()
6103 : "token without window");
6104 }
6105
Vishnu Nairc519ff72021-01-21 08:23:08 -08006106 const sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Prabir Pradhan99987712020-11-10 18:43:05 -08006107 if (focusedToken != windowToken) {
6108 ALOGW("Ignoring request to %s Pointer Capture: window does not have focus.",
6109 enabled ? "enable" : "disable");
6110 return;
6111 }
6112
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006113 if (enabled == mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006114 ALOGW("Ignoring request to %s Pointer Capture: "
6115 "window has %s requested pointer capture.",
6116 enabled ? "enable" : "disable", enabled ? "already" : "not");
6117 return;
6118 }
6119
Christine Franksb768bb42021-11-29 12:11:31 -08006120 if (enabled) {
6121 if (std::find(mIneligibleDisplaysForPointerCapture.begin(),
6122 mIneligibleDisplaysForPointerCapture.end(),
6123 mFocusedDisplayId) != mIneligibleDisplaysForPointerCapture.end()) {
6124 ALOGW("Ignoring request to enable Pointer Capture: display is not eligible");
6125 return;
6126 }
6127 }
6128
Prabir Pradhan99987712020-11-10 18:43:05 -08006129 setPointerCaptureLocked(enabled);
6130 } // release lock
6131
6132 // Wake the thread to process command entries.
6133 mLooper->wake();
6134}
6135
Christine Franksb768bb42021-11-29 12:11:31 -08006136void InputDispatcher::setDisplayEligibilityForPointerCapture(int32_t displayId, bool isEligible) {
6137 { // acquire lock
6138 std::scoped_lock _l(mLock);
6139 std::erase(mIneligibleDisplaysForPointerCapture, displayId);
6140 if (!isEligible) {
6141 mIneligibleDisplaysForPointerCapture.push_back(displayId);
6142 }
6143 } // release lock
6144}
6145
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00006146std::optional<gui::Pid> InputDispatcher::findMonitorPidByTokenLocked(const sp<IBinder>& token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006147 for (const auto& [_, monitors] : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00006148 for (const Monitor& monitor : monitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07006149 if (monitor.inputChannel->getConnectionToken() == token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006150 return monitor.pid;
Michael Wright3dd60e22019-03-27 22:06:44 +00006151 }
6152 }
6153 }
6154 return std::nullopt;
6155}
6156
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006157std::shared_ptr<Connection> InputDispatcher::getConnectionLocked(
6158 const sp<IBinder>& inputConnectionToken) const {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07006159 if (inputConnectionToken == nullptr) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07006160 return nullptr;
Arthur Hung3b413f22018-10-26 18:05:34 +08006161 }
6162
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00006163 for (const auto& [token, connection] : mConnectionsByToken) {
6164 if (token == inputConnectionToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07006165 return connection;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006166 }
6167 }
Robert Carr4e670e52018-08-15 13:26:12 -07006168
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07006169 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006170}
6171
Siarhei Vishniakouad991402020-10-28 11:40:09 -05006172std::string InputDispatcher::getConnectionNameLocked(const sp<IBinder>& connectionToken) const {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006173 std::shared_ptr<Connection> connection = getConnectionLocked(connectionToken);
Siarhei Vishniakouad991402020-10-28 11:40:09 -05006174 if (connection == nullptr) {
6175 return "<nullptr>";
6176 }
6177 return connection->getInputChannelName();
6178}
6179
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006180void InputDispatcher::removeConnectionLocked(const std::shared_ptr<Connection>& connection) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006181 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00006182 mConnectionsByToken.erase(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07006183}
6184
Prabir Pradhancef936d2021-07-21 16:17:52 +00006185void InputDispatcher::doDispatchCycleFinishedCommand(nsecs_t finishTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006186 const std::shared_ptr<Connection>& connection,
6187 uint32_t seq, bool handled,
6188 nsecs_t consumeTime) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006189 // Handle post-event policy actions.
Prabir Pradhan24047542023-11-02 17:14:59 +00006190 std::unique_ptr<const KeyEntry> fallbackKeyEntry;
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006191
6192 { // Start critical section
6193 auto dispatchEntryIt =
6194 std::find_if(connection->waitQueue.begin(), connection->waitQueue.end(),
6195 [seq](auto& e) { return e->seq == seq; });
6196 if (dispatchEntryIt == connection->waitQueue.end()) {
6197 return;
6198 }
6199
6200 DispatchEntry& dispatchEntry = **dispatchEntryIt;
6201
6202 const nsecs_t eventDuration = finishTime - dispatchEntry.deliveryTime;
6203 if (eventDuration > SLOW_EVENT_PROCESSING_WARNING_TIMEOUT) {
6204 ALOGI("%s spent %" PRId64 "ms processing %s", connection->getWindowName().c_str(),
6205 ns2ms(eventDuration), dispatchEntry.eventEntry->getDescription().c_str());
6206 }
6207 if (shouldReportFinishedEvent(dispatchEntry, *connection)) {
6208 mLatencyTracker.trackFinishedEvent(dispatchEntry.eventEntry->id,
6209 connection->inputChannel->getConnectionToken(),
6210 dispatchEntry.deliveryTime, consumeTime, finishTime);
6211 }
6212
6213 if (dispatchEntry.eventEntry->type == EventEntry::Type::KEY) {
Prabir Pradhanb9dd1642023-11-02 18:05:36 +00006214 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(*(dispatchEntry.eventEntry));
6215 fallbackKeyEntry =
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006216 afterKeyEventLockedInterruptable(connection, dispatchEntry, keyEntry, handled);
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006217 }
6218 } // End critical section: The -LockedInterruptable methods may have released the lock.
Prabir Pradhancef936d2021-07-21 16:17:52 +00006219
6220 // Dequeue the event and start the next cycle.
6221 // Because the lock might have been released, it is possible that the
6222 // contents of the wait queue to have been drained, so we need to double-check
6223 // a few things.
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006224 auto entryIt = std::find_if(connection->waitQueue.begin(), connection->waitQueue.end(),
6225 [seq](auto& e) { return e->seq == seq; });
6226 if (entryIt != connection->waitQueue.end()) {
6227 std::unique_ptr<DispatchEntry> dispatchEntry = std::move(*entryIt);
6228 connection->waitQueue.erase(entryIt);
6229
Prabir Pradhancef936d2021-07-21 16:17:52 +00006230 const sp<IBinder>& connectionToken = connection->inputChannel->getConnectionToken();
6231 mAnrTracker.erase(dispatchEntry->timeoutTime, connectionToken);
6232 if (!connection->responsive) {
6233 connection->responsive = isConnectionResponsive(*connection);
6234 if (connection->responsive) {
6235 // The connection was unresponsive, and now it's responsive.
6236 processConnectionResponsiveLocked(*connection);
6237 }
6238 }
6239 traceWaitQueueLength(*connection);
Prabir Pradhanb9dd1642023-11-02 18:05:36 +00006240 if (fallbackKeyEntry && connection->status == Connection::Status::NORMAL) {
6241 const InputTarget target{.inputChannel = connection->inputChannel,
6242 .flags = dispatchEntry->targetFlags};
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00006243 enqueueDispatchEntryLocked(connection, std::move(fallbackKeyEntry), target);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006244 }
Prabir Pradhanb9dd1642023-11-02 18:05:36 +00006245 releaseDispatchEntry(std::move(dispatchEntry));
Prabir Pradhancef936d2021-07-21 16:17:52 +00006246 }
6247
6248 // Start the next dispatch cycle for this connection.
6249 startDispatchCycleLocked(now(), connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006250}
6251
Prabir Pradhancef936d2021-07-21 16:17:52 +00006252void InputDispatcher::sendFocusChangedCommandLocked(const sp<IBinder>& oldToken,
6253 const sp<IBinder>& newToken) {
6254 auto command = [this, oldToken, newToken]() REQUIRES(mLock) {
6255 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00006256 mPolicy.notifyFocusChanged(oldToken, newToken);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006257 };
6258 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08006259}
6260
Prabir Pradhancef936d2021-07-21 16:17:52 +00006261void InputDispatcher::sendDropWindowCommandLocked(const sp<IBinder>& token, float x, float y) {
6262 auto command = [this, token, x, y]() REQUIRES(mLock) {
6263 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00006264 mPolicy.notifyDropWindow(token, x, y);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006265 };
6266 postCommandLocked(std::move(command));
Robert Carrf759f162018-11-13 12:57:11 -08006267}
6268
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006269void InputDispatcher::onAnrLocked(const std::shared_ptr<Connection>& connection) {
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006270 if (connection == nullptr) {
6271 LOG_ALWAYS_FATAL("Caller must check for nullness");
6272 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006273 // Since we are allowing the policy to extend the timeout, maybe the waitQueue
6274 // is already healthy again. Don't raise ANR in this situation
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006275 if (connection->waitQueue.empty()) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006276 ALOGI("Not raising ANR because the connection %s has recovered",
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006277 connection->inputChannel->getName().c_str());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006278 return;
6279 }
6280 /**
6281 * The "oldestEntry" is the entry that was first sent to the application. That entry, however,
6282 * may not be the one that caused the timeout to occur. One possibility is that window timeout
6283 * has changed. This could cause newer entries to time out before the already dispatched
6284 * entries. In that situation, the newest entries caused ANR. But in all likelihood, the app
6285 * processes the events linearly. So providing information about the oldest entry seems to be
6286 * most useful.
6287 */
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006288 DispatchEntry& oldestEntry = *connection->waitQueue.front();
6289 const nsecs_t currentWait = now() - oldestEntry.deliveryTime;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006290 std::string reason =
6291 android::base::StringPrintf("%s is not responding. Waited %" PRId64 "ms for %s",
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006292 connection->inputChannel->getName().c_str(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006293 ns2ms(currentWait),
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006294 oldestEntry.eventEntry->getDescription().c_str());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006295 sp<IBinder> connectionToken = connection->inputChannel->getConnectionToken();
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -06006296 updateLastAnrStateLocked(getWindowHandleLocked(connectionToken), reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006297
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006298 processConnectionUnresponsiveLocked(*connection, std::move(reason));
6299
6300 // Stop waking up for events on this connection, it is already unresponsive
6301 cancelEventsForAnrLocked(connection);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006302}
6303
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05006304void InputDispatcher::onAnrLocked(std::shared_ptr<InputApplicationHandle> application) {
6305 std::string reason =
6306 StringPrintf("%s does not have a focused window", application->getName().c_str());
6307 updateLastAnrStateLocked(*application, reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006308
Yabin Cui8eb9c552023-06-08 18:05:07 +00006309 auto command = [this, app = std::move(application)]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006310 scoped_unlock unlock(mLock);
Yabin Cuiced952f2023-06-09 21:12:51 +00006311 mPolicy.notifyNoFocusedWindowAnr(app);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006312 };
6313 postCommandLocked(std::move(command));
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00006314}
6315
chaviw98318de2021-05-19 16:45:23 -05006316void InputDispatcher::updateLastAnrStateLocked(const sp<WindowInfoHandle>& window,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006317 const std::string& reason) {
6318 const std::string windowLabel = getApplicationWindowLabel(nullptr, window);
6319 updateLastAnrStateLocked(windowLabel, reason);
6320}
6321
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05006322void InputDispatcher::updateLastAnrStateLocked(const InputApplicationHandle& application,
6323 const std::string& reason) {
6324 const std::string windowLabel = getApplicationWindowLabel(&application, nullptr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006325 updateLastAnrStateLocked(windowLabel, reason);
6326}
6327
6328void InputDispatcher::updateLastAnrStateLocked(const std::string& windowLabel,
6329 const std::string& reason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006330 // Capture a record of the InputDispatcher state at the time of the ANR.
Yi Kong9b14ac62018-07-17 13:48:38 -07006331 time_t t = time(nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006332 struct tm tm;
6333 localtime_r(&t, &tm);
6334 char timestr[64];
6335 strftime(timestr, sizeof(timestr), "%F %T", &tm);
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006336 mLastAnrState.clear();
6337 mLastAnrState += INDENT "ANR:\n";
6338 mLastAnrState += StringPrintf(INDENT2 "Time: %s\n", timestr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006339 mLastAnrState += StringPrintf(INDENT2 "Reason: %s\n", reason.c_str());
6340 mLastAnrState += StringPrintf(INDENT2 "Window: %s\n", windowLabel.c_str());
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006341 dumpDispatchStateLocked(mLastAnrState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006342}
6343
Prabir Pradhancef936d2021-07-21 16:17:52 +00006344void InputDispatcher::doInterceptKeyBeforeDispatchingCommand(const sp<IBinder>& focusedWindowToken,
Prabir Pradhan24047542023-11-02 17:14:59 +00006345 const KeyEntry& entry) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006346 const KeyEvent event = createKeyEvent(entry);
6347 nsecs_t delay = 0;
6348 { // release lock
6349 scoped_unlock unlock(mLock);
6350 android::base::Timer t;
Prabir Pradhana41d2442023-04-20 21:30:40 +00006351 delay = mPolicy.interceptKeyBeforeDispatching(focusedWindowToken, event, entry.policyFlags);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006352 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
6353 ALOGW("Excessive delay in interceptKeyBeforeDispatching; took %s ms",
6354 std::to_string(t.duration().count()).c_str());
6355 }
6356 } // acquire lock
Michael Wrightd02c5b62014-02-10 15:10:22 -08006357
6358 if (delay < 0) {
Michael Wright5caf55a2022-11-24 22:31:42 +00006359 entry.interceptKeyResult = KeyEntry::InterceptKeyResult::SKIP;
Prabir Pradhancef936d2021-07-21 16:17:52 +00006360 } else if (delay == 0) {
Michael Wright5caf55a2022-11-24 22:31:42 +00006361 entry.interceptKeyResult = KeyEntry::InterceptKeyResult::CONTINUE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006362 } else {
Michael Wright5caf55a2022-11-24 22:31:42 +00006363 entry.interceptKeyResult = KeyEntry::InterceptKeyResult::TRY_AGAIN_LATER;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006364 entry.interceptKeyWakeupTime = now() + delay;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006365 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006366}
6367
Prabir Pradhancef936d2021-07-21 16:17:52 +00006368void InputDispatcher::sendWindowUnresponsiveCommandLocked(const sp<IBinder>& token,
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00006369 std::optional<gui::Pid> pid,
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006370 std::string reason) {
Yabin Cui8eb9c552023-06-08 18:05:07 +00006371 auto command = [this, token, pid, r = std::move(reason)]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006372 scoped_unlock unlock(mLock);
Yabin Cuiced952f2023-06-09 21:12:51 +00006373 mPolicy.notifyWindowUnresponsive(token, pid, r);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006374 };
6375 postCommandLocked(std::move(command));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006376}
6377
Prabir Pradhanedd96402022-02-15 01:46:16 -08006378void InputDispatcher::sendWindowResponsiveCommandLocked(const sp<IBinder>& token,
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00006379 std::optional<gui::Pid> pid) {
Prabir Pradhanedd96402022-02-15 01:46:16 -08006380 auto command = [this, token, pid]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006381 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00006382 mPolicy.notifyWindowResponsive(token, pid);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006383 };
6384 postCommandLocked(std::move(command));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006385}
6386
6387/**
6388 * Tell the policy that a connection has become unresponsive so that it can start ANR.
6389 * Check whether the connection of interest is a monitor or a window, and add the corresponding
6390 * command entry to the command queue.
6391 */
6392void InputDispatcher::processConnectionUnresponsiveLocked(const Connection& connection,
6393 std::string reason) {
6394 const sp<IBinder>& connectionToken = connection.inputChannel->getConnectionToken();
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00006395 std::optional<gui::Pid> pid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006396 if (connection.monitor) {
6397 ALOGW("Monitor %s is unresponsive: %s", connection.inputChannel->getName().c_str(),
6398 reason.c_str());
Prabir Pradhanedd96402022-02-15 01:46:16 -08006399 pid = findMonitorPidByTokenLocked(connectionToken);
6400 } else {
6401 // The connection is a window
6402 ALOGW("Window %s is unresponsive: %s", connection.inputChannel->getName().c_str(),
6403 reason.c_str());
6404 const sp<WindowInfoHandle> handle = getWindowHandleLocked(connectionToken);
6405 if (handle != nullptr) {
6406 pid = handle->getInfo()->ownerPid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006407 }
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006408 }
Prabir Pradhanedd96402022-02-15 01:46:16 -08006409 sendWindowUnresponsiveCommandLocked(connectionToken, pid, std::move(reason));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006410}
6411
6412/**
6413 * Tell the policy that a connection has become responsive so that it can stop ANR.
6414 */
6415void InputDispatcher::processConnectionResponsiveLocked(const Connection& connection) {
6416 const sp<IBinder>& connectionToken = connection.inputChannel->getConnectionToken();
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00006417 std::optional<gui::Pid> pid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006418 if (connection.monitor) {
Prabir Pradhanedd96402022-02-15 01:46:16 -08006419 pid = findMonitorPidByTokenLocked(connectionToken);
6420 } else {
6421 // The connection is a window
6422 const sp<WindowInfoHandle> handle = getWindowHandleLocked(connectionToken);
6423 if (handle != nullptr) {
6424 pid = handle->getInfo()->ownerPid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006425 }
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006426 }
Prabir Pradhanedd96402022-02-15 01:46:16 -08006427 sendWindowResponsiveCommandLocked(connectionToken, pid);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006428}
6429
Prabir Pradhan24047542023-11-02 17:14:59 +00006430std::unique_ptr<const KeyEntry> InputDispatcher::afterKeyEventLockedInterruptable(
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006431 const std::shared_ptr<Connection>& connection, DispatchEntry& dispatchEntry,
Prabir Pradhanb9dd1642023-11-02 18:05:36 +00006432 const KeyEntry& keyEntry, bool handled) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006433 if (keyEntry.flags & AKEY_EVENT_FLAG_FALLBACK) {
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006434 if (!handled) {
6435 // Report the key as unhandled, since the fallback was not handled.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006436 mReporter->reportUnhandledKey(keyEntry.id);
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006437 }
Prabir Pradhanb9dd1642023-11-02 18:05:36 +00006438 return {};
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006439 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006440
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006441 // Get the fallback key state.
6442 // Clear it out after dispatching the UP.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006443 int32_t originalKeyCode = keyEntry.keyCode;
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006444 std::optional<int32_t> fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006445 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006446 connection->inputState.removeFallbackKey(originalKeyCode);
6447 }
6448
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006449 if (handled || !dispatchEntry.hasForegroundTarget()) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006450 // If the application handles the original key for which we previously
6451 // generated a fallback or if the window is not a foreground window,
6452 // then cancel the associated fallback key, if any.
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006453 if (fallbackKeyCode) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006454 // Dispatch the unhandled key to the policy with the cancel flag.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006455 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6456 ALOGD("Unhandled key event: Asking policy to cancel fallback action. "
6457 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6458 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount,
6459 keyEntry.policyFlags);
6460 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006461 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006462 event.setFlags(event.getFlags() | AKEY_EVENT_FLAG_CANCELED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006463
6464 mLock.unlock();
6465
Prabir Pradhana41d2442023-04-20 21:30:40 +00006466 if (const auto unhandledKeyFallback =
6467 mPolicy.dispatchUnhandledKey(connection->inputChannel->getConnectionToken(),
6468 event, keyEntry.policyFlags);
6469 unhandledKeyFallback) {
6470 event = *unhandledKeyFallback;
6471 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006472
6473 mLock.lock();
6474
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006475 // Cancel the fallback key.
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006476 if (*fallbackKeyCode != AKEYCODE_UNKNOWN) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00006477 CancelationOptions options(CancelationOptions::Mode::CANCEL_FALLBACK_EVENTS,
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006478 "application handled the original non-fallback key "
6479 "or is no longer a foreground target, "
6480 "canceling previously dispatched fallback key");
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006481 options.keyCode = *fallbackKeyCode;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006482 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006483 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006484 connection->inputState.removeFallbackKey(originalKeyCode);
6485 }
6486 } else {
6487 // If the application did not handle a non-fallback key, first check
6488 // that we are in a good state to perform unhandled key event processing
6489 // Then ask the policy what to do with it.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006490 bool initialDown = keyEntry.action == AKEY_EVENT_ACTION_DOWN && keyEntry.repeatCount == 0;
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006491 if (!fallbackKeyCode && !initialDown) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006492 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6493 ALOGD("Unhandled key event: Skipping unhandled key event processing "
6494 "since this is not an initial down. "
6495 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6496 originalKeyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
6497 }
Prabir Pradhanb9dd1642023-11-02 18:05:36 +00006498 return {};
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006499 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006500
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006501 // Dispatch the unhandled key to the policy.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006502 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6503 ALOGD("Unhandled key event: Asking policy to perform fallback action. "
6504 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6505 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
6506 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006507 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006508
6509 mLock.unlock();
6510
Prabir Pradhana41d2442023-04-20 21:30:40 +00006511 bool fallback = false;
6512 if (auto fb = mPolicy.dispatchUnhandledKey(connection->inputChannel->getConnectionToken(),
6513 event, keyEntry.policyFlags);
6514 fb) {
6515 fallback = true;
6516 event = *fb;
6517 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006518
6519 mLock.lock();
6520
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08006521 if (connection->status != Connection::Status::NORMAL) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006522 connection->inputState.removeFallbackKey(originalKeyCode);
Prabir Pradhanb9dd1642023-11-02 18:05:36 +00006523 return {};
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006524 }
6525
6526 // Latch the fallback keycode for this key on an initial down.
6527 // The fallback keycode cannot change at any other point in the lifecycle.
6528 if (initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006529 if (fallback) {
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006530 *fallbackKeyCode = event.getKeyCode();
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006531 } else {
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006532 *fallbackKeyCode = AKEYCODE_UNKNOWN;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006533 }
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006534 connection->inputState.setFallbackKey(originalKeyCode, *fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006535 }
6536
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006537 ALOG_ASSERT(fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006538
6539 // Cancel the fallback key if the policy decides not to send it anymore.
6540 // We will continue to dispatch the key to the policy but we will no
6541 // longer dispatch a fallback key to the application.
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006542 if (*fallbackKeyCode != AKEYCODE_UNKNOWN &&
6543 (!fallback || *fallbackKeyCode != event.getKeyCode())) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006544 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6545 if (fallback) {
6546 ALOGD("Unhandled key event: Policy requested to send key %d"
6547 "as a fallback for %d, but on the DOWN it had requested "
6548 "to send %d instead. Fallback canceled.",
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006549 event.getKeyCode(), originalKeyCode, *fallbackKeyCode);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006550 } else {
6551 ALOGD("Unhandled key event: Policy did not request fallback for %d, "
6552 "but on the DOWN it had requested to send %d. "
6553 "Fallback canceled.",
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006554 originalKeyCode, *fallbackKeyCode);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006555 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006556 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006557
Michael Wrightfb04fd52022-11-24 22:31:11 +00006558 CancelationOptions options(CancelationOptions::Mode::CANCEL_FALLBACK_EVENTS,
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006559 "canceling fallback, policy no longer desires it");
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006560 options.keyCode = *fallbackKeyCode;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006561 synthesizeCancelationEventsForConnectionLocked(connection, options);
6562
6563 fallback = false;
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006564 *fallbackKeyCode = AKEYCODE_UNKNOWN;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006565 if (keyEntry.action != AKEY_EVENT_ACTION_UP) {
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006566 connection->inputState.setFallbackKey(originalKeyCode, *fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006567 }
6568 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006569
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006570 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6571 {
6572 std::string msg;
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006573 const std::map<int32_t, int32_t>& fallbackKeys =
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006574 connection->inputState.getFallbackKeys();
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006575 for (const auto& [key, value] : fallbackKeys) {
6576 msg += StringPrintf(", %d->%d", key, value);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006577 }
6578 ALOGD("Unhandled key event: %zu currently tracked fallback keys%s.",
6579 fallbackKeys.size(), msg.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006580 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006581 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006582
6583 if (fallback) {
Prabir Pradhanb9dd1642023-11-02 18:05:36 +00006584 // Return the fallback key that we want dispatched to the channel.
6585 std::unique_ptr<KeyEntry> newEntry =
6586 std::make_unique<KeyEntry>(mIdGenerator.nextId(), keyEntry.injectionState,
6587 event.getEventTime(), event.getDeviceId(),
6588 event.getSource(), event.getDisplayId(),
6589 keyEntry.policyFlags, keyEntry.action,
6590 event.getFlags() | AKEY_EVENT_FLAG_FALLBACK,
6591 *fallbackKeyCode, event.getScanCode(),
6592 event.getMetaState(), event.getRepeatCount(),
6593 event.getDownTime());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006594 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6595 ALOGD("Unhandled key event: Dispatching fallback key. "
6596 "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006597 originalKeyCode, *fallbackKeyCode, keyEntry.metaState);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006598 }
Prabir Pradhanb9dd1642023-11-02 18:05:36 +00006599 return newEntry;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006600 } else {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006601 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6602 ALOGD("Unhandled key event: No fallback key.");
6603 }
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006604
6605 // Report the key as unhandled, since there is no fallback key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006606 mReporter->reportUnhandledKey(keyEntry.id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006607 }
6608 }
Prabir Pradhanb9dd1642023-11-02 18:05:36 +00006609 return {};
Michael Wrightd02c5b62014-02-10 15:10:22 -08006610}
6611
Michael Wrightd02c5b62014-02-10 15:10:22 -08006612void InputDispatcher::traceInboundQueueLengthLocked() {
6613 if (ATRACE_ENABLED()) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07006614 ATRACE_INT("iq", mInboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006615 }
6616}
6617
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006618void InputDispatcher::traceOutboundQueueLength(const Connection& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006619 if (ATRACE_ENABLED()) {
6620 char counterName[40];
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006621 snprintf(counterName, sizeof(counterName), "oq:%s", connection.getWindowName().c_str());
6622 ATRACE_INT(counterName, connection.outboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006623 }
6624}
6625
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006626void InputDispatcher::traceWaitQueueLength(const Connection& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006627 if (ATRACE_ENABLED()) {
6628 char counterName[40];
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006629 snprintf(counterName, sizeof(counterName), "wq:%s", connection.getWindowName().c_str());
6630 ATRACE_INT(counterName, connection.waitQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006631 }
6632}
6633
Siarhei Vishniakou5e20f272023-06-08 17:24:44 -07006634void InputDispatcher::dump(std::string& dump) const {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006635 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006636
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006637 dump += "Input Dispatcher State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08006638 dumpDispatchStateLocked(dump);
6639
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006640 if (!mLastAnrState.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006641 dump += "\nInput Dispatcher State at time of last ANR:\n";
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006642 dump += mLastAnrState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006643 }
6644}
6645
6646void InputDispatcher::monitor() {
6647 // Acquire and release the lock to ensure that the dispatcher has not deadlocked.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006648 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006649 mLooper->wake();
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006650 mDispatcherIsAlive.wait(_l);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006651}
6652
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08006653/**
6654 * Wake up the dispatcher and wait until it processes all events and commands.
6655 * The notification of mDispatcherEnteredIdle is guaranteed to happen after wake(), so
6656 * this method can be safely called from any thread, as long as you've ensured that
6657 * the work you are interested in completing has already been queued.
6658 */
Siarhei Vishniakoua66d65e2023-06-16 10:32:51 -07006659bool InputDispatcher::waitForIdle() const {
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08006660 /**
6661 * Timeout should represent the longest possible time that a device might spend processing
6662 * events and commands.
6663 */
6664 constexpr std::chrono::duration TIMEOUT = 100ms;
6665 std::unique_lock lock(mLock);
6666 mLooper->wake();
6667 std::cv_status result = mDispatcherEnteredIdle.wait_for(lock, TIMEOUT);
6668 return result == std::cv_status::no_timeout;
6669}
6670
Vishnu Naire798b472020-07-23 13:52:21 -07006671/**
6672 * Sets focus to the window identified by the token. This must be called
6673 * after updating any input window handles.
6674 *
6675 * Params:
6676 * request.token - input channel token used to identify the window that should gain focus.
6677 * request.focusedToken - the token that the caller expects currently to be focused. If the
6678 * specified token does not match the currently focused window, this request will be dropped.
6679 * If the specified focused token matches the currently focused window, the call will succeed.
6680 * Set this to "null" if this call should succeed no matter what the currently focused token is.
6681 * request.timestamp - SYSTEM_TIME_MONOTONIC timestamp in nanos set by the client (wm)
6682 * when requesting the focus change. This determines which request gets
6683 * precedence if there is a focus change request from another source such as pointer down.
6684 */
Vishnu Nair958da932020-08-21 17:12:37 -07006685void InputDispatcher::setFocusedWindow(const FocusRequest& request) {
6686 { // acquire lock
6687 std::scoped_lock _l(mLock);
Vishnu Nairc519ff72021-01-21 08:23:08 -08006688 std::optional<FocusResolver::FocusChanges> changes =
6689 mFocusResolver.setFocusedWindow(request, getWindowHandlesLocked(request.displayId));
6690 if (changes) {
6691 onFocusChangedLocked(*changes);
Vishnu Nair958da932020-08-21 17:12:37 -07006692 }
6693 } // release lock
6694 // Wake up poll loop since it may need to make new input dispatching choices.
6695 mLooper->wake();
6696}
6697
Vishnu Nairc519ff72021-01-21 08:23:08 -08006698void InputDispatcher::onFocusChangedLocked(const FocusResolver::FocusChanges& changes) {
6699 if (changes.oldFocus) {
6700 std::shared_ptr<InputChannel> focusedInputChannel = getInputChannelLocked(changes.oldFocus);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006701 if (focusedInputChannel) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00006702 CancelationOptions options(CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS,
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006703 "focus left window");
6704 synthesizeCancelationEventsForInputChannelLocked(focusedInputChannel, options);
Harry Cutts33476232023-01-30 19:57:29 +00006705 enqueueFocusEventLocked(changes.oldFocus, /*hasFocus=*/false, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006706 }
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006707 }
Vishnu Nairc519ff72021-01-21 08:23:08 -08006708 if (changes.newFocus) {
Siarhei Vishniakouc033dfb2023-10-03 10:45:16 -07006709 resetNoFocusedWindowTimeoutLocked();
Harry Cutts33476232023-01-30 19:57:29 +00006710 enqueueFocusEventLocked(changes.newFocus, /*hasFocus=*/true, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006711 }
6712
Prabir Pradhan99987712020-11-10 18:43:05 -08006713 // If a window has pointer capture, then it must have focus. We need to ensure that this
6714 // contract is upheld when pointer capture is being disabled due to a loss of window focus.
6715 // If the window loses focus before it loses pointer capture, then the window can be in a state
6716 // where it has pointer capture but not focus, violating the contract. Therefore we must
6717 // dispatch the pointer capture event before the focus event. Since focus events are added to
6718 // the front of the queue (above), we add the pointer capture event to the front of the queue
6719 // after the focus events are added. This ensures the pointer capture event ends up at the
6720 // front.
6721 disablePointerCaptureForcedLocked();
6722
Vishnu Nairc519ff72021-01-21 08:23:08 -08006723 if (mFocusedDisplayId == changes.displayId) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006724 sendFocusChangedCommandLocked(changes.oldFocus, changes.newFocus);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006725 }
6726}
Vishnu Nair958da932020-08-21 17:12:37 -07006727
Prabir Pradhan99987712020-11-10 18:43:05 -08006728void InputDispatcher::disablePointerCaptureForcedLocked() {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006729 if (!mCurrentPointerCaptureRequest.enable && !mWindowTokenWithPointerCapture) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006730 return;
6731 }
6732
6733 ALOGD_IF(DEBUG_FOCUS, "Disabling Pointer Capture because the window lost focus.");
6734
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006735 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006736 setPointerCaptureLocked(false);
6737 }
6738
6739 if (!mWindowTokenWithPointerCapture) {
6740 // No need to send capture changes because no window has capture.
6741 return;
6742 }
6743
6744 if (mPendingEvent != nullptr) {
6745 // Move the pending event to the front of the queue. This will give the chance
6746 // for the pending event to be dropped if it is a captured event.
6747 mInboundQueue.push_front(mPendingEvent);
6748 mPendingEvent = nullptr;
6749 }
6750
6751 auto entry = std::make_unique<PointerCaptureChangedEntry>(mIdGenerator.nextId(), now(),
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006752 mCurrentPointerCaptureRequest);
Prabir Pradhan99987712020-11-10 18:43:05 -08006753 mInboundQueue.push_front(std::move(entry));
6754}
6755
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006756void InputDispatcher::setPointerCaptureLocked(bool enable) {
6757 mCurrentPointerCaptureRequest.enable = enable;
6758 mCurrentPointerCaptureRequest.seq++;
6759 auto command = [this, request = mCurrentPointerCaptureRequest]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006760 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00006761 mPolicy.setPointerCapture(request);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006762 };
6763 postCommandLocked(std::move(command));
Prabir Pradhan99987712020-11-10 18:43:05 -08006764}
6765
Vishnu Nair599f1412021-06-21 10:39:58 -07006766void InputDispatcher::displayRemoved(int32_t displayId) {
6767 { // acquire lock
6768 std::scoped_lock _l(mLock);
6769 // Set an empty list to remove all handles from the specific display.
Harry Cutts101ee9b2023-07-06 18:04:14 +00006770 setInputWindowsLocked(/*windowInfoHandles=*/{}, displayId);
Vishnu Nair599f1412021-06-21 10:39:58 -07006771 setFocusedApplicationLocked(displayId, nullptr);
6772 // Call focus resolver to clean up stale requests. This must be called after input windows
6773 // have been removed for the removed display.
6774 mFocusResolver.displayRemoved(displayId);
Christine Franksb768bb42021-11-29 12:11:31 -08006775 // Reset pointer capture eligibility, regardless of previous state.
6776 std::erase(mIneligibleDisplaysForPointerCapture, displayId);
Antonio Kantek15beb512022-06-13 22:35:41 +00006777 // Remove the associated touch mode state.
6778 mTouchModePerDisplay.erase(displayId);
Siarhei Vishniakou5c02a712023-05-15 15:45:02 -07006779 mVerifiersByDisplay.erase(displayId);
Vishnu Nair599f1412021-06-21 10:39:58 -07006780 } // release lock
6781
6782 // Wake up poll loop since it may need to make new input dispatching choices.
6783 mLooper->wake();
6784}
6785
Patrick Williamsd828f302023-04-28 17:52:08 -05006786void InputDispatcher::onWindowInfosChanged(const gui::WindowInfosUpdate& update) {
Siarhei Vishniakouaeed0da2024-01-09 08:57:13 -08006787 if (auto result = validateWindowInfosUpdate(update); !result.ok()) {
6788 {
6789 // acquire lock
6790 std::scoped_lock _l(mLock);
6791 logDispatchStateLocked();
6792 }
6793 LOG_ALWAYS_FATAL("Incorrect WindowInfosUpdate provided: %s",
6794 result.error().message().c_str());
6795 };
chaviw15fab6f2021-06-07 14:15:52 -05006796 // The listener sends the windows as a flattened array. Separate the windows by display for
6797 // more convenient parsing.
6798 std::unordered_map<int32_t, std::vector<sp<WindowInfoHandle>>> handlesPerDisplay;
Patrick Williamsd828f302023-04-28 17:52:08 -05006799 for (const auto& info : update.windowInfos) {
chaviw15fab6f2021-06-07 14:15:52 -05006800 handlesPerDisplay.emplace(info.displayId, std::vector<sp<WindowInfoHandle>>());
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07006801 handlesPerDisplay[info.displayId].push_back(sp<WindowInfoHandle>::make(info));
chaviw15fab6f2021-06-07 14:15:52 -05006802 }
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006803
6804 { // acquire lock
6805 std::scoped_lock _l(mLock);
Prabir Pradhan814fe082022-07-22 20:22:18 +00006806
6807 // Ensure that we have an entry created for all existing displays so that if a displayId has
6808 // no windows, we can tell that the windows were removed from the display.
6809 for (const auto& [displayId, _] : mWindowHandlesByDisplay) {
6810 handlesPerDisplay[displayId];
6811 }
6812
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006813 mDisplayInfos.clear();
Patrick Williamsd828f302023-04-28 17:52:08 -05006814 for (const auto& displayInfo : update.displayInfos) {
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006815 mDisplayInfos.emplace(displayInfo.displayId, displayInfo);
6816 }
6817
6818 for (const auto& [displayId, handles] : handlesPerDisplay) {
6819 setInputWindowsLocked(handles, displayId);
6820 }
Patrick Williams9464b2c2023-05-23 11:22:04 -05006821
6822 if (update.vsyncId < mWindowInfosVsyncId) {
6823 ALOGE("Received out of order window infos update. Last update vsync id: %" PRId64
6824 ", current update vsync id: %" PRId64,
6825 mWindowInfosVsyncId, update.vsyncId);
6826 }
6827 mWindowInfosVsyncId = update.vsyncId;
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006828 }
6829 // Wake up poll loop since it may need to make new input dispatching choices.
6830 mLooper->wake();
chaviw15fab6f2021-06-07 14:15:52 -05006831}
6832
Vishnu Nair062a8672021-09-03 16:07:44 -07006833bool InputDispatcher::shouldDropInput(
6834 const EventEntry& entry, const sp<android::gui::WindowInfoHandle>& windowHandle) const {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006835 if (windowHandle->getInfo()->inputConfig.test(WindowInfo::InputConfig::DROP_INPUT) ||
6836 (windowHandle->getInfo()->inputConfig.test(
6837 WindowInfo::InputConfig::DROP_INPUT_IF_OBSCURED) &&
Vishnu Nair062a8672021-09-03 16:07:44 -07006838 isWindowObscuredLocked(windowHandle))) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006839 ALOGW("Dropping %s event targeting %s as requested by the input configuration {%s} on "
6840 "display %" PRId32 ".",
Vishnu Nair062a8672021-09-03 16:07:44 -07006841 ftl::enum_string(entry.type).c_str(), windowHandle->getName().c_str(),
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006842 windowHandle->getInfo()->inputConfig.string().c_str(),
Vishnu Nair062a8672021-09-03 16:07:44 -07006843 windowHandle->getInfo()->displayId);
6844 return true;
6845 }
6846 return false;
6847}
6848
Siarhei Vishniakou18050092021-09-01 13:32:49 -07006849void InputDispatcher::DispatcherWindowListener::onWindowInfosChanged(
Patrick Williamsd828f302023-04-28 17:52:08 -05006850 const gui::WindowInfosUpdate& update) {
6851 mDispatcher.onWindowInfosChanged(update);
Siarhei Vishniakou18050092021-09-01 13:32:49 -07006852}
6853
Arthur Hungdfd528e2021-12-08 13:23:04 +00006854void InputDispatcher::cancelCurrentTouch() {
6855 {
6856 std::scoped_lock _l(mLock);
6857 ALOGD("Canceling all ongoing pointer gestures on all displays.");
Michael Wrightfb04fd52022-11-24 22:31:11 +00006858 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
Arthur Hungdfd528e2021-12-08 13:23:04 +00006859 "cancel current touch");
6860 synthesizeCancelationEventsForAllConnectionsLocked(options);
6861
6862 mTouchStatesByDisplay.clear();
Arthur Hungdfd528e2021-12-08 13:23:04 +00006863 }
6864 // Wake up poll loop since there might be work to do.
6865 mLooper->wake();
6866}
6867
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006868void InputDispatcher::setMonitorDispatchingTimeoutForTest(std::chrono::nanoseconds timeout) {
6869 std::scoped_lock _l(mLock);
6870 mMonitorDispatchingTimeout = timeout;
6871}
6872
Arthur Hungc539dbb2022-12-08 07:45:36 +00006873void InputDispatcher::slipWallpaperTouch(ftl::Flags<InputTarget::Flags> targetFlags,
6874 const sp<WindowInfoHandle>& oldWindowHandle,
6875 const sp<WindowInfoHandle>& newWindowHandle,
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08006876 TouchState& state, int32_t deviceId,
6877 const PointerProperties& pointerProperties,
Siarhei Vishniakoubf880522023-05-01 11:03:22 -07006878 std::vector<InputTarget>& targets) const {
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08006879 std::vector<PointerProperties> pointers{pointerProperties};
Arthur Hungc539dbb2022-12-08 07:45:36 +00006880 const bool oldHasWallpaper = oldWindowHandle->getInfo()->inputConfig.test(
6881 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
6882 const bool newHasWallpaper = targetFlags.test(InputTarget::Flags::FOREGROUND) &&
6883 newWindowHandle->getInfo()->inputConfig.test(
6884 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
6885 const sp<WindowInfoHandle> oldWallpaper =
6886 oldHasWallpaper ? state.getWallpaperWindow() : nullptr;
6887 const sp<WindowInfoHandle> newWallpaper =
6888 newHasWallpaper ? findWallpaperWindowBelow(newWindowHandle) : nullptr;
6889 if (oldWallpaper == newWallpaper) {
6890 return;
6891 }
6892
6893 if (oldWallpaper != nullptr) {
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08006894 const TouchedWindow& oldTouchedWindow = state.getTouchedWindow(oldWallpaper);
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00006895 addPointerWindowTargetLocked(oldWallpaper, InputTarget::DispatchMode::SLIPPERY_EXIT,
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08006896 oldTouchedWindow.targetFlags, getPointerIds(pointers),
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00006897 oldTouchedWindow.getDownTimeInTarget(deviceId), targets);
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08006898 state.removeTouchingPointerFromWindow(deviceId, pointerProperties.id, oldWallpaper);
Arthur Hungc539dbb2022-12-08 07:45:36 +00006899 }
6900
6901 if (newWallpaper != nullptr) {
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00006902 state.addOrUpdateWindow(newWallpaper, InputTarget::DispatchMode::SLIPPERY_ENTER,
6903 InputTarget::Flags::WINDOW_IS_OBSCURED |
Arthur Hungc539dbb2022-12-08 07:45:36 +00006904 InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED,
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08006905 deviceId, pointers);
Arthur Hungc539dbb2022-12-08 07:45:36 +00006906 }
6907}
6908
6909void InputDispatcher::transferWallpaperTouch(ftl::Flags<InputTarget::Flags> oldTargetFlags,
6910 ftl::Flags<InputTarget::Flags> newTargetFlags,
6911 const sp<WindowInfoHandle> fromWindowHandle,
6912 const sp<WindowInfoHandle> toWindowHandle,
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07006913 TouchState& state, int32_t deviceId,
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08006914 const std::vector<PointerProperties>& pointers) {
Arthur Hungc539dbb2022-12-08 07:45:36 +00006915 const bool oldHasWallpaper = oldTargetFlags.test(InputTarget::Flags::FOREGROUND) &&
6916 fromWindowHandle->getInfo()->inputConfig.test(
6917 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
6918 const bool newHasWallpaper = newTargetFlags.test(InputTarget::Flags::FOREGROUND) &&
6919 toWindowHandle->getInfo()->inputConfig.test(
6920 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
6921
6922 const sp<WindowInfoHandle> oldWallpaper =
6923 oldHasWallpaper ? state.getWallpaperWindow() : nullptr;
6924 const sp<WindowInfoHandle> newWallpaper =
6925 newHasWallpaper ? findWallpaperWindowBelow(toWindowHandle) : nullptr;
6926 if (oldWallpaper == newWallpaper) {
6927 return;
6928 }
6929
6930 if (oldWallpaper != nullptr) {
6931 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
6932 "transferring touch focus to another window");
6933 state.removeWindowByToken(oldWallpaper->getToken());
6934 synthesizeCancelationEventsForWindowLocked(oldWallpaper, options);
6935 }
6936
6937 if (newWallpaper != nullptr) {
6938 nsecs_t downTimeInTarget = now();
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00006939 ftl::Flags<InputTarget::Flags> wallpaperFlags = oldTargetFlags & InputTarget::Flags::SPLIT;
Arthur Hungc539dbb2022-12-08 07:45:36 +00006940 wallpaperFlags |= InputTarget::Flags::WINDOW_IS_OBSCURED |
6941 InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED;
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00006942 state.addOrUpdateWindow(newWallpaper, InputTarget::DispatchMode::AS_IS, wallpaperFlags,
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08006943 deviceId, pointers, downTimeInTarget);
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006944 std::shared_ptr<Connection> wallpaperConnection =
6945 getConnectionLocked(newWallpaper->getToken());
Arthur Hungc539dbb2022-12-08 07:45:36 +00006946 if (wallpaperConnection != nullptr) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006947 std::shared_ptr<Connection> toConnection =
6948 getConnectionLocked(toWindowHandle->getToken());
Arthur Hungc539dbb2022-12-08 07:45:36 +00006949 toConnection->inputState.mergePointerStateTo(wallpaperConnection->inputState);
6950 synthesizePointerDownEventsForConnectionLocked(downTimeInTarget, wallpaperConnection,
6951 wallpaperFlags);
6952 }
6953 }
6954}
6955
6956sp<WindowInfoHandle> InputDispatcher::findWallpaperWindowBelow(
6957 const sp<WindowInfoHandle>& windowHandle) const {
6958 const std::vector<sp<WindowInfoHandle>>& windowHandles =
6959 getWindowHandlesLocked(windowHandle->getInfo()->displayId);
6960 bool foundWindow = false;
6961 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
6962 if (!foundWindow && otherHandle != windowHandle) {
6963 continue;
6964 }
6965 if (windowHandle == otherHandle) {
6966 foundWindow = true;
6967 continue;
6968 }
6969
6970 if (otherHandle->getInfo()->inputConfig.test(WindowInfo::InputConfig::IS_WALLPAPER)) {
6971 return otherHandle;
6972 }
6973 }
6974 return nullptr;
6975}
6976
Siarhei Vishniakoufa2a0492023-11-14 13:13:18 -08006977void InputDispatcher::setKeyRepeatConfiguration(std::chrono::nanoseconds timeout,
6978 std::chrono::nanoseconds delay) {
Nergi Rahardi730cf3c2023-04-13 12:41:17 +09006979 std::scoped_lock _l(mLock);
6980
Siarhei Vishniakoufa2a0492023-11-14 13:13:18 -08006981 mConfig.keyRepeatTimeout = timeout.count();
6982 mConfig.keyRepeatDelay = delay.count();
Nergi Rahardi730cf3c2023-04-13 12:41:17 +09006983}
6984
Prabir Pradhan64f21d22023-11-28 21:19:42 +00006985bool InputDispatcher::isPointerInWindow(const sp<android::IBinder>& token, int32_t displayId,
6986 DeviceId deviceId, int32_t pointerId) {
6987 std::scoped_lock _l(mLock);
6988 auto touchStateIt = mTouchStatesByDisplay.find(displayId);
6989 if (touchStateIt == mTouchStatesByDisplay.end()) {
6990 return false;
6991 }
6992 for (const TouchedWindow& window : touchStateIt->second.windows) {
6993 if (window.windowHandle->getToken() == token &&
6994 (window.hasTouchingPointer(deviceId, pointerId) ||
6995 window.hasHoveringPointer(deviceId, pointerId))) {
6996 return true;
6997 }
6998 }
6999 return false;
7000}
7001
Garfield Tane84e6f92019-08-29 17:28:41 -07007002} // namespace android::inputdispatcher