blob: d50e2b8bcb19a7a06b7eac5599e8b44129945670 [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");
Linnan Lid8150952024-01-26 18:07:17 +00001964 options.displayId = entry->displayId;
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001965 synthesizeCancelationEventsForMonitorsLocked(options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001966 return true;
1967 }
1968
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001969 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001970 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001971
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00001972 if (mTracer) {
1973 ensureEventTraced(*entry);
1974 for (const auto& target : inputTargets) {
1975 mTracer->dispatchToTargetHint(*entry->traceTracker, target);
1976 }
1977 }
1978
Michael Wrightd02c5b62014-02-10 15:10:22 -08001979 // Dispatch the motion.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001980 dispatchEventLocked(currentTime, entry, inputTargets);
1981 return true;
1982}
1983
chaviw98318de2021-05-19 16:45:23 -05001984void InputDispatcher::enqueueDragEventLocked(const sp<WindowInfoHandle>& windowHandle,
Arthur Hung54745652022-04-20 07:17:41 +00001985 bool isExiting, const int32_t rawX,
1986 const int32_t rawY) {
1987 const vec2 xy = windowHandle->getInfo()->transform.transform(vec2(rawX, rawY));
arthurhungb89ccb02020-12-30 16:19:01 +08001988 std::unique_ptr<DragEntry> dragEntry =
Arthur Hung54745652022-04-20 07:17:41 +00001989 std::make_unique<DragEntry>(mIdGenerator.nextId(), now(), windowHandle->getToken(),
1990 isExiting, xy.x, xy.y);
arthurhungb89ccb02020-12-30 16:19:01 +08001991
1992 enqueueInboundEventLocked(std::move(dragEntry));
1993}
1994
Prabir Pradhan24047542023-11-02 17:14:59 +00001995void InputDispatcher::dispatchDragLocked(nsecs_t currentTime,
1996 std::shared_ptr<const DragEntry> entry) {
arthurhungb89ccb02020-12-30 16:19:01 +08001997 std::shared_ptr<InputChannel> channel = getInputChannelLocked(entry->connectionToken);
1998 if (channel == nullptr) {
1999 return; // Window has gone away
2000 }
2001 InputTarget target;
2002 target.inputChannel = channel;
arthurhungb89ccb02020-12-30 16:19:01 +08002003 entry->dispatchInProgress = true;
2004 dispatchEventLocked(currentTime, entry, {target});
2005}
2006
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002007void InputDispatcher::logOutboundMotionDetails(const char* prefix, const MotionEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002008 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -08002009 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=%s, displayId=%" PRId32
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002010 ", policyFlags=0x%x, "
Siarhei Vishniakouca205502021-07-16 21:31:58 +00002011 "action=%s, actionButton=0x%x, flags=0x%x, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002012 "metaState=0x%x, buttonState=0x%x,"
2013 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%" PRId64,
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -08002014 prefix, entry.eventTime, entry.deviceId,
2015 inputEventSourceToString(entry.source).c_str(), entry.displayId, entry.policyFlags,
2016 MotionEvent::actionToString(entry.action).c_str(), entry.actionButton, entry.flags,
2017 entry.metaState, entry.buttonState, entry.edgeFlags, entry.xPrecision,
2018 entry.yPrecision, entry.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002019
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07002020 for (uint32_t i = 0; i < entry.getPointerCount(); i++) {
Siarhei Vishniakou09a8fe42022-07-21 17:27:03 -07002021 ALOGD(" Pointer %d: id=%d, toolType=%s, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002022 "x=%f, y=%f, pressure=%f, size=%f, "
2023 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
2024 "orientation=%f",
Siarhei Vishniakou09a8fe42022-07-21 17:27:03 -07002025 i, entry.pointerProperties[i].id,
2026 ftl::enum_string(entry.pointerProperties[i].toolType).c_str(),
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002027 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
2028 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
2029 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
2030 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
2031 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
2032 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
2033 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
2034 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
2035 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
2036 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002037 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002038}
2039
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002040void InputDispatcher::dispatchEventLocked(nsecs_t currentTime,
Prabir Pradhan24047542023-11-02 17:14:59 +00002041 std::shared_ptr<const EventEntry> eventEntry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002042 const std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002043 ATRACE_CALL();
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002044 if (DEBUG_DISPATCH_CYCLE) {
2045 ALOGD("dispatchEventToCurrentInputTargets");
2046 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002047
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00002048 processInteractionsLocked(*eventEntry, inputTargets);
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00002049
Michael Wrightd02c5b62014-02-10 15:10:22 -08002050 ALOG_ASSERT(eventEntry->dispatchInProgress); // should already have been set to true
2051
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002052 pokeUserActivityLocked(*eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002053
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002054 for (const InputTarget& inputTarget : inputTargets) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07002055 std::shared_ptr<Connection> connection =
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07002056 getConnectionLocked(inputTarget.inputChannel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07002057 if (connection != nullptr) {
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002058 prepareDispatchCycleLocked(currentTime, connection, eventEntry, inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002059 } else {
Siarhei Vishniakou31dd1552023-10-30 18:46:10 -07002060 if (DEBUG_DROPPED_EVENTS_VERBOSE) {
2061 LOG(INFO) << "Dropping event delivery to target with channel "
2062 << inputTarget.inputChannel->getName()
2063 << " because it is no longer registered with the input dispatcher.";
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002064 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002065 }
2066 }
2067}
2068
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07002069void InputDispatcher::cancelEventsForAnrLocked(const std::shared_ptr<Connection>& connection) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002070 // We will not be breaking any connections here, even if the policy wants us to abort dispatch.
2071 // If the policy decides to close the app, we will get a channel removal event via
2072 // unregisterInputChannel, and will clean up the connection that way. We are already not
2073 // sending new pointers to the connection when it blocked, but focused events will continue to
2074 // pile up.
2075 ALOGW("Canceling events for %s because it is unresponsive",
2076 connection->inputChannel->getName().c_str());
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08002077 if (connection->status == Connection::Status::NORMAL) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00002078 CancelationOptions options(CancelationOptions::Mode::CANCEL_ALL_EVENTS,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002079 "application not responding");
2080 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002081 }
2082}
2083
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002084void InputDispatcher::resetNoFocusedWindowTimeoutLocked() {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002085 if (DEBUG_FOCUS) {
2086 ALOGD("Resetting ANR timeouts.");
2087 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002088
2089 // Reset input target wait timeout.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002090 mNoFocusedWindowTimeoutTime = std::nullopt;
Chris Yea209fde2020-07-22 13:54:51 -07002091 mAwaitedFocusedApplication.reset();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002092}
2093
Tiger Huang721e26f2018-07-24 22:26:19 +08002094/**
2095 * Get the display id that the given event should go to. If this event specifies a valid display id,
2096 * then it should be dispatched to that display. Otherwise, the event goes to the focused display.
2097 * Focused display is the display that the user most recently interacted with.
2098 */
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002099int32_t InputDispatcher::getTargetDisplayId(const EventEntry& entry) {
Tiger Huang721e26f2018-07-24 22:26:19 +08002100 int32_t displayId;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002101 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002102 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002103 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
2104 displayId = keyEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002105 break;
2106 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002107 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002108 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
2109 displayId = motionEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002110 break;
2111 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00002112 case EventEntry::Type::TOUCH_MODE_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08002113 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002114 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002115 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07002116 case EventEntry::Type::DEVICE_RESET:
arthurhungb89ccb02020-12-30 16:19:01 +08002117 case EventEntry::Type::SENSOR:
2118 case EventEntry::Type::DRAG: {
Dominik Laskowski75788452021-02-09 18:51:25 -08002119 ALOGE("%s events do not have a target display", ftl::enum_string(entry.type).c_str());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002120 return ADISPLAY_ID_NONE;
2121 }
Tiger Huang721e26f2018-07-24 22:26:19 +08002122 }
2123 return displayId == ADISPLAY_ID_NONE ? mFocusedDisplayId : displayId;
2124}
2125
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002126bool InputDispatcher::shouldWaitToSendKeyLocked(nsecs_t currentTime,
2127 const char* focusedWindowName) {
2128 if (mAnrTracker.empty()) {
2129 // already processed all events that we waited for
2130 mKeyIsWaitingForEventsTimeout = std::nullopt;
2131 return false;
2132 }
2133
2134 if (!mKeyIsWaitingForEventsTimeout.has_value()) {
2135 // Start the timer
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00002136 // Wait to send key because there are unprocessed events that may cause focus to change
Siarhei Vishniakou70622952020-07-30 11:17:23 -05002137 mKeyIsWaitingForEventsTimeout = currentTime +
2138 std::chrono::duration_cast<std::chrono::nanoseconds>(KEY_WAITING_FOR_EVENTS_TIMEOUT)
2139 .count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002140 return true;
2141 }
2142
2143 // We still have pending events, and already started the timer
2144 if (currentTime < *mKeyIsWaitingForEventsTimeout) {
2145 return true; // Still waiting
2146 }
2147
2148 // Waited too long, and some connection still hasn't processed all motions
2149 // Just send the key to the focused window
2150 ALOGW("Dispatching key to %s even though there are other unprocessed events",
2151 focusedWindowName);
2152 mKeyIsWaitingForEventsTimeout = std::nullopt;
2153 return false;
2154}
2155
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002156sp<WindowInfoHandle> InputDispatcher::findFocusedWindowTargetLocked(
Siarhei Vishniakou69505962023-12-28 12:07:04 -08002157 nsecs_t currentTime, const EventEntry& entry, nsecs_t& nextWakeupTime,
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002158 InputEventInjectionResult& outInjectionResult) {
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002159 outInjectionResult = InputEventInjectionResult::FAILED; // Default result
Michael Wrightd02c5b62014-02-10 15:10:22 -08002160
Tiger Huang721e26f2018-07-24 22:26:19 +08002161 int32_t displayId = getTargetDisplayId(entry);
chaviw98318de2021-05-19 16:45:23 -05002162 sp<WindowInfoHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Chris Yea209fde2020-07-22 13:54:51 -07002163 std::shared_ptr<InputApplicationHandle> focusedApplicationHandle =
Tiger Huang721e26f2018-07-24 22:26:19 +08002164 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
2165
Michael Wrightd02c5b62014-02-10 15:10:22 -08002166 // If there is no currently focused window and no focused application
2167 // then drop the event.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002168 if (focusedWindowHandle == nullptr && focusedApplicationHandle == nullptr) {
2169 ALOGI("Dropping %s event because there is no focused window or focused application in "
2170 "display %" PRId32 ".",
Dominik Laskowski75788452021-02-09 18:51:25 -08002171 ftl::enum_string(entry.type).c_str(), displayId);
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002172 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002173 }
2174
Vishnu Nair062a8672021-09-03 16:07:44 -07002175 // Drop key events if requested by input feature
2176 if (focusedWindowHandle != nullptr && shouldDropInput(entry, focusedWindowHandle)) {
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002177 return nullptr;
Vishnu Nair062a8672021-09-03 16:07:44 -07002178 }
2179
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002180 // Compatibility behavior: raise ANR if there is a focused application, but no focused window.
2181 // Only start counting when we have a focused event to dispatch. The ANR is canceled if we
2182 // start interacting with another application via touch (app switch). This code can be removed
2183 // if the "no focused window ANR" is moved to the policy. Input doesn't know whether
2184 // an app is expected to have a focused window.
2185 if (focusedWindowHandle == nullptr && focusedApplicationHandle != nullptr) {
2186 if (!mNoFocusedWindowTimeoutTime.has_value()) {
2187 // We just discovered that there's no focused window. Start the ANR timer
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05002188 std::chrono::nanoseconds timeout = focusedApplicationHandle->getDispatchingTimeout(
2189 DEFAULT_INPUT_DISPATCHING_TIMEOUT);
2190 mNoFocusedWindowTimeoutTime = currentTime + timeout.count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002191 mAwaitedFocusedApplication = focusedApplicationHandle;
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05002192 mAwaitedApplicationDisplayId = displayId;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002193 ALOGW("Waiting because no window has focus but %s may eventually add a "
2194 "window when it finishes starting up. Will wait for %" PRId64 "ms",
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05002195 mAwaitedFocusedApplication->getName().c_str(), millis(timeout));
Siarhei Vishniakou69505962023-12-28 12:07:04 -08002196 nextWakeupTime = std::min(nextWakeupTime, *mNoFocusedWindowTimeoutTime);
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002197 outInjectionResult = InputEventInjectionResult::PENDING;
2198 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002199 } else if (currentTime > *mNoFocusedWindowTimeoutTime) {
2200 // Already raised ANR. Drop the event
2201 ALOGE("Dropping %s event because there is no focused window",
Dominik Laskowski75788452021-02-09 18:51:25 -08002202 ftl::enum_string(entry.type).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002203 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002204 } else {
2205 // Still waiting for the focused window
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002206 outInjectionResult = InputEventInjectionResult::PENDING;
2207 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002208 }
2209 }
2210
2211 // we have a valid, non-null focused window
2212 resetNoFocusedWindowTimeoutLocked();
2213
Prabir Pradhan5735a322022-04-11 17:23:34 +00002214 // Verify targeted injection.
2215 if (const auto err = verifyTargetedInjection(focusedWindowHandle, entry); err) {
2216 ALOGW("Dropping injected event: %s", (*err).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002217 outInjectionResult = InputEventInjectionResult::TARGET_MISMATCH;
2218 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002219 }
2220
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002221 if (focusedWindowHandle->getInfo()->inputConfig.test(
2222 WindowInfo::InputConfig::PAUSE_DISPATCHING)) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002223 ALOGI("Waiting because %s is paused", focusedWindowHandle->getName().c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002224 outInjectionResult = InputEventInjectionResult::PENDING;
2225 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002226 }
2227
2228 // If the event is a key event, then we must wait for all previous events to
2229 // complete before delivering it because previous events may have the
2230 // side-effect of transferring focus to a different window and we want to
2231 // ensure that the following keys are sent to the new window.
2232 //
2233 // Suppose the user touches a button in a window then immediately presses "A".
2234 // If the button causes a pop-up window to appear then we want to ensure that
2235 // the "A" key is delivered to the new pop-up window. This is because users
2236 // often anticipate pending UI changes when typing on a keyboard.
2237 // To obtain this behavior, we must serialize key events with respect to all
2238 // prior input events.
2239 if (entry.type == EventEntry::Type::KEY) {
2240 if (shouldWaitToSendKeyLocked(currentTime, focusedWindowHandle->getName().c_str())) {
Siarhei Vishniakou69505962023-12-28 12:07:04 -08002241 nextWakeupTime = std::min(nextWakeupTime, *mKeyIsWaitingForEventsTimeout);
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002242 outInjectionResult = InputEventInjectionResult::PENDING;
2243 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002244 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002245 }
2246
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002247 outInjectionResult = InputEventInjectionResult::SUCCEEDED;
2248 return focusedWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002249}
2250
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002251/**
2252 * Given a list of monitors, remove the ones we cannot find a connection for, and the ones
2253 * that are currently unresponsive.
2254 */
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002255std::vector<Monitor> InputDispatcher::selectResponsiveMonitorsLocked(
2256 const std::vector<Monitor>& monitors) const {
2257 std::vector<Monitor> responsiveMonitors;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002258 std::copy_if(monitors.begin(), monitors.end(), std::back_inserter(responsiveMonitors),
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002259 [this](const Monitor& monitor) REQUIRES(mLock) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07002260 std::shared_ptr<Connection> connection =
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002261 getConnectionLocked(monitor.inputChannel->getConnectionToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002262 if (connection == nullptr) {
2263 ALOGE("Could not find connection for monitor %s",
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002264 monitor.inputChannel->getName().c_str());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002265 return false;
2266 }
2267 if (!connection->responsive) {
2268 ALOGW("Unresponsive monitor %s will not get the new gesture",
2269 connection->inputChannel->getName().c_str());
2270 return false;
2271 }
2272 return true;
2273 });
2274 return responsiveMonitors;
2275}
2276
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002277std::vector<InputTarget> InputDispatcher::findTouchedWindowTargetsLocked(
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002278 nsecs_t currentTime, const MotionEntry& entry,
Siarhei Vishniakou4fe57392022-10-25 13:44:30 -07002279 InputEventInjectionResult& outInjectionResult) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002280 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002281
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002282 std::vector<InputTarget> targets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002283 // For security reasons, we defer updating the touch state until we are sure that
2284 // event injection will be allowed.
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002285 const int32_t displayId = entry.displayId;
2286 const int32_t action = entry.action;
Siarhei Vishniakoubf880522023-05-01 11:03:22 -07002287 const int32_t maskedAction = MotionEvent::getActionMasked(action);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002288
2289 // Update the touch state as needed based on the properties of the touch event.
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002290 outInjectionResult = InputEventInjectionResult::PENDING;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002291
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002292 // Copy current touch state into tempTouchState.
2293 // This state will be used to update mTouchStatesByDisplay at the end of this function.
2294 // If no state for the specified display exists, then our initial state will be empty.
Yi Kong9b14ac62018-07-17 13:48:38 -07002295 const TouchState* oldState = nullptr;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002296 TouchState tempTouchState;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002297 if (const auto it = mTouchStatesByDisplay.find(displayId); it != mTouchStatesByDisplay.end()) {
2298 oldState = &(it->second);
Prabir Pradhane680f9b2022-02-04 04:24:00 -08002299 tempTouchState = *oldState;
Jeff Brownf086ddb2014-02-11 14:28:48 -08002300 }
2301
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07002302 bool isSplit = shouldSplitTouch(tempTouchState, entry);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002303
2304 const bool isHoverAction = (maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE ||
2305 maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2306 maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT);
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002307 // A DOWN could be generated from POINTER_DOWN if the initial pointers did not land into any
2308 // touchable windows.
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002309 const bool wasDown = oldState != nullptr && oldState->isDown(entry.deviceId);
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002310 const bool isDown = (maskedAction == AMOTION_EVENT_ACTION_DOWN) ||
2311 (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN && !wasDown);
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07002312 const bool newGesture = isDown || maskedAction == AMOTION_EVENT_ACTION_SCROLL ||
2313 maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2314 maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE;
Prabir Pradhanaa561d12021-09-24 06:57:33 -07002315 const bool isFromMouse = isFromSource(entry.source, AINPUT_SOURCE_MOUSE);
Siarhei Vishniakou5cee1e32022-11-29 12:35:39 -08002316
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002317 if (newGesture) {
2318 isSplit = false;
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002319 }
2320
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002321 if (isDown && tempTouchState.hasHoveringPointers(entry.deviceId)) {
2322 // Compatibility behaviour: ACTION_DOWN causes HOVER_EXIT to get generated.
2323 tempTouchState.clearHoveringPointers(entry.deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002324 }
2325
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002326 if (isHoverAction) {
Siarhei Vishniakou7be50c92023-11-17 17:09:08 -08002327 if (wasDown) {
2328 // Started hovering, but the device is already down: reject the hover event
2329 LOG(ERROR) << "Got hover event " << entry.getDescription()
2330 << " but the device is already down " << oldState->dump();
2331 outInjectionResult = InputEventInjectionResult::FAILED;
2332 return {};
2333 }
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002334 // For hover actions, we will treat 'tempTouchState' as a new state, so let's erase
2335 // all of the existing hovering pointers and recompute.
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002336 tempTouchState.clearHoveringPointers(entry.deviceId);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002337 }
2338
Michael Wrightd02c5b62014-02-10 15:10:22 -08002339 if (newGesture || (isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN)) {
2340 /* Case 1: New splittable pointer going down, or need target for hover or scroll. */
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07002341 const auto [x, y] = resolveTouchedPosition(entry);
Siarhei Vishniakou5b9766d2023-07-18 14:06:29 -07002342 const int32_t pointerIndex = MotionEvent::getActionIndex(action);
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002343 const PointerProperties& pointer = entry.pointerProperties[pointerIndex];
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002344 // Outside targets should be added upon first dispatched DOWN event. That means, this should
2345 // be a pointer that would generate ACTION_DOWN, *and* touch should not already be down.
Prabir Pradhand65552b2021-10-07 11:23:50 -07002346 const bool isStylus = isPointerFromStylus(entry, pointerIndex);
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07002347 sp<WindowInfoHandle> newTouchedWindowHandle =
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002348 findTouchedWindowAtLocked(displayId, x, y, isStylus);
Michael Wright3dd60e22019-03-27 22:06:44 +00002349
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002350 if (isDown) {
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002351 targets += findOutsideTargetsLocked(displayId, newTouchedWindowHandle, pointer.id);
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002352 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002353 // Handle the case where we did not find a window.
Yi Kong9b14ac62018-07-17 13:48:38 -07002354 if (newTouchedWindowHandle == nullptr) {
Prabir Pradhan82e081e2022-12-06 09:50:09 +00002355 ALOGD("No new touched window at (%.1f, %.1f) in display %" PRId32, x, y, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002356 // Try to assign the pointer to the first foreground window we find, if there is one.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002357 newTouchedWindowHandle = tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002358 }
2359
Prabir Pradhan5735a322022-04-11 17:23:34 +00002360 // Verify targeted injection.
2361 if (const auto err = verifyTargetedInjection(newTouchedWindowHandle, entry); err) {
2362 ALOGW("Dropping injected touch event: %s", (*err).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002363 outInjectionResult = os::InputEventInjectionResult::TARGET_MISMATCH;
Prabir Pradhan5735a322022-04-11 17:23:34 +00002364 newTouchedWindowHandle = nullptr;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002365 return {};
Prabir Pradhan5735a322022-04-11 17:23:34 +00002366 }
2367
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002368 // Figure out whether splitting will be allowed for this window.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002369 if (newTouchedWindowHandle != nullptr) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002370 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
2371 // New window supports splitting, but we should never split mouse events.
2372 isSplit = !isFromMouse;
2373 } else if (isSplit) {
2374 // New window does not support splitting but we have already split events.
2375 // Ignore the new window.
Siarhei Vishniakou25537f82023-07-18 14:35:47 -07002376 LOG(INFO) << "Skipping " << newTouchedWindowHandle->getName()
2377 << " because it doesn't support split touch";
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002378 newTouchedWindowHandle = nullptr;
2379 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002380 } else {
2381 // No window is touched, so set split to true. This will allow the next pointer down to
Prabir Pradhan713bb3e2021-12-20 02:07:40 -08002382 // be delivered to a new window which supports split touch. Pointers from a mouse device
2383 // should never be split.
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07002384 isSplit = !isFromMouse;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002385 }
2386
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002387 std::vector<sp<WindowInfoHandle>> newTouchedWindows =
Prabir Pradhand65552b2021-10-07 11:23:50 -07002388 findTouchedSpyWindowsAtLocked(displayId, x, y, isStylus);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002389 if (newTouchedWindowHandle != nullptr) {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002390 // Process the foreground window first so that it is the first to receive the event.
2391 newTouchedWindows.insert(newTouchedWindows.begin(), newTouchedWindowHandle);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002392 }
2393
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002394 if (newTouchedWindows.empty()) {
Prabir Pradhan82e081e2022-12-06 09:50:09 +00002395 ALOGI("Dropping event because there is no touchable window at (%.1f, %.1f) on display "
2396 "%d.",
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002397 x, y, displayId);
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002398 outInjectionResult = InputEventInjectionResult::FAILED;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002399 return {};
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002400 }
2401
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002402 for (const sp<WindowInfoHandle>& windowHandle : newTouchedWindows) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07002403 if (!canWindowReceiveMotionLocked(windowHandle, entry)) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002404 continue;
2405 }
2406
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002407 if (isHoverAction) {
Siarhei Vishniakoub681c202023-05-01 11:22:33 -07002408 // The "windowHandle" is the target of this hovering pointer.
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002409 tempTouchState.addHoveringPointerToWindow(windowHandle, entry.deviceId, pointer);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002410 }
2411
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002412 // Set target flags.
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002413 ftl::Flags<InputTarget::Flags> targetFlags;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002414
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002415 if (canReceiveForegroundTouches(*windowHandle->getInfo())) {
2416 // There should only be one touched window that can be "foreground" for the pointer.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002417 targetFlags |= InputTarget::Flags::FOREGROUND;
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002418 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002419
2420 if (isSplit) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002421 targetFlags |= InputTarget::Flags::SPLIT;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002422 }
2423 if (isWindowObscuredAtPointLocked(windowHandle, x, y)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002424 targetFlags |= InputTarget::Flags::WINDOW_IS_OBSCURED;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002425 } else if (isWindowObscuredLocked(windowHandle)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002426 targetFlags |= InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002427 }
Michael Wright3dd60e22019-03-27 22:06:44 +00002428
2429 // Update the temporary touch state.
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002430
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002431 if (!isHoverAction) {
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002432 const bool isDownOrPointerDown = maskedAction == AMOTION_EVENT_ACTION_DOWN ||
2433 maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN;
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002434 tempTouchState.addOrUpdateWindow(windowHandle, InputTarget::DispatchMode::AS_IS,
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002435 targetFlags, entry.deviceId, {pointer},
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002436 isDownOrPointerDown
2437 ? std::make_optional(entry.eventTime)
2438 : std::nullopt);
2439 // If this is the pointer going down and the touched window has a wallpaper
2440 // then also add the touched wallpaper windows so they are locked in for the
2441 // duration of the touch gesture. We do not collect wallpapers during HOVER_MOVE or
2442 // SCROLL because the wallpaper engine only supports touch events. We would need to
2443 // add a mechanism similar to View.onGenericMotionEvent to enable wallpapers to
2444 // handle these events.
2445 if (isDownOrPointerDown && targetFlags.test(InputTarget::Flags::FOREGROUND) &&
Arthur Hungc539dbb2022-12-08 07:45:36 +00002446 windowHandle->getInfo()->inputConfig.test(
2447 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER)) {
2448 sp<WindowInfoHandle> wallpaper = findWallpaperWindowBelow(windowHandle);
2449 if (wallpaper != nullptr) {
2450 ftl::Flags<InputTarget::Flags> wallpaperFlags =
2451 InputTarget::Flags::WINDOW_IS_OBSCURED |
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002452 InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED;
Arthur Hungc539dbb2022-12-08 07:45:36 +00002453 if (isSplit) {
2454 wallpaperFlags |= InputTarget::Flags::SPLIT;
2455 }
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002456 tempTouchState.addOrUpdateWindow(wallpaper,
2457 InputTarget::DispatchMode::AS_IS,
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002458 wallpaperFlags, entry.deviceId, {pointer},
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002459 entry.eventTime);
Arthur Hungc539dbb2022-12-08 07:45:36 +00002460 }
2461 }
2462 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002463 }
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00002464
Siarhei Vishniakou060f82b2023-01-27 06:39:14 -08002465 // If a window is already pilfering some pointers, give it this new pointer as well and
2466 // make it pilfering. This will prevent other non-spy windows from getting this pointer,
2467 // which is a specific behaviour that we want.
Siarhei Vishniakou060f82b2023-01-27 06:39:14 -08002468 for (TouchedWindow& touchedWindow : tempTouchState.windows) {
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002469 if (touchedWindow.hasTouchingPointer(entry.deviceId, pointer.id) &&
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002470 touchedWindow.hasPilferingPointers(entry.deviceId)) {
Siarhei Vishniakou060f82b2023-01-27 06:39:14 -08002471 // This window is already pilfering some pointers, and this new pointer is also
2472 // going to it. Therefore, take over this pointer and don't give it to anyone
2473 // else.
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002474 touchedWindow.addPilferingPointer(entry.deviceId, pointer.id);
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00002475 }
2476 }
Siarhei Vishniakou060f82b2023-01-27 06:39:14 -08002477
2478 // Restrict all pilfered pointers to the pilfering windows.
2479 tempTouchState.cancelPointersForNonPilferingWindows();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002480 } else {
2481 /* Case 2: Pointer move, up, cancel or non-splittable pointer down. */
2482
2483 // If the pointer is not currently down, then ignore the event.
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002484 if (!tempTouchState.isDown(entry.deviceId) &&
2485 maskedAction != AMOTION_EVENT_ACTION_HOVER_EXIT) {
Siarhei Vishniakou31dd1552023-10-30 18:46:10 -07002486 if (DEBUG_DROPPED_EVENTS_VERBOSE) {
2487 LOG(INFO) << "Dropping event because the pointer for device " << entry.deviceId
2488 << " is not down or we previously dropped the pointer down event in "
2489 << "display " << displayId << ": " << entry.getDescription();
2490 }
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002491 outInjectionResult = InputEventInjectionResult::FAILED;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002492 return {};
Michael Wrightd02c5b62014-02-10 15:10:22 -08002493 }
2494
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07002495 // If the pointer is not currently hovering, then ignore the event.
2496 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT) {
2497 const int32_t pointerId = entry.pointerProperties[0].id;
2498 if (oldState == nullptr ||
2499 oldState->getWindowsWithHoveringPointer(entry.deviceId, pointerId).empty()) {
2500 LOG(INFO) << "Dropping event because the hovering pointer is not in any windows in "
2501 "display "
2502 << displayId << ": " << entry.getDescription();
2503 outInjectionResult = InputEventInjectionResult::FAILED;
2504 return {};
2505 }
2506 tempTouchState.removeHoveringPointer(entry.deviceId, pointerId);
2507 }
2508
arthurhung6d4bed92021-03-17 11:59:33 +08002509 addDragEventLocked(entry);
arthurhungb89ccb02020-12-30 16:19:01 +08002510
Michael Wrightd02c5b62014-02-10 15:10:22 -08002511 // Check whether touches should slip outside of the current foreground window.
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07002512 if (maskedAction == AMOTION_EVENT_ACTION_MOVE && entry.getPointerCount() == 1 &&
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002513 tempTouchState.isSlippery()) {
Siarhei Vishniakou9306c382022-09-30 15:30:31 -07002514 const auto [x, y] = resolveTouchedPosition(entry);
Harry Cutts33476232023-01-30 19:57:29 +00002515 const bool isStylus = isPointerFromStylus(entry, /*pointerIndex=*/0);
chaviw98318de2021-05-19 16:45:23 -05002516 sp<WindowInfoHandle> oldTouchedWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002517 tempTouchState.getFirstForegroundWindowHandle();
Siarhei Vishniakou0f6558d2023-04-21 12:05:13 -07002518 LOG_ALWAYS_FATAL_IF(oldTouchedWindowHandle == nullptr);
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07002519 sp<WindowInfoHandle> newTouchedWindowHandle =
2520 findTouchedWindowAtLocked(displayId, x, y, isStylus);
Vishnu Nair062a8672021-09-03 16:07:44 -07002521
Prabir Pradhan5735a322022-04-11 17:23:34 +00002522 // Verify targeted injection.
2523 if (const auto err = verifyTargetedInjection(newTouchedWindowHandle, entry); err) {
2524 ALOGW("Dropping injected event: %s", (*err).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002525 outInjectionResult = os::InputEventInjectionResult::TARGET_MISMATCH;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002526 return {};
Prabir Pradhan5735a322022-04-11 17:23:34 +00002527 }
2528
Vishnu Nair062a8672021-09-03 16:07:44 -07002529 // Drop touch events if requested by input feature
2530 if (newTouchedWindowHandle != nullptr &&
2531 shouldDropInput(entry, newTouchedWindowHandle)) {
2532 newTouchedWindowHandle = nullptr;
2533 }
2534
Siarhei Vishniakouafa08cc2023-05-08 22:35:50 -07002535 if (newTouchedWindowHandle != nullptr &&
2536 !haveSameToken(oldTouchedWindowHandle, newTouchedWindowHandle)) {
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002537 ALOGI("Touch is slipping out of window %s into window %s in display %" PRId32,
Siarhei Vishniakou0f6558d2023-04-21 12:05:13 -07002538 oldTouchedWindowHandle->getName().c_str(),
2539 newTouchedWindowHandle->getName().c_str(), displayId);
2540
Michael Wrightd02c5b62014-02-10 15:10:22 -08002541 // Make a slippery exit from the old window.
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08002542 std::bitset<MAX_POINTER_ID + 1> pointerIds;
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002543 const PointerProperties& pointer = entry.pointerProperties[0];
2544 pointerIds.set(pointer.id);
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002545
2546 const TouchedWindow& touchedWindow =
2547 tempTouchState.getTouchedWindow(oldTouchedWindowHandle);
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002548 addPointerWindowTargetLocked(oldTouchedWindowHandle,
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002549 InputTarget::DispatchMode::SLIPPERY_EXIT,
2550 ftl::Flags<InputTarget::Flags>(), pointerIds,
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002551 touchedWindow.getDownTimeInTarget(entry.deviceId),
2552 targets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002553
2554 // Make a slippery entrance into the new window.
2555 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
Prabir Pradhan713bb3e2021-12-20 02:07:40 -08002556 isSplit = !isFromMouse;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002557 }
2558
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002559 ftl::Flags<InputTarget::Flags> targetFlags;
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002560 if (canReceiveForegroundTouches(*newTouchedWindowHandle->getInfo())) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002561 targetFlags |= InputTarget::Flags::FOREGROUND;
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002562 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002563 if (isSplit) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002564 targetFlags |= InputTarget::Flags::SPLIT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002565 }
2566 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002567 targetFlags |= InputTarget::Flags::WINDOW_IS_OBSCURED;
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002568 } else if (isWindowObscuredLocked(newTouchedWindowHandle)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002569 targetFlags |= InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002570 }
2571
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002572 tempTouchState.addOrUpdateWindow(newTouchedWindowHandle,
2573 InputTarget::DispatchMode::SLIPPERY_ENTER,
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002574 targetFlags, entry.deviceId, {pointer},
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002575 entry.eventTime);
Arthur Hungc539dbb2022-12-08 07:45:36 +00002576
2577 // Check if the wallpaper window should deliver the corresponding event.
2578 slipWallpaperTouch(targetFlags, oldTouchedWindowHandle, newTouchedWindowHandle,
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002579 tempTouchState, entry.deviceId, pointer, targets);
2580 tempTouchState.removeTouchingPointerFromWindow(entry.deviceId, pointer.id,
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002581 oldTouchedWindowHandle);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002582 }
2583 }
Arthur Hung96483742022-11-15 03:30:48 +00002584
2585 // Update the pointerIds for non-splittable when it received pointer down.
2586 if (!isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN) {
2587 // If no split, we suppose all touched windows should receive pointer down.
Siarhei Vishniakou5b9766d2023-07-18 14:06:29 -07002588 const int32_t pointerIndex = MotionEvent::getActionIndex(action);
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002589 std::vector<PointerProperties> touchingPointers{entry.pointerProperties[pointerIndex]};
2590 for (TouchedWindow& touchedWindow : tempTouchState.windows) {
Arthur Hung96483742022-11-15 03:30:48 +00002591 // Ignore drag window for it should just track one pointer.
2592 if (mDragState && mDragState->dragWindow == touchedWindow.windowHandle) {
2593 continue;
2594 }
Siarhei Vishniakou5b9766d2023-07-18 14:06:29 -07002595 touchedWindow.addTouchingPointers(entry.deviceId, touchingPointers);
Arthur Hung96483742022-11-15 03:30:48 +00002596 }
2597 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002598 }
2599
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002600 // Update dispatching for hover enter and exit.
Sam Dubeyf886dec2023-01-27 13:28:19 +00002601 {
2602 std::vector<TouchedWindow> hoveringWindows =
2603 getHoveringWindowsLocked(oldState, tempTouchState, entry);
2604 for (const TouchedWindow& touchedWindow : hoveringWindows) {
Siarhei Vishniakoud5876ba2023-05-15 17:58:34 -07002605 std::optional<InputTarget> target =
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002606 createInputTargetLocked(touchedWindow.windowHandle, touchedWindow.dispatchMode,
2607 touchedWindow.targetFlags,
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002608 touchedWindow.getDownTimeInTarget(entry.deviceId));
Siarhei Vishniakoud5876ba2023-05-15 17:58:34 -07002609 if (!target) {
2610 continue;
2611 }
2612 // Hardcode to single hovering pointer for now.
2613 std::bitset<MAX_POINTER_ID + 1> pointerIds;
2614 pointerIds.set(entry.pointerProperties[0].id);
2615 target->addPointers(pointerIds, touchedWindow.windowHandle->getInfo()->transform);
2616 targets.push_back(*target);
Sam Dubeyf886dec2023-01-27 13:28:19 +00002617 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002618 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002619
Prabir Pradhan5735a322022-04-11 17:23:34 +00002620 // Ensure that all touched windows are valid for injection.
2621 if (entry.injectionState != nullptr) {
2622 std::string errs;
2623 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Prabir Pradhan5735a322022-04-11 17:23:34 +00002624 const auto err = verifyTargetedInjection(touchedWindow.windowHandle, entry);
2625 if (err) errs += "\n - " + *err;
2626 }
2627 if (!errs.empty()) {
2628 ALOGW("Dropping targeted injection: At least one touched window is not owned by uid "
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00002629 "%s:%s",
2630 entry.injectionState->targetUid->toString().c_str(), errs.c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002631 outInjectionResult = InputEventInjectionResult::TARGET_MISMATCH;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002632 return {};
Prabir Pradhan5735a322022-04-11 17:23:34 +00002633 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002634 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002635
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002636 // Check whether windows listening for outside touches are owned by the same UID. If the owner
2637 // has a different UID, then we will not reveal coordinate information to this window.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002638 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
chaviw98318de2021-05-19 16:45:23 -05002639 sp<WindowInfoHandle> foregroundWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002640 tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002641 if (foregroundWindowHandle) {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00002642 const auto foregroundWindowUid = foregroundWindowHandle->getInfo()->ownerUid;
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002643 for (InputTarget& target : targets) {
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002644 if (target.dispatchMode == InputTarget::DispatchMode::OUTSIDE) {
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002645 sp<WindowInfoHandle> targetWindow =
2646 getWindowHandleLocked(target.inputChannel->getConnectionToken());
2647 if (targetWindow->getInfo()->ownerUid != foregroundWindowUid) {
2648 target.flags |= InputTarget::Flags::ZERO_COORDS;
Michael Wright3dd60e22019-03-27 22:06:44 +00002649 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002650 }
2651 }
2652 }
2653 }
2654
Harry Cuttsb166c002023-05-09 13:06:05 +00002655 // If this is a touchpad navigation gesture, it needs to only be sent to trusted targets, as we
2656 // only want the system UI to handle these gestures.
2657 const bool isTouchpadNavGesture = isFromSource(entry.source, AINPUT_SOURCE_MOUSE) &&
2658 entry.classification == MotionClassification::MULTI_FINGER_SWIPE;
2659 if (isTouchpadNavGesture) {
2660 filterUntrustedTargets(/* byref */ tempTouchState, /* byref */ targets);
2661 }
2662
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07002663 // Output targets from the touch state.
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002664 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002665 std::vector<PointerProperties> touchingPointers =
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002666 touchedWindow.getTouchingPointers(entry.deviceId);
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002667 if (touchingPointers.empty()) {
Siarhei Vishniakoue0431e42023-01-28 17:01:39 -08002668 continue;
2669 }
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002670 addPointerWindowTargetLocked(touchedWindow.windowHandle, touchedWindow.dispatchMode,
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002671 touchedWindow.targetFlags, getPointerIds(touchingPointers),
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002672 touchedWindow.getDownTimeInTarget(entry.deviceId), targets);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002673 }
Sam Dubey39d37cf2022-12-07 18:05:35 +00002674
Siarhei Vishniakou580fb3a2023-05-05 15:02:20 -07002675 // During targeted injection, only allow owned targets to receive events
2676 std::erase_if(targets, [&](const InputTarget& target) {
2677 LOG_ALWAYS_FATAL_IF(target.windowHandle == nullptr);
2678 const auto err = verifyTargetedInjection(target.windowHandle, entry);
2679 if (err) {
2680 LOG(WARNING) << "Dropping injected event from " << target.windowHandle->getName()
2681 << ": " << (*err);
2682 return true;
2683 }
2684 return false;
2685 });
2686
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07002687 if (targets.empty()) {
2688 LOG(INFO) << "Dropping event because no targets were found: " << entry.getDescription();
2689 outInjectionResult = InputEventInjectionResult::FAILED;
2690 return {};
2691 }
2692
2693 // If we only have windows getting ACTION_OUTSIDE, then drop the event, because there is no
2694 // window that is actually receiving the entire gesture.
2695 if (std::all_of(targets.begin(), targets.end(), [](const InputTarget& target) {
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002696 return target.dispatchMode == InputTarget::DispatchMode::OUTSIDE;
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07002697 })) {
2698 LOG(INFO) << "Dropping event because all windows would just receive ACTION_OUTSIDE: "
2699 << entry.getDescription();
2700 outInjectionResult = InputEventInjectionResult::FAILED;
2701 return {};
2702 }
2703
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002704 outInjectionResult = InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002705
Prabir Pradhan502a7252023-12-01 16:11:24 +00002706 // Now that we have generated all of the input targets for this event, reset the dispatch
2707 // mode for all touched window to AS_IS.
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002708 for (TouchedWindow& touchedWindow : tempTouchState.windows) {
Prabir Pradhan502a7252023-12-01 16:11:24 +00002709 touchedWindow.dispatchMode = InputTarget::DispatchMode::AS_IS;
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002710 }
2711
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002712 // Update final pieces of touch state if the injector had permission.
Siarhei Vishniakou7be50c92023-11-17 17:09:08 -08002713 if (maskedAction == AMOTION_EVENT_ACTION_UP) {
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002714 // Pointer went up.
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002715 tempTouchState.removeTouchingPointer(entry.deviceId, entry.pointerProperties[0].id);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002716 } else if (maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002717 // All pointers up or canceled.
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002718 tempTouchState.removeAllPointersForDevice(entry.deviceId);
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002719 } else if (maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
2720 // One pointer went up.
Siarhei Vishniakou5b9766d2023-07-18 14:06:29 -07002721 const int32_t pointerIndex = MotionEvent::getActionIndex(action);
2722 const uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
2723 tempTouchState.removeTouchingPointer(entry.deviceId, pointerId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002724 }
2725
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002726 // Save changes unless the action was scroll in which case the temporary touch
2727 // state was only valid for this one action.
2728 if (maskedAction != AMOTION_EVENT_ACTION_SCROLL) {
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07002729 if (displayId >= 0) {
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002730 tempTouchState.clearWindowsWithoutPointers();
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002731 mTouchStatesByDisplay[displayId] = tempTouchState;
2732 } else {
2733 mTouchStatesByDisplay.erase(displayId);
2734 }
2735 }
2736
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -08002737 if (tempTouchState.windows.empty()) {
2738 mTouchStatesByDisplay.erase(displayId);
2739 }
2740
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002741 return targets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002742}
2743
arthurhung6d4bed92021-03-17 11:59:33 +08002744void InputDispatcher::finishDragAndDrop(int32_t displayId, float x, float y) {
Prabir Pradhand65552b2021-10-07 11:23:50 -07002745 // Prevent stylus interceptor windows from affecting drag and drop behavior for now, until we
2746 // have an explicit reason to support it.
2747 constexpr bool isStylus = false;
2748
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07002749 sp<WindowInfoHandle> dropWindow =
Harry Cutts33476232023-01-30 19:57:29 +00002750 findTouchedWindowAtLocked(displayId, x, y, isStylus, /*ignoreDragWindow=*/true);
arthurhung6d4bed92021-03-17 11:59:33 +08002751 if (dropWindow) {
2752 vec2 local = dropWindow->getInfo()->transform.transform(x, y);
Prabir Pradhancef936d2021-07-21 16:17:52 +00002753 sendDropWindowCommandLocked(dropWindow->getToken(), local.x, local.y);
Arthur Hung6d0571e2021-04-09 20:18:16 +08002754 } else {
Arthur Hung54745652022-04-20 07:17:41 +00002755 ALOGW("No window found when drop.");
Prabir Pradhancef936d2021-07-21 16:17:52 +00002756 sendDropWindowCommandLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08002757 }
2758 mDragState.reset();
2759}
2760
2761void InputDispatcher::addDragEventLocked(const MotionEntry& entry) {
Arthur Hung3915c1f2022-05-31 07:17:17 +00002762 if (!mDragState || mDragState->dragWindow->getInfo()->displayId != entry.displayId) {
arthurhungb89ccb02020-12-30 16:19:01 +08002763 return;
2764 }
2765
arthurhung6d4bed92021-03-17 11:59:33 +08002766 if (!mDragState->isStartDrag) {
2767 mDragState->isStartDrag = true;
2768 mDragState->isStylusButtonDownAtStart =
2769 (entry.buttonState & AMOTION_EVENT_BUTTON_STYLUS_PRIMARY) != 0;
2770 }
2771
Arthur Hung54745652022-04-20 07:17:41 +00002772 // Find the pointer index by id.
2773 int32_t pointerIndex = 0;
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07002774 for (; static_cast<uint32_t>(pointerIndex) < entry.getPointerCount(); pointerIndex++) {
Arthur Hung54745652022-04-20 07:17:41 +00002775 const PointerProperties& pointerProperties = entry.pointerProperties[pointerIndex];
2776 if (pointerProperties.id == mDragState->pointerId) {
2777 break;
arthurhung6d4bed92021-03-17 11:59:33 +08002778 }
Arthur Hung54745652022-04-20 07:17:41 +00002779 }
arthurhung6d4bed92021-03-17 11:59:33 +08002780
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07002781 if (uint32_t(pointerIndex) == entry.getPointerCount()) {
Arthur Hung54745652022-04-20 07:17:41 +00002782 LOG_ALWAYS_FATAL("Should find a valid pointer index by id %d", mDragState->pointerId);
Arthur Hung54745652022-04-20 07:17:41 +00002783 }
2784
2785 const int32_t maskedAction = entry.action & AMOTION_EVENT_ACTION_MASK;
2786 const int32_t x = entry.pointerCoords[pointerIndex].getX();
2787 const int32_t y = entry.pointerCoords[pointerIndex].getY();
2788
2789 switch (maskedAction) {
2790 case AMOTION_EVENT_ACTION_MOVE: {
2791 // Handle the special case : stylus button no longer pressed.
2792 bool isStylusButtonDown =
2793 (entry.buttonState & AMOTION_EVENT_BUTTON_STYLUS_PRIMARY) != 0;
2794 if (mDragState->isStylusButtonDownAtStart && !isStylusButtonDown) {
2795 finishDragAndDrop(entry.displayId, x, y);
2796 return;
2797 }
2798
2799 // Prevent stylus interceptor windows from affecting drag and drop behavior for now,
2800 // until we have an explicit reason to support it.
2801 constexpr bool isStylus = false;
2802
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07002803 sp<WindowInfoHandle> hoverWindowHandle =
2804 findTouchedWindowAtLocked(entry.displayId, x, y, isStylus,
2805 /*ignoreDragWindow=*/true);
Arthur Hung54745652022-04-20 07:17:41 +00002806 // enqueue drag exit if needed.
2807 if (hoverWindowHandle != mDragState->dragHoverWindowHandle &&
2808 !haveSameToken(hoverWindowHandle, mDragState->dragHoverWindowHandle)) {
2809 if (mDragState->dragHoverWindowHandle != nullptr) {
Harry Cutts33476232023-01-30 19:57:29 +00002810 enqueueDragEventLocked(mDragState->dragHoverWindowHandle, /*isExiting=*/true, x,
Arthur Hung54745652022-04-20 07:17:41 +00002811 y);
2812 }
2813 mDragState->dragHoverWindowHandle = hoverWindowHandle;
2814 }
2815 // enqueue drag location if needed.
2816 if (hoverWindowHandle != nullptr) {
Harry Cutts33476232023-01-30 19:57:29 +00002817 enqueueDragEventLocked(hoverWindowHandle, /*isExiting=*/false, x, y);
Arthur Hung54745652022-04-20 07:17:41 +00002818 }
2819 break;
2820 }
2821
2822 case AMOTION_EVENT_ACTION_POINTER_UP:
Siarhei Vishniakou5b9766d2023-07-18 14:06:29 -07002823 if (MotionEvent::getActionIndex(entry.action) != pointerIndex) {
Arthur Hung54745652022-04-20 07:17:41 +00002824 break;
2825 }
2826 // The drag pointer is up.
2827 [[fallthrough]];
2828 case AMOTION_EVENT_ACTION_UP:
2829 finishDragAndDrop(entry.displayId, x, y);
2830 break;
2831 case AMOTION_EVENT_ACTION_CANCEL: {
2832 ALOGD("Receiving cancel when drag and drop.");
2833 sendDropWindowCommandLocked(nullptr, 0, 0);
2834 mDragState.reset();
2835 break;
2836 }
arthurhungb89ccb02020-12-30 16:19:01 +08002837 }
2838}
2839
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002840std::optional<InputTarget> InputDispatcher::createInputTargetLocked(
2841 const sp<android::gui::WindowInfoHandle>& windowHandle,
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002842 InputTarget::DispatchMode dispatchMode, ftl::Flags<InputTarget::Flags> targetFlags,
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002843 std::optional<nsecs_t> firstDownTimeInTarget) const {
2844 std::shared_ptr<InputChannel> inputChannel = getInputChannelLocked(windowHandle->getToken());
2845 if (inputChannel == nullptr) {
2846 ALOGW("Not creating InputTarget for %s, no input channel", windowHandle->getName().c_str());
2847 return {};
2848 }
2849 InputTarget inputTarget;
2850 inputTarget.inputChannel = inputChannel;
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00002851 inputTarget.windowHandle = windowHandle;
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002852 inputTarget.dispatchMode = dispatchMode;
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002853 inputTarget.flags = targetFlags;
2854 inputTarget.globalScaleFactor = windowHandle->getInfo()->globalScaleFactor;
2855 inputTarget.firstDownTimeInTarget = firstDownTimeInTarget;
2856 const auto& displayInfoIt = mDisplayInfos.find(windowHandle->getInfo()->displayId);
2857 if (displayInfoIt != mDisplayInfos.end()) {
2858 inputTarget.displayTransform = displayInfoIt->second.transform;
2859 } else {
Siarhei Vishniakou580fb3a2023-05-05 15:02:20 -07002860 // DisplayInfo not found for this window on display windowHandle->getInfo()->displayId.
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002861 // TODO(b/198444055): Make this an error message after 'setInputWindows' API is removed.
2862 }
2863 return inputTarget;
2864}
2865
chaviw98318de2021-05-19 16:45:23 -05002866void InputDispatcher::addWindowTargetLocked(const sp<WindowInfoHandle>& windowHandle,
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002867 InputTarget::DispatchMode dispatchMode,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002868 ftl::Flags<InputTarget::Flags> targetFlags,
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002869 std::optional<nsecs_t> firstDownTimeInTarget,
Siarhei Vishniakouf75cddb2022-10-25 10:42:16 -07002870 std::vector<InputTarget>& inputTargets) const {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002871 std::vector<InputTarget>::iterator it =
2872 std::find_if(inputTargets.begin(), inputTargets.end(),
2873 [&windowHandle](const InputTarget& inputTarget) {
2874 return inputTarget.inputChannel->getConnectionToken() ==
2875 windowHandle->getToken();
2876 });
Chavi Weingarten97b8eec2020-01-09 18:09:08 +00002877
chaviw98318de2021-05-19 16:45:23 -05002878 const WindowInfo* windowInfo = windowHandle->getInfo();
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002879
2880 if (it == inputTargets.end()) {
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002881 std::optional<InputTarget> target =
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002882 createInputTargetLocked(windowHandle, dispatchMode, targetFlags,
2883 firstDownTimeInTarget);
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002884 if (!target) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002885 return;
2886 }
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002887 inputTargets.push_back(*target);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002888 it = inputTargets.end() - 1;
2889 }
2890
Siarhei Vishniakou23d73fb2023-10-29 13:27:46 -07002891 if (it->flags != targetFlags) {
2892 LOG(ERROR) << "Flags don't match! targetFlags=" << targetFlags.string() << ", it=" << *it;
2893 }
2894 if (it->globalScaleFactor != windowInfo->globalScaleFactor) {
2895 LOG(ERROR) << "Mismatch! it->globalScaleFactor=" << it->globalScaleFactor
2896 << ", windowInfo->globalScaleFactor=" << windowInfo->globalScaleFactor;
2897 }
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002898}
2899
2900void InputDispatcher::addPointerWindowTargetLocked(
2901 const sp<android::gui::WindowInfoHandle>& windowHandle,
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002902 InputTarget::DispatchMode dispatchMode, ftl::Flags<InputTarget::Flags> targetFlags,
2903 std::bitset<MAX_POINTER_ID + 1> pointerIds, std::optional<nsecs_t> firstDownTimeInTarget,
2904 std::vector<InputTarget>& inputTargets) const REQUIRES(mLock) {
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002905 if (pointerIds.none()) {
2906 for (const auto& target : inputTargets) {
2907 LOG(INFO) << "Target: " << target;
2908 }
2909 LOG(FATAL) << "No pointers specified for " << windowHandle->getName();
2910 return;
2911 }
2912 std::vector<InputTarget>::iterator it =
2913 std::find_if(inputTargets.begin(), inputTargets.end(),
2914 [&windowHandle](const InputTarget& inputTarget) {
2915 return inputTarget.inputChannel->getConnectionToken() ==
2916 windowHandle->getToken();
2917 });
2918
2919 // This is a hack, because the actual entry could potentially be an ACTION_DOWN event that
2920 // causes a HOVER_EXIT to be generated. That means that the same entry of ACTION_DOWN would
2921 // have DISPATCH_AS_HOVER_EXIT and DISPATCH_AS_IS. And therefore, we have to create separate
2922 // input targets for hovering pointers and for touching pointers.
2923 // If we picked an existing input target above, but it's for HOVER_EXIT - let's use a new
2924 // target instead.
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002925 if (it != inputTargets.end() && it->dispatchMode == InputTarget::DispatchMode::HOVER_EXIT) {
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002926 // Force the code below to create a new input target
2927 it = inputTargets.end();
2928 }
2929
2930 const WindowInfo* windowInfo = windowHandle->getInfo();
2931
2932 if (it == inputTargets.end()) {
2933 std::optional<InputTarget> target =
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002934 createInputTargetLocked(windowHandle, dispatchMode, targetFlags,
2935 firstDownTimeInTarget);
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002936 if (!target) {
2937 return;
2938 }
2939 inputTargets.push_back(*target);
2940 it = inputTargets.end() - 1;
2941 }
2942
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002943 if (it->dispatchMode != dispatchMode) {
2944 LOG(ERROR) << __func__ << ": DispatchMode doesn't match! ignoring new mode="
2945 << ftl::enum_string(dispatchMode) << ", it=" << *it;
2946 }
Siarhei Vishniakou4bd0b7c2023-10-27 00:51:14 -07002947 if (it->flags != targetFlags) {
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002948 LOG(ERROR) << __func__ << ": Flags don't match! new targetFlags=" << targetFlags.string()
2949 << ", it=" << *it;
Siarhei Vishniakou4bd0b7c2023-10-27 00:51:14 -07002950 }
Siarhei Vishniakou23d73fb2023-10-29 13:27:46 -07002951 if (it->globalScaleFactor != windowInfo->globalScaleFactor) {
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002952 LOG(ERROR) << __func__ << ": Mismatch! it->globalScaleFactor=" << it->globalScaleFactor
Siarhei Vishniakou23d73fb2023-10-29 13:27:46 -07002953 << ", windowInfo->globalScaleFactor=" << windowInfo->globalScaleFactor;
2954 }
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002955
chaviw1ff3d1e2020-07-01 15:53:47 -07002956 it->addPointers(pointerIds, windowInfo->transform);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002957}
2958
Michael Wright3dd60e22019-03-27 22:06:44 +00002959void InputDispatcher::addGlobalMonitoringTargetsLocked(std::vector<InputTarget>& inputTargets,
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002960 int32_t displayId) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002961 auto monitorsIt = mGlobalMonitorsByDisplay.find(displayId);
2962 if (monitorsIt == mGlobalMonitorsByDisplay.end()) return;
Michael Wright3dd60e22019-03-27 22:06:44 +00002963
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002964 for (const Monitor& monitor : selectResponsiveMonitorsLocked(monitorsIt->second)) {
2965 InputTarget target;
2966 target.inputChannel = monitor.inputChannel;
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002967 // target.firstDownTimeInTarget is not set for global monitors. It is only required in split
2968 // touch and global monitoring works as intended even without setting firstDownTimeInTarget
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002969 if (const auto& it = mDisplayInfos.find(displayId); it != mDisplayInfos.end()) {
2970 target.displayTransform = it->second.transform;
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002971 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002972 target.setDefaultPointerTransform(target.displayTransform);
2973 inputTargets.push_back(target);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002974 }
2975}
2976
Robert Carrc9bf1d32020-04-13 17:21:08 -07002977/**
2978 * Indicate whether one window handle should be considered as obscuring
2979 * another window handle. We only check a few preconditions. Actually
2980 * checking the bounds is left to the caller.
2981 */
chaviw98318de2021-05-19 16:45:23 -05002982static bool canBeObscuredBy(const sp<WindowInfoHandle>& windowHandle,
2983 const sp<WindowInfoHandle>& otherHandle) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002984 // Compare by token so cloned layers aren't counted
2985 if (haveSameToken(windowHandle, otherHandle)) {
2986 return false;
2987 }
2988 auto info = windowHandle->getInfo();
2989 auto otherInfo = otherHandle->getInfo();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002990 if (otherInfo->inputConfig.test(WindowInfo::InputConfig::NOT_VISIBLE)) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002991 return false;
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002992 } else if (otherInfo->alpha == 0 &&
2993 otherInfo->inputConfig.test(WindowInfo::InputConfig::NOT_TOUCHABLE)) {
Bernardo Rufino653d2e02020-10-20 17:32:40 +00002994 // Those act as if they were invisible, so we don't need to flag them.
2995 // We do want to potentially flag touchable windows even if they have 0
2996 // opacity, since they can consume touches and alter the effects of the
2997 // user interaction (eg. apps that rely on
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002998 // Flags::WINDOW_IS_PARTIALLY_OBSCURED should still be told about those
Bernardo Rufino653d2e02020-10-20 17:32:40 +00002999 // windows), hence we also check for FLAG_NOT_TOUCHABLE.
3000 return false;
Bernardo Rufino8007daf2020-09-22 09:40:01 +00003001 } else if (info->ownerUid == otherInfo->ownerUid) {
3002 // If ownerUid is the same we don't generate occlusion events as there
3003 // is no security boundary within an uid.
Robert Carrc9bf1d32020-04-13 17:21:08 -07003004 return false;
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08003005 } else if (otherInfo->inputConfig.test(gui::WindowInfo::InputConfig::TRUSTED_OVERLAY)) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07003006 return false;
3007 } else if (otherInfo->displayId != info->displayId) {
3008 return false;
3009 }
3010 return true;
3011}
3012
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003013/**
3014 * Returns touch occlusion information in the form of TouchOcclusionInfo. To check if the touch is
3015 * untrusted, one should check:
3016 *
3017 * 1. If result.hasBlockingOcclusion is true.
3018 * If it's, it means the touch should be blocked due to a window with occlusion mode of
3019 * BLOCK_UNTRUSTED.
3020 *
3021 * 2. If result.obscuringOpacity > mMaximumObscuringOpacityForTouch.
3022 * If it is (and 1 is false), then the touch should be blocked because a stack of windows
3023 * (possibly only one) with occlusion mode of USE_OPACITY from one UID resulted in a composed
3024 * obscuring opacity above the threshold. Note that if there was no window of occlusion mode
3025 * USE_OPACITY, result.obscuringOpacity would've been 0 and since
3026 * mMaximumObscuringOpacityForTouch >= 0, the condition above would never be true.
3027 *
3028 * If neither of those is true, then it means the touch can be allowed.
3029 */
3030InputDispatcher::TouchOcclusionInfo InputDispatcher::computeTouchOcclusionInfoLocked(
chaviw98318de2021-05-19 16:45:23 -05003031 const sp<WindowInfoHandle>& windowHandle, int32_t x, int32_t y) const {
3032 const WindowInfo* windowInfo = windowHandle->getInfo();
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00003033 int32_t displayId = windowInfo->displayId;
chaviw98318de2021-05-19 16:45:23 -05003034 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003035 TouchOcclusionInfo info;
3036 info.hasBlockingOcclusion = false;
3037 info.obscuringOpacity = 0;
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003038 info.obscuringUid = gui::Uid::INVALID;
3039 std::map<gui::Uid, float> opacityByUid;
chaviw98318de2021-05-19 16:45:23 -05003040 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003041 if (windowHandle == otherHandle) {
3042 break; // All future windows are below us. Exit early.
3043 }
chaviw98318de2021-05-19 16:45:23 -05003044 const WindowInfo* otherInfo = otherHandle->getInfo();
Bernardo Rufino1ff9d592021-01-18 16:58:57 +00003045 if (canBeObscuredBy(windowHandle, otherHandle) && otherInfo->frameContainsPoint(x, y) &&
3046 !haveSameApplicationToken(windowInfo, otherInfo)) {
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00003047 if (DEBUG_TOUCH_OCCLUSION) {
3048 info.debugInfo.push_back(
Harry Cutts101ee9b2023-07-06 18:04:14 +00003049 dumpWindowForTouchOcclusion(otherInfo, /*isTouchedWindow=*/false));
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00003050 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003051 // canBeObscuredBy() has returned true above, which means this window is untrusted, so
3052 // we perform the checks below to see if the touch can be propagated or not based on the
3053 // window's touch occlusion mode
3054 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::BLOCK_UNTRUSTED) {
3055 info.hasBlockingOcclusion = true;
3056 info.obscuringUid = otherInfo->ownerUid;
3057 info.obscuringPackage = otherInfo->packageName;
3058 break;
3059 }
3060 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::USE_OPACITY) {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003061 const auto uid = otherInfo->ownerUid;
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003062 float opacity =
3063 (opacityByUid.find(uid) == opacityByUid.end()) ? 0 : opacityByUid[uid];
3064 // Given windows A and B:
3065 // opacity(A, B) = 1 - [1 - opacity(A)] * [1 - opacity(B)]
3066 opacity = 1 - (1 - opacity) * (1 - otherInfo->alpha);
3067 opacityByUid[uid] = opacity;
3068 if (opacity > info.obscuringOpacity) {
3069 info.obscuringOpacity = opacity;
3070 info.obscuringUid = uid;
3071 info.obscuringPackage = otherInfo->packageName;
3072 }
3073 }
3074 }
3075 }
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00003076 if (DEBUG_TOUCH_OCCLUSION) {
Harry Cutts101ee9b2023-07-06 18:04:14 +00003077 info.debugInfo.push_back(dumpWindowForTouchOcclusion(windowInfo, /*isTouchedWindow=*/true));
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00003078 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003079 return info;
3080}
3081
chaviw98318de2021-05-19 16:45:23 -05003082std::string InputDispatcher::dumpWindowForTouchOcclusion(const WindowInfo* info,
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00003083 bool isTouchedWindow) const {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003084 return StringPrintf(INDENT2 "* %spackage=%s/%s, id=%" PRId32 ", mode=%s, alpha=%.2f, "
Prabir Pradhan51e7db02022-02-07 06:02:57 -08003085 "frame=[%" PRId32 ",%" PRId32 "][%" PRId32 ",%" PRId32
3086 "], touchableRegion=%s, window={%s}, inputConfig={%s}, "
3087 "hasToken=%s, applicationInfo.name=%s, applicationInfo.token=%s\n",
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08003088 isTouchedWindow ? "[TOUCHED] " : "", info->packageName.c_str(),
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003089 info->ownerUid.toString().c_str(), info->id,
Chavi Weingarten7f019192023-08-08 20:39:01 +00003090 toString(info->touchOcclusionMode).c_str(), info->alpha, info->frame.left,
3091 info->frame.top, info->frame.right, info->frame.bottom,
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003092 dumpRegion(info->touchableRegion).c_str(), info->name.c_str(),
3093 info->inputConfig.string().c_str(), toString(info->token != nullptr),
3094 info->applicationInfo.name.c_str(),
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07003095 binderToString(info->applicationInfo.token).c_str());
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00003096}
3097
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003098bool InputDispatcher::isTouchTrustedLocked(const TouchOcclusionInfo& occlusionInfo) const {
3099 if (occlusionInfo.hasBlockingOcclusion) {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003100 ALOGW("Untrusted touch due to occlusion by %s/%s", occlusionInfo.obscuringPackage.c_str(),
3101 occlusionInfo.obscuringUid.toString().c_str());
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003102 return false;
3103 }
3104 if (occlusionInfo.obscuringOpacity > mMaximumObscuringOpacityForTouch) {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003105 ALOGW("Untrusted touch due to occlusion by %s/%s (obscuring opacity = "
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003106 "%.2f, maximum allowed = %.2f)",
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003107 occlusionInfo.obscuringPackage.c_str(), occlusionInfo.obscuringUid.toString().c_str(),
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003108 occlusionInfo.obscuringOpacity, mMaximumObscuringOpacityForTouch);
3109 return false;
3110 }
3111 return true;
3112}
3113
chaviw98318de2021-05-19 16:45:23 -05003114bool InputDispatcher::isWindowObscuredAtPointLocked(const sp<WindowInfoHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003115 int32_t x, int32_t y) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003116 int32_t displayId = windowHandle->getInfo()->displayId;
chaviw98318de2021-05-19 16:45:23 -05003117 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
3118 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07003119 if (windowHandle == otherHandle) {
3120 break; // All future windows are below us. Exit early.
Michael Wrightd02c5b62014-02-10 15:10:22 -08003121 }
chaviw98318de2021-05-19 16:45:23 -05003122 const WindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07003123 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08003124 otherInfo->frameContainsPoint(x, y)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003125 return true;
3126 }
3127 }
3128 return false;
3129}
3130
chaviw98318de2021-05-19 16:45:23 -05003131bool InputDispatcher::isWindowObscuredLocked(const sp<WindowInfoHandle>& windowHandle) const {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07003132 int32_t displayId = windowHandle->getInfo()->displayId;
chaviw98318de2021-05-19 16:45:23 -05003133 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
3134 const WindowInfo* windowInfo = windowHandle->getInfo();
3135 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07003136 if (windowHandle == otherHandle) {
3137 break; // All future windows are below us. Exit early.
Michael Wrightcdcd8f22016-03-22 16:52:13 -07003138 }
chaviw98318de2021-05-19 16:45:23 -05003139 const WindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07003140 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08003141 otherInfo->overlaps(windowInfo)) {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07003142 return true;
3143 }
3144 }
3145 return false;
3146}
3147
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08003148std::string InputDispatcher::getApplicationWindowLabel(
chaviw98318de2021-05-19 16:45:23 -05003149 const InputApplicationHandle* applicationHandle, const sp<WindowInfoHandle>& windowHandle) {
Yi Kong9b14ac62018-07-17 13:48:38 -07003150 if (applicationHandle != nullptr) {
3151 if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07003152 return applicationHandle->getName() + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003153 } else {
3154 return applicationHandle->getName();
3155 }
Yi Kong9b14ac62018-07-17 13:48:38 -07003156 } else if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07003157 return windowHandle->getInfo()->applicationInfo.name + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003158 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003159 return "<unknown application or window>";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003160 }
3161}
3162
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003163void InputDispatcher::pokeUserActivityLocked(const EventEntry& eventEntry) {
Antonio Kantekf16f2832021-09-28 04:39:20 +00003164 if (!isUserActivityEvent(eventEntry)) {
3165 // Not poking user activity if the event type does not represent a user activity
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003166 return;
3167 }
Yeabkal Wubshitb8aadfa2024-01-17 17:03:42 -08003168
3169 const int32_t eventType = getUserActivityEventType(eventEntry);
3170 if (input_flags::rate_limit_user_activity_poke_in_dispatcher()) {
3171 // Note that we're directly getting the time diff between the current event and the previous
3172 // event. This is assuming that the first user event always happens at a timestamp that is
3173 // greater than `mMinTimeBetweenUserActivityPokes` (otherwise, the first user event will
3174 // wrongly be dropped). In real life, `mMinTimeBetweenUserActivityPokes` is a much smaller
3175 // value than the potential first user activity event time, so this is ok.
3176 std::chrono::nanoseconds timeSinceLastEvent =
3177 std::chrono::nanoseconds(eventEntry.eventTime - mLastUserActivityTimes[eventType]);
3178 if (timeSinceLastEvent < mMinTimeBetweenUserActivityPokes) {
3179 return;
3180 }
3181 }
3182
Tiger Huang721e26f2018-07-24 22:26:19 +08003183 int32_t displayId = getTargetDisplayId(eventEntry);
chaviw98318de2021-05-19 16:45:23 -05003184 sp<WindowInfoHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Josep del Riob3981622023-04-18 15:49:45 +00003185 const WindowInfo* windowDisablingUserActivityInfo = nullptr;
Tiger Huang721e26f2018-07-24 22:26:19 +08003186 if (focusedWindowHandle != nullptr) {
chaviw98318de2021-05-19 16:45:23 -05003187 const WindowInfo* info = focusedWindowHandle->getInfo();
Prabir Pradhan51e7db02022-02-07 06:02:57 -08003188 if (info->inputConfig.test(WindowInfo::InputConfig::DISABLE_USER_ACTIVITY)) {
Josep del Riob3981622023-04-18 15:49:45 +00003189 windowDisablingUserActivityInfo = info;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003190 }
3191 }
3192
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003193 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003194 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003195 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
3196 if (motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003197 return;
3198 }
Josep del Riob3981622023-04-18 15:49:45 +00003199 if (windowDisablingUserActivityInfo != nullptr) {
3200 if (DEBUG_DISPATCH_CYCLE) {
3201 ALOGD("Not poking user activity: disabled by window '%s'.",
3202 windowDisablingUserActivityInfo->name.c_str());
3203 }
3204 return;
3205 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003206 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003207 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003208 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003209 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
3210 if (keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003211 return;
3212 }
Josep del Riob3981622023-04-18 15:49:45 +00003213 // If the key code is unknown, we don't consider it user activity
3214 if (keyEntry.keyCode == AKEYCODE_UNKNOWN) {
3215 return;
3216 }
3217 // Don't inhibit events that were intercepted or are not passed to
3218 // the apps, like system shortcuts
3219 if (windowDisablingUserActivityInfo != nullptr &&
3220 keyEntry.interceptKeyResult != KeyEntry::InterceptKeyResult::SKIP &&
3221 keyEntry.policyFlags & POLICY_FLAG_PASS_TO_USER) {
3222 if (DEBUG_DISPATCH_CYCLE) {
3223 ALOGD("Not poking user activity: disabled by window '%s'.",
3224 windowDisablingUserActivityInfo->name.c_str());
3225 }
3226 return;
3227 }
3228
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003229 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003230 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00003231 default: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003232 LOG_ALWAYS_FATAL("%s events are not user activity",
Dominik Laskowski75788452021-02-09 18:51:25 -08003233 ftl::enum_string(eventEntry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003234 break;
3235 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003236 }
3237
Yeabkal Wubshitb8aadfa2024-01-17 17:03:42 -08003238 mLastUserActivityTimes[eventType] = eventEntry.eventTime;
Prabir Pradhancef936d2021-07-21 16:17:52 +00003239 auto command = [this, eventTime = eventEntry.eventTime, eventType, displayId]()
3240 REQUIRES(mLock) {
3241 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00003242 mPolicy.pokeUserActivity(eventTime, eventType, displayId);
Prabir Pradhancef936d2021-07-21 16:17:52 +00003243 };
3244 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003245}
3246
3247void InputDispatcher::prepareDispatchCycleLocked(nsecs_t currentTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003248 const std::shared_ptr<Connection>& connection,
Prabir Pradhan24047542023-11-02 17:14:59 +00003249 std::shared_ptr<const EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003250 const InputTarget& inputTarget) {
Prabir Pradhan2dac8b82023-09-06 01:11:51 +00003251 ATRACE_NAME_IF(ATRACE_ENABLED(),
3252 StringPrintf("prepareDispatchCycleLocked(inputChannel=%s, id=0x%" PRIx32 ")",
3253 connection->getInputChannelName().c_str(), eventEntry->id));
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003254 if (DEBUG_DISPATCH_CYCLE) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003255 ALOGD("channel '%s' ~ prepareDispatchCycle - flags=%s, "
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08003256 "globalScaleFactor=%f, pointerIds=%s %s",
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003257 connection->getInputChannelName().c_str(), inputTarget.flags.string().c_str(),
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08003258 inputTarget.globalScaleFactor, bitsetToString(inputTarget.pointerIds).c_str(),
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003259 inputTarget.getPointerInfoString().c_str());
3260 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003261
3262 // Skip this event if the connection status is not normal.
3263 // We don't want to enqueue additional outbound events if the connection is broken.
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003264 if (connection->status != Connection::Status::NORMAL) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003265 if (DEBUG_DISPATCH_CYCLE) {
3266 ALOGD("channel '%s' ~ Dropping event because the channel status is %s",
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003267 connection->getInputChannelName().c_str(),
3268 ftl::enum_string(connection->status).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003269 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003270 return;
3271 }
3272
3273 // Split a motion event if needed.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003274 if (inputTarget.flags.test(InputTarget::Flags::SPLIT)) {
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003275 LOG_ALWAYS_FATAL_IF(eventEntry->type != EventEntry::Type::MOTION,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003276 "Entry type %s should not have Flags::SPLIT",
Dominik Laskowski75788452021-02-09 18:51:25 -08003277 ftl::enum_string(eventEntry->type).c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003278
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003279 const MotionEntry& originalMotionEntry = static_cast<const MotionEntry&>(*eventEntry);
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07003280 if (inputTarget.pointerIds.count() != originalMotionEntry.getPointerCount()) {
Siarhei Vishniakou16e4fa02023-02-16 17:48:56 -08003281 if (!inputTarget.firstDownTimeInTarget.has_value()) {
3282 logDispatchStateLocked();
3283 LOG(FATAL) << "Splitting motion events requires a down time to be set for the "
3284 "target on connection "
3285 << connection->getInputChannelName() << " for "
3286 << originalMotionEntry.getDescription();
3287 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003288 std::unique_ptr<MotionEntry> splitMotionEntry =
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00003289 splitMotionEvent(originalMotionEntry, inputTarget.pointerIds,
3290 inputTarget.firstDownTimeInTarget.value());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003291 if (!splitMotionEntry) {
3292 return; // split event was dropped
3293 }
Arthur Hungb3307ee2021-10-14 10:57:37 +00003294 if (splitMotionEntry->action == AMOTION_EVENT_ACTION_CANCEL) {
3295 std::string reason = std::string("reason=pointer cancel on split window");
3296 android_log_event_list(LOGTAG_INPUT_CANCEL)
3297 << connection->getInputChannelName().c_str() << reason << LOG_ID_EVENTS;
3298 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003299 if (DEBUG_FOCUS) {
3300 ALOGD("channel '%s' ~ Split motion event.",
3301 connection->getInputChannelName().c_str());
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003302 logOutboundMotionDetails(" ", *splitMotionEntry);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003303 }
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003304 enqueueDispatchEntryAndStartDispatchCycleLocked(currentTime, connection,
3305 std::move(splitMotionEntry),
3306 inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003307 return;
3308 }
3309 }
3310
3311 // Not splitting. Enqueue dispatch entries for the event as is.
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003312 enqueueDispatchEntryAndStartDispatchCycleLocked(currentTime, connection, eventEntry,
3313 inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003314}
3315
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003316void InputDispatcher::enqueueDispatchEntryAndStartDispatchCycleLocked(
3317 nsecs_t currentTime, const std::shared_ptr<Connection>& connection,
3318 std::shared_ptr<const EventEntry> eventEntry, const InputTarget& inputTarget) {
Prabir Pradhan2dac8b82023-09-06 01:11:51 +00003319 ATRACE_NAME_IF(ATRACE_ENABLED(),
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003320 StringPrintf("enqueueDispatchEntryAndStartDispatchCycleLocked(inputChannel=%s, "
3321 "id=0x%" PRIx32 ")",
Prabir Pradhan2dac8b82023-09-06 01:11:51 +00003322 connection->getInputChannelName().c_str(), eventEntry->id));
Michael Wright3dd60e22019-03-27 22:06:44 +00003323
hongzuo liu95785e22022-09-06 02:51:35 +00003324 const bool wasEmpty = connection->outboundQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003325
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003326 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003327
3328 // If the outbound queue was previously empty, start the dispatch cycle going.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003329 if (wasEmpty && !connection->outboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003330 startDispatchCycleLocked(currentTime, connection);
3331 }
3332}
3333
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003334void InputDispatcher::enqueueDispatchEntryLocked(const std::shared_ptr<Connection>& connection,
Prabir Pradhan24047542023-11-02 17:14:59 +00003335 std::shared_ptr<const EventEntry> eventEntry,
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003336 const InputTarget& inputTarget) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003337 // This is a new event.
3338 // Enqueue a new dispatch entry onto the outbound queue for this connection.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003339 std::unique_ptr<DispatchEntry> dispatchEntry =
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003340 createDispatchEntry(inputTarget, eventEntry, inputTarget.flags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003341
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003342 // Use the eventEntry from dispatchEntry since the entry may have changed and can now be a
3343 // different EventEntry than what was passed in.
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003344 eventEntry = dispatchEntry->eventEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003345 // Apply target flags and update the connection's input state.
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003346 switch (eventEntry->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003347 case EventEntry::Type::KEY: {
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003348 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(*eventEntry);
3349 if (!connection->inputState.trackKey(keyEntry, keyEntry.flags)) {
Siarhei Vishniakouc94dafe2023-05-26 10:24:19 -07003350 LOG(WARNING) << "channel " << connection->getInputChannelName()
3351 << "~ dropping inconsistent event: " << *dispatchEntry;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003352 return; // skip the inconsistent event
3353 }
3354 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003355 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003356
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003357 case EventEntry::Type::MOTION: {
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003358 std::shared_ptr<const MotionEntry> resolvedMotion =
3359 std::static_pointer_cast<const MotionEntry>(eventEntry);
3360 {
3361 // Determine the resolved motion entry.
3362 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(*eventEntry);
3363 int32_t resolvedAction = motionEntry.action;
3364 int32_t resolvedFlags = motionEntry.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003365
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003366 if (inputTarget.dispatchMode == InputTarget::DispatchMode::OUTSIDE) {
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003367 resolvedAction = AMOTION_EVENT_ACTION_OUTSIDE;
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003368 } else if (inputTarget.dispatchMode == InputTarget::DispatchMode::HOVER_EXIT) {
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003369 resolvedAction = AMOTION_EVENT_ACTION_HOVER_EXIT;
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003370 } else if (inputTarget.dispatchMode == InputTarget::DispatchMode::HOVER_ENTER) {
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003371 resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003372 } else if (inputTarget.dispatchMode == InputTarget::DispatchMode::SLIPPERY_EXIT) {
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003373 resolvedAction = AMOTION_EVENT_ACTION_CANCEL;
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003374 } else if (inputTarget.dispatchMode == InputTarget::DispatchMode::SLIPPERY_ENTER) {
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003375 resolvedAction = AMOTION_EVENT_ACTION_DOWN;
3376 }
3377 if (resolvedAction == AMOTION_EVENT_ACTION_HOVER_MOVE &&
3378 !connection->inputState.isHovering(motionEntry.deviceId, motionEntry.source,
3379 motionEntry.displayId)) {
3380 if (DEBUG_DISPATCH_CYCLE) {
3381 LOG(DEBUG) << "channel '" << connection->getInputChannelName().c_str()
3382 << "' ~ enqueueDispatchEntryLocked: filling in missing hover "
3383 "enter event";
3384 }
3385 resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
3386 }
3387
3388 if (resolvedAction == AMOTION_EVENT_ACTION_CANCEL) {
3389 resolvedFlags |= AMOTION_EVENT_FLAG_CANCELED;
3390 }
3391 if (dispatchEntry->targetFlags.test(InputTarget::Flags::WINDOW_IS_OBSCURED)) {
3392 resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED;
3393 }
3394 if (dispatchEntry->targetFlags.test(
3395 InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED)) {
3396 resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
3397 }
3398
3399 dispatchEntry->resolvedFlags = resolvedFlags;
3400 if (resolvedAction != motionEntry.action) {
Siarhei Vishniakoue9ef6bc2023-12-21 19:47:20 -08003401 std::optional<std::vector<PointerProperties>> usingProperties;
3402 std::optional<std::vector<PointerCoords>> usingCoords;
3403 if (resolvedAction == AMOTION_EVENT_ACTION_HOVER_EXIT ||
3404 resolvedAction == AMOTION_EVENT_ACTION_CANCEL) {
3405 // This is a HOVER_EXIT or an ACTION_CANCEL event that was synthesized by
3406 // the dispatcher, and therefore the coordinates of this event are currently
3407 // incorrect. These events should use the coordinates of the last dispatched
3408 // ACTION_MOVE or HOVER_MOVE. We need to query InputState to get this data.
3409 const bool hovering = resolvedAction == AMOTION_EVENT_ACTION_HOVER_EXIT;
3410 std::optional<std::pair<std::vector<PointerProperties>,
3411 std::vector<PointerCoords>>>
3412 pointerInfo =
3413 connection->inputState.getPointersOfLastEvent(motionEntry,
3414 hovering);
3415 if (pointerInfo) {
3416 usingProperties = pointerInfo->first;
3417 usingCoords = pointerInfo->second;
3418 }
3419 }
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003420 // Generate a new MotionEntry with a new eventId using the resolved action and
3421 // flags.
Siarhei Vishniakoue9ef6bc2023-12-21 19:47:20 -08003422 resolvedMotion = std::make_shared<
3423 MotionEntry>(mIdGenerator.nextId(), motionEntry.injectionState,
3424 motionEntry.eventTime, motionEntry.deviceId,
3425 motionEntry.source, motionEntry.displayId,
3426 motionEntry.policyFlags, resolvedAction,
3427 motionEntry.actionButton, resolvedFlags,
3428 motionEntry.metaState, motionEntry.buttonState,
3429 motionEntry.classification, motionEntry.edgeFlags,
3430 motionEntry.xPrecision, motionEntry.yPrecision,
3431 motionEntry.xCursorPosition, motionEntry.yCursorPosition,
3432 motionEntry.downTime,
3433 usingProperties.value_or(motionEntry.pointerProperties),
3434 usingCoords.value_or(motionEntry.pointerCoords));
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003435 if (ATRACE_ENABLED()) {
3436 std::string message = StringPrintf("Transmute MotionEvent(id=0x%" PRIx32
3437 ") to MotionEvent(id=0x%" PRIx32 ").",
3438 motionEntry.id, resolvedMotion->id);
3439 ATRACE_NAME(message.c_str());
3440 }
3441
3442 // Set the resolved motion entry in the DispatchEntry.
3443 dispatchEntry->eventEntry = resolvedMotion;
3444 eventEntry = resolvedMotion;
3445 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003446 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003447
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07003448 // Check if we need to cancel any of the ongoing gestures. We don't support multiple
3449 // devices being active at the same time in the same window, so if a new device is
3450 // active, cancel the gesture from the old device.
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07003451 std::unique_ptr<EventEntry> cancelEvent =
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003452 connection->inputState.cancelConflictingInputStream(*resolvedMotion);
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07003453 if (cancelEvent != nullptr) {
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003454 LOG(INFO) << "Canceling pointers for device " << resolvedMotion->deviceId << " in "
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07003455 << connection->getInputChannelName() << " with event "
3456 << cancelEvent->getDescription();
3457 std::unique_ptr<DispatchEntry> cancelDispatchEntry =
3458 createDispatchEntry(inputTarget, std::move(cancelEvent),
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003459 ftl::Flags<InputTarget::Flags>());
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07003460
3461 // Send these cancel events to the queue before sending the event from the new
3462 // device.
3463 connection->outboundQueue.emplace_back(std::move(cancelDispatchEntry));
3464 }
3465
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003466 if (!connection->inputState.trackMotion(*resolvedMotion,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003467 dispatchEntry->resolvedFlags)) {
Siarhei Vishniakouc94dafe2023-05-26 10:24:19 -07003468 LOG(WARNING) << "channel " << connection->getInputChannelName()
3469 << "~ dropping inconsistent event: " << *dispatchEntry;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003470 return; // skip the inconsistent event
3471 }
3472
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003473 if ((resolvedMotion->flags & AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE) &&
3474 (resolvedMotion->policyFlags & POLICY_FLAG_TRUSTED)) {
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08003475 // Skip reporting pointer down outside focus to the policy.
3476 break;
3477 }
3478
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003479 dispatchPointerDownOutsideFocus(resolvedMotion->source, resolvedMotion->action,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003480 inputTarget.inputChannel->getConnectionToken());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003481
3482 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003483 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003484 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003485 case EventEntry::Type::TOUCH_MODE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08003486 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
3487 case EventEntry::Type::DRAG: {
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003488 break;
3489 }
Chris Yef59a2f42020-10-16 12:55:26 -07003490 case EventEntry::Type::SENSOR: {
3491 LOG_ALWAYS_FATAL("SENSOR events should not go to apps via input channel");
3492 break;
3493 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003494 case EventEntry::Type::CONFIGURATION_CHANGED:
3495 case EventEntry::Type::DEVICE_RESET: {
3496 LOG_ALWAYS_FATAL("%s events should not go to apps",
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003497 ftl::enum_string(eventEntry->type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003498 break;
3499 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003500 }
3501
3502 // Remember that we are waiting for this dispatch to complete.
3503 if (dispatchEntry->hasForegroundTarget()) {
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003504 incrementPendingForegroundDispatches(*eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003505 }
3506
3507 // Enqueue the dispatch entry.
Prabir Pradhan8c90d782023-09-15 21:16:44 +00003508 connection->outboundQueue.emplace_back(std::move(dispatchEntry));
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003509 traceOutboundQueueLength(*connection);
chaviw8c9cf542019-03-25 13:02:48 -07003510}
3511
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003512/**
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003513 * This function is for debugging and metrics collection. It has two roles.
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003514 *
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003515 * The first role is to log input interaction with windows, which helps determine what the user was
3516 * interacting with. For example, if user is touching launcher, we will see an input_interaction log
3517 * that user started interacting with launcher window, as well as any other window that received
3518 * that gesture, such as the wallpaper or other spy windows. A new input_interaction is only logged
3519 * when the set of tokens that received the event changes. It is not logged again as long as the
3520 * user is interacting with the same windows.
3521 *
3522 * The second role is to track input device activity for metrics collection. For each input event,
3523 * we report the set of UIDs that the input device interacted with to the policy. Unlike for the
3524 * input_interaction logs, the device interaction is reported even when the set of interaction
3525 * tokens do not change.
3526 *
3527 * For these purposes, we do not count ACTION_OUTSIDE, ACTION_UP and ACTION_CANCEL actions as
3528 * interaction. This includes up and cancel events for both keys and motions.
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003529 */
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003530void InputDispatcher::processInteractionsLocked(const EventEntry& entry,
3531 const std::vector<InputTarget>& targets) {
3532 int32_t deviceId;
3533 nsecs_t eventTime;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003534 // Skip ACTION_UP events, and all events other than keys and motions
3535 if (entry.type == EventEntry::Type::KEY) {
3536 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
3537 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
3538 return;
3539 }
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003540 deviceId = keyEntry.deviceId;
3541 eventTime = keyEntry.eventTime;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003542 } else if (entry.type == EventEntry::Type::MOTION) {
3543 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
3544 if (motionEntry.action == AMOTION_EVENT_ACTION_UP ||
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003545 motionEntry.action == AMOTION_EVENT_ACTION_CANCEL ||
3546 MotionEvent::getActionMasked(motionEntry.action) == AMOTION_EVENT_ACTION_POINTER_UP) {
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003547 return;
3548 }
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003549 deviceId = motionEntry.deviceId;
3550 eventTime = motionEntry.eventTime;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003551 } else {
3552 return; // Not a key or a motion
3553 }
3554
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003555 std::set<gui::Uid> interactionUids;
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07003556 std::unordered_set<sp<IBinder>, StrongPointerHash<IBinder>> newConnectionTokens;
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003557 std::vector<std::shared_ptr<Connection>> newConnections;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003558 for (const InputTarget& target : targets) {
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003559 if (target.dispatchMode == InputTarget::DispatchMode::OUTSIDE) {
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003560 continue; // Skip windows that receive ACTION_OUTSIDE
3561 }
3562
3563 sp<IBinder> token = target.inputChannel->getConnectionToken();
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003564 std::shared_ptr<Connection> connection = getConnectionLocked(token);
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003565 if (connection == nullptr) {
3566 continue;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003567 }
3568 newConnectionTokens.insert(std::move(token));
3569 newConnections.emplace_back(connection);
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003570 if (target.windowHandle) {
3571 interactionUids.emplace(target.windowHandle->getInfo()->ownerUid);
3572 }
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003573 }
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003574
3575 auto command = [this, deviceId, eventTime, uids = std::move(interactionUids)]()
3576 REQUIRES(mLock) {
3577 scoped_unlock unlock(mLock);
3578 mPolicy.notifyDeviceInteraction(deviceId, eventTime, uids);
3579 };
3580 postCommandLocked(std::move(command));
3581
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003582 if (newConnectionTokens == mInteractionConnectionTokens) {
3583 return; // no change
3584 }
3585 mInteractionConnectionTokens = newConnectionTokens;
3586
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003587 std::string targetList;
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003588 for (const std::shared_ptr<Connection>& connection : newConnections) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003589 targetList += connection->getWindowName() + ", ";
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003590 }
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003591 std::string message = "Interaction with: " + targetList;
3592 if (targetList.empty()) {
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003593 message += "<none>";
3594 }
3595 android_log_event_list(LOGTAG_INPUT_INTERACTION) << message << LOG_ID_EVENTS;
3596}
3597
chaviwfd6d3512019-03-25 13:23:49 -07003598void InputDispatcher::dispatchPointerDownOutsideFocus(uint32_t source, int32_t action,
Vishnu Nairad321cd2020-08-20 16:40:21 -07003599 const sp<IBinder>& token) {
chaviw8c9cf542019-03-25 13:02:48 -07003600 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
chaviwfd6d3512019-03-25 13:23:49 -07003601 uint32_t maskedSource = source & AINPUT_SOURCE_CLASS_MASK;
3602 if (maskedSource != AINPUT_SOURCE_CLASS_POINTER || maskedAction != AMOTION_EVENT_ACTION_DOWN) {
chaviw8c9cf542019-03-25 13:02:48 -07003603 return;
3604 }
3605
Vishnu Nairc519ff72021-01-21 08:23:08 -08003606 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07003607 if (focusedToken == token) {
3608 // ignore since token is focused
chaviw8c9cf542019-03-25 13:02:48 -07003609 return;
3610 }
3611
Prabir Pradhancef936d2021-07-21 16:17:52 +00003612 auto command = [this, token]() REQUIRES(mLock) {
3613 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00003614 mPolicy.onPointerDownOutsideFocus(token);
Prabir Pradhancef936d2021-07-21 16:17:52 +00003615 };
3616 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003617}
3618
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003619status_t InputDispatcher::publishMotionEvent(Connection& connection,
3620 DispatchEntry& dispatchEntry) const {
3621 const EventEntry& eventEntry = *(dispatchEntry.eventEntry);
3622 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
3623
3624 PointerCoords scaledCoords[MAX_POINTERS];
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07003625 const PointerCoords* usingCoords = motionEntry.pointerCoords.data();
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003626
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00003627 // TODO(b/316355518): Do not modify coords before dispatch.
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003628 // Set the X and Y offset and X and Y scale depending on the input source.
3629 if ((motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) &&
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003630 !(dispatchEntry.targetFlags.test(InputTarget::Flags::ZERO_COORDS))) {
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003631 float globalScaleFactor = dispatchEntry.globalScaleFactor;
3632 if (globalScaleFactor != 1.0f) {
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07003633 for (uint32_t i = 0; i < motionEntry.getPointerCount(); i++) {
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003634 scaledCoords[i] = motionEntry.pointerCoords[i];
3635 // Don't apply window scale here since we don't want scale to affect raw
3636 // coordinates. The scale will be sent back to the client and applied
3637 // later when requesting relative coordinates.
Harry Cutts33476232023-01-30 19:57:29 +00003638 scaledCoords[i].scale(globalScaleFactor, /*windowXScale=*/1, /*windowYScale=*/1);
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003639 }
3640 usingCoords = scaledCoords;
3641 }
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003642 } else if (dispatchEntry.targetFlags.test(InputTarget::Flags::ZERO_COORDS)) {
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003643 // We don't want the dispatch target to know the coordinates
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07003644 for (uint32_t i = 0; i < motionEntry.getPointerCount(); i++) {
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003645 scaledCoords[i].clear();
3646 }
3647 usingCoords = scaledCoords;
3648 }
3649
3650 std::array<uint8_t, 32> hmac = getSignature(motionEntry, dispatchEntry);
3651
3652 // Publish the motion event.
3653 return connection.inputPublisher
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003654 .publishMotionEvent(dispatchEntry.seq, motionEntry.id, motionEntry.deviceId,
3655 motionEntry.source, motionEntry.displayId, std::move(hmac),
3656 motionEntry.action, motionEntry.actionButton,
3657 dispatchEntry.resolvedFlags, motionEntry.edgeFlags,
3658 motionEntry.metaState, motionEntry.buttonState,
3659 motionEntry.classification, dispatchEntry.transform,
3660 motionEntry.xPrecision, motionEntry.yPrecision,
3661 motionEntry.xCursorPosition, motionEntry.yCursorPosition,
3662 dispatchEntry.rawTransform, motionEntry.downTime,
3663 motionEntry.eventTime, motionEntry.getPointerCount(),
3664 motionEntry.pointerProperties.data(), usingCoords);
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003665}
3666
Michael Wrightd02c5b62014-02-10 15:10:22 -08003667void InputDispatcher::startDispatchCycleLocked(nsecs_t currentTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003668 const std::shared_ptr<Connection>& connection) {
Prabir Pradhan2dac8b82023-09-06 01:11:51 +00003669 ATRACE_NAME_IF(ATRACE_ENABLED(),
3670 StringPrintf("startDispatchCycleLocked(inputChannel=%s)",
3671 connection->getInputChannelName().c_str()));
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003672 if (DEBUG_DISPATCH_CYCLE) {
3673 ALOGD("channel '%s' ~ startDispatchCycle", connection->getInputChannelName().c_str());
3674 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003675
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003676 while (connection->status == Connection::Status::NORMAL && !connection->outboundQueue.empty()) {
Prabir Pradhan8c90d782023-09-15 21:16:44 +00003677 std::unique_ptr<DispatchEntry>& dispatchEntry = connection->outboundQueue.front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003678 dispatchEntry->deliveryTime = currentTime;
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003679 const std::chrono::nanoseconds timeout = getDispatchingTimeoutLocked(connection);
Siarhei Vishniakou70622952020-07-30 11:17:23 -05003680 dispatchEntry->timeoutTime = currentTime + timeout.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003681
3682 // Publish the event.
3683 status_t status;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003684 const EventEntry& eventEntry = *(dispatchEntry->eventEntry);
3685 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003686 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003687 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
3688 std::array<uint8_t, 32> hmac = getSignature(keyEntry, *dispatchEntry);
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08003689 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07003690 LOG(INFO) << "Publishing " << *dispatchEntry << " to "
3691 << connection->getInputChannelName();
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08003692 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003693
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003694 // Publish the key event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003695 status = connection->inputPublisher
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003696 .publishKeyEvent(dispatchEntry->seq, keyEntry.id,
3697 keyEntry.deviceId, keyEntry.source,
3698 keyEntry.displayId, std::move(hmac),
3699 keyEntry.action, dispatchEntry->resolvedFlags,
3700 keyEntry.keyCode, keyEntry.scanCode,
3701 keyEntry.metaState, keyEntry.repeatCount,
3702 keyEntry.downTime, keyEntry.eventTime);
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00003703 if (mTracer) {
3704 mTracer->traceEventDispatch(*dispatchEntry, keyEntry.traceTracker.get());
3705 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003706 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003707 }
3708
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003709 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08003710 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07003711 LOG(INFO) << "Publishing " << *dispatchEntry << " to "
3712 << connection->getInputChannelName();
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08003713 }
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00003714 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003715 status = publishMotionEvent(*connection, *dispatchEntry);
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00003716 if (mTracer) {
3717 mTracer->traceEventDispatch(*dispatchEntry, motionEntry.traceTracker.get());
3718 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003719 break;
3720 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003721
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003722 case EventEntry::Type::FOCUS: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003723 const FocusEntry& focusEntry = static_cast<const FocusEntry&>(eventEntry);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003724 status = connection->inputPublisher.publishFocusEvent(dispatchEntry->seq,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003725 focusEntry.id,
Antonio Kantek3cfec7b2021-11-05 18:26:17 -07003726 focusEntry.hasFocus);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003727 break;
3728 }
3729
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003730 case EventEntry::Type::TOUCH_MODE_CHANGED: {
3731 const TouchModeEntry& touchModeEntry =
3732 static_cast<const TouchModeEntry&>(eventEntry);
3733 status = connection->inputPublisher
3734 .publishTouchModeEvent(dispatchEntry->seq, touchModeEntry.id,
3735 touchModeEntry.inTouchMode);
3736
3737 break;
3738 }
3739
Prabir Pradhan99987712020-11-10 18:43:05 -08003740 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
3741 const auto& captureEntry =
3742 static_cast<const PointerCaptureChangedEntry&>(eventEntry);
3743 status = connection->inputPublisher
3744 .publishCaptureEvent(dispatchEntry->seq, captureEntry.id,
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00003745 captureEntry.pointerCaptureRequest.enable);
Prabir Pradhan99987712020-11-10 18:43:05 -08003746 break;
3747 }
3748
arthurhungb89ccb02020-12-30 16:19:01 +08003749 case EventEntry::Type::DRAG: {
3750 const DragEntry& dragEntry = static_cast<const DragEntry&>(eventEntry);
3751 status = connection->inputPublisher.publishDragEvent(dispatchEntry->seq,
3752 dragEntry.id, dragEntry.x,
3753 dragEntry.y,
3754 dragEntry.isExiting);
3755 break;
3756 }
3757
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003758 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07003759 case EventEntry::Type::DEVICE_RESET:
3760 case EventEntry::Type::SENSOR: {
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003761 LOG_ALWAYS_FATAL("Should never start dispatch cycles for %s events",
Dominik Laskowski75788452021-02-09 18:51:25 -08003762 ftl::enum_string(eventEntry.type).c_str());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003763 return;
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003764 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003765 }
3766
3767 // Check the result.
3768 if (status) {
3769 if (status == WOULD_BLOCK) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003770 if (connection->waitQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003771 ALOGE("channel '%s' ~ Could not publish event because the pipe is full. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003772 "This is unexpected because the wait queue is empty, so the pipe "
3773 "should be empty and we shouldn't have any problems writing an "
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +00003774 "event to it, status=%s(%d)",
3775 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3776 status);
Harry Cutts33476232023-01-30 19:57:29 +00003777 abortBrokenDispatchCycleLocked(currentTime, connection, /*notify=*/true);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003778 } else {
3779 // Pipe is full and we are waiting for the app to finish process some events
3780 // before sending more events to it.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003781 if (DEBUG_DISPATCH_CYCLE) {
3782 ALOGD("channel '%s' ~ Could not publish event because the pipe is full, "
3783 "waiting for the application to catch up",
3784 connection->getInputChannelName().c_str());
3785 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003786 }
3787 } else {
3788 ALOGE("channel '%s' ~ Could not publish event due to an unexpected error, "
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +00003789 "status=%s(%d)",
3790 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3791 status);
Harry Cutts33476232023-01-30 19:57:29 +00003792 abortBrokenDispatchCycleLocked(currentTime, connection, /*notify=*/true);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003793 }
3794 return;
3795 }
3796
3797 // Re-enqueue the event on the wait queue.
Prabir Pradhan8c90d782023-09-15 21:16:44 +00003798 const nsecs_t timeoutTime = dispatchEntry->timeoutTime;
3799 connection->waitQueue.emplace_back(std::move(dispatchEntry));
3800 connection->outboundQueue.erase(connection->outboundQueue.begin());
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003801 traceOutboundQueueLength(*connection);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003802 if (connection->responsive) {
Prabir Pradhan8c90d782023-09-15 21:16:44 +00003803 mAnrTracker.insert(timeoutTime, connection->inputChannel->getConnectionToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003804 }
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003805 traceWaitQueueLength(*connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003806 }
3807}
3808
chaviw09c8d2d2020-08-24 15:48:26 -07003809std::array<uint8_t, 32> InputDispatcher::sign(const VerifiedInputEvent& event) const {
3810 size_t size;
3811 switch (event.type) {
3812 case VerifiedInputEvent::Type::KEY: {
3813 size = sizeof(VerifiedKeyEvent);
3814 break;
3815 }
3816 case VerifiedInputEvent::Type::MOTION: {
3817 size = sizeof(VerifiedMotionEvent);
3818 break;
3819 }
3820 }
3821 const uint8_t* start = reinterpret_cast<const uint8_t*>(&event);
3822 return mHmacKeyManager.sign(start, size);
3823}
3824
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003825const std::array<uint8_t, 32> InputDispatcher::getSignature(
3826 const MotionEntry& motionEntry, const DispatchEntry& dispatchEntry) const {
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003827 const int32_t actionMasked = MotionEvent::getActionMasked(motionEntry.action);
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003828 if (actionMasked != AMOTION_EVENT_ACTION_UP && actionMasked != AMOTION_EVENT_ACTION_DOWN) {
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003829 // Only sign events up and down events as the purely move events
3830 // are tied to their up/down counterparts so signing would be redundant.
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003831 return INVALID_HMAC;
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003832 }
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003833
3834 VerifiedMotionEvent verifiedEvent =
3835 verifiedMotionEventFromMotionEntry(motionEntry, dispatchEntry.rawTransform);
3836 verifiedEvent.actionMasked = actionMasked;
3837 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_MOTION_EVENT_FLAGS;
3838 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003839}
3840
3841const std::array<uint8_t, 32> InputDispatcher::getSignature(
3842 const KeyEntry& keyEntry, const DispatchEntry& dispatchEntry) const {
3843 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEntry(keyEntry);
3844 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_KEY_EVENT_FLAGS;
chaviw09c8d2d2020-08-24 15:48:26 -07003845 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003846}
3847
Michael Wrightd02c5b62014-02-10 15:10:22 -08003848void InputDispatcher::finishDispatchCycleLocked(nsecs_t currentTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003849 const std::shared_ptr<Connection>& connection,
3850 uint32_t seq, bool handled, nsecs_t consumeTime) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003851 if (DEBUG_DISPATCH_CYCLE) {
3852 ALOGD("channel '%s' ~ finishDispatchCycle - seq=%u, handled=%s",
3853 connection->getInputChannelName().c_str(), seq, toString(handled));
3854 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003855
Prabir Pradhan98ca4a22024-01-09 23:51:50 +00003856 if (connection->status != Connection::Status::NORMAL) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003857 return;
3858 }
3859
3860 // Notify other system components and prepare to start the next dispatch cycle.
Prabir Pradhancef936d2021-07-21 16:17:52 +00003861 auto command = [this, currentTime, connection, seq, handled, consumeTime]() REQUIRES(mLock) {
3862 doDispatchCycleFinishedCommand(currentTime, connection, seq, handled, consumeTime);
3863 };
3864 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003865}
3866
3867void InputDispatcher::abortBrokenDispatchCycleLocked(nsecs_t currentTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003868 const std::shared_ptr<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003869 bool notify) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003870 if (DEBUG_DISPATCH_CYCLE) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07003871 LOG(INFO) << "channel '" << connection->getInputChannelName() << "'~ " << __func__
3872 << " - notify=" << toString(notify);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003873 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003874
3875 // Clear the dispatch queues.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003876 drainDispatchQueue(connection->outboundQueue);
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003877 traceOutboundQueueLength(*connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003878 drainDispatchQueue(connection->waitQueue);
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003879 traceWaitQueueLength(*connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003880
3881 // The connection appears to be unrecoverably broken.
3882 // Ignore already broken or zombie connections.
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003883 if (connection->status == Connection::Status::NORMAL) {
3884 connection->status = Connection::Status::BROKEN;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003885
3886 if (notify) {
3887 // Notify other system components.
Prabir Pradhancef936d2021-07-21 16:17:52 +00003888 ALOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
3889 connection->getInputChannelName().c_str());
3890
3891 auto command = [this, connection]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00003892 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00003893 mPolicy.notifyInputChannelBroken(connection->inputChannel->getConnectionToken());
Prabir Pradhancef936d2021-07-21 16:17:52 +00003894 };
3895 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003896 }
3897 }
3898}
3899
Prabir Pradhan8c90d782023-09-15 21:16:44 +00003900void InputDispatcher::drainDispatchQueue(std::deque<std::unique_ptr<DispatchEntry>>& queue) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003901 while (!queue.empty()) {
Prabir Pradhan8c90d782023-09-15 21:16:44 +00003902 releaseDispatchEntry(std::move(queue.front()));
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003903 queue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003904 }
3905}
3906
Prabir Pradhan8c90d782023-09-15 21:16:44 +00003907void InputDispatcher::releaseDispatchEntry(std::unique_ptr<DispatchEntry> dispatchEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003908 if (dispatchEntry->hasForegroundTarget()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003909 decrementPendingForegroundDispatches(*(dispatchEntry->eventEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003910 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003911}
3912
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003913int InputDispatcher::handleReceiveCallback(int events, sp<IBinder> connectionToken) {
3914 std::scoped_lock _l(mLock);
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003915 std::shared_ptr<Connection> connection = getConnectionLocked(connectionToken);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003916 if (connection == nullptr) {
3917 ALOGW("Received looper callback for unknown input channel token %p. events=0x%x",
3918 connectionToken.get(), events);
3919 return 0; // remove the callback
3920 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003921
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003922 bool notify;
3923 if (!(events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP))) {
3924 if (!(events & ALOOPER_EVENT_INPUT)) {
3925 ALOGW("channel '%s' ~ Received spurious callback for unhandled poll event. "
3926 "events=0x%x",
3927 connection->getInputChannelName().c_str(), events);
3928 return 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003929 }
3930
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003931 nsecs_t currentTime = now();
3932 bool gotOne = false;
3933 status_t status = OK;
3934 for (;;) {
3935 Result<InputPublisher::ConsumerResponse> result =
3936 connection->inputPublisher.receiveConsumerResponse();
3937 if (!result.ok()) {
3938 status = result.error().code();
3939 break;
3940 }
3941
3942 if (std::holds_alternative<InputPublisher::Finished>(*result)) {
3943 const InputPublisher::Finished& finish =
3944 std::get<InputPublisher::Finished>(*result);
3945 finishDispatchCycleLocked(currentTime, connection, finish.seq, finish.handled,
3946 finish.consumeTime);
3947 } else if (std::holds_alternative<InputPublisher::Timeline>(*result)) {
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00003948 if (shouldReportMetricsForConnection(*connection)) {
3949 const InputPublisher::Timeline& timeline =
3950 std::get<InputPublisher::Timeline>(*result);
3951 mLatencyTracker
3952 .trackGraphicsLatency(timeline.inputEventId,
3953 connection->inputChannel->getConnectionToken(),
3954 std::move(timeline.graphicsTimeline));
3955 }
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003956 }
3957 gotOne = true;
3958 }
3959 if (gotOne) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00003960 runCommandsLockedInterruptable();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003961 if (status == WOULD_BLOCK) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003962 return 1;
3963 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003964 }
3965
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003966 notify = status != DEAD_OBJECT || !connection->monitor;
3967 if (notify) {
3968 ALOGE("channel '%s' ~ Failed to receive finished signal. status=%s(%d)",
3969 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3970 status);
3971 }
3972 } else {
3973 // Monitor channels are never explicitly unregistered.
3974 // We do it automatically when the remote endpoint is closed so don't warn about them.
3975 const bool stillHaveWindowHandle =
3976 getWindowHandleLocked(connection->inputChannel->getConnectionToken()) != nullptr;
3977 notify = !connection->monitor && stillHaveWindowHandle;
3978 if (notify) {
3979 ALOGW("channel '%s' ~ Consumer closed input channel or an error occurred. events=0x%x",
3980 connection->getInputChannelName().c_str(), events);
3981 }
3982 }
3983
3984 // Remove the channel.
3985 removeInputChannelLocked(connection->inputChannel->getConnectionToken(), notify);
3986 return 0; // remove the callback
Michael Wrightd02c5b62014-02-10 15:10:22 -08003987}
3988
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003989void InputDispatcher::synthesizeCancelationEventsForAllConnectionsLocked(
Michael Wrightd02c5b62014-02-10 15:10:22 -08003990 const CancelationOptions& options) {
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003991 for (const auto& [token, connection] : mConnectionsByToken) {
Siarhei Vishniakou2e2ea992020-12-15 02:57:19 +00003992 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003993 }
3994}
3995
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003996void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
Michael Wrightfa13dcf2015-06-12 13:25:11 +01003997 const CancelationOptions& options) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08003998 for (const auto& [_, monitors] : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003999 for (const Monitor& monitor : monitors) {
4000 synthesizeCancelationEventsForInputChannelLocked(monitor.inputChannel, options);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004001 }
Michael Wrightfa13dcf2015-06-12 13:25:11 +01004002 }
4003}
4004
Michael Wrightd02c5b62014-02-10 15:10:22 -08004005void InputDispatcher::synthesizeCancelationEventsForInputChannelLocked(
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004006 const std::shared_ptr<InputChannel>& channel, const CancelationOptions& options) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07004007 std::shared_ptr<Connection> connection = getConnectionLocked(channel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004008 if (connection == nullptr) {
4009 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004010 }
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004011
4012 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004013}
4014
4015void InputDispatcher::synthesizeCancelationEventsForConnectionLocked(
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07004016 const std::shared_ptr<Connection>& connection, const CancelationOptions& options) {
Prabir Pradhanb13da8f2024-01-09 23:10:13 +00004017 if (connection->status != Connection::Status::NORMAL) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004018 return;
4019 }
4020
4021 nsecs_t currentTime = now();
4022
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004023 std::vector<std::unique_ptr<EventEntry>> cancelationEvents =
Siarhei Vishniakou00fca7c2019-10-29 13:05:57 -07004024 connection->inputState.synthesizeCancelationEvents(currentTime, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004025
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004026 if (cancelationEvents.empty()) {
4027 return;
4028 }
Vaibhav Devmurari110ba322023-11-17 10:47:16 +00004029
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004030 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
4031 ALOGD("channel '%s' ~ Synthesized %zu cancelation events to bring channel back in sync "
Siarhei Vishniakou2e3e4432023-02-09 18:34:11 -08004032 "with reality: %s, mode=%s.",
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004033 connection->getInputChannelName().c_str(), cancelationEvents.size(), options.reason,
Siarhei Vishniakou2e3e4432023-02-09 18:34:11 -08004034 ftl::enum_string(options.mode).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004035 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08004036
Arthur Hungb3307ee2021-10-14 10:57:37 +00004037 std::string reason = std::string("reason=").append(options.reason);
4038 android_log_event_list(LOGTAG_INPUT_CANCEL)
4039 << connection->getInputChannelName().c_str() << reason << LOG_ID_EVENTS;
4040
hongzuo liu95785e22022-09-06 02:51:35 +00004041 const bool wasEmpty = connection->outboundQueue.empty();
Prabir Pradhan16463382023-10-12 23:03:19 +00004042 // The target to use if we don't find a window associated with the channel.
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00004043 const InputTarget fallbackTarget{.inputChannel = connection->inputChannel};
Prabir Pradhan16463382023-10-12 23:03:19 +00004044 const auto& token = connection->inputChannel->getConnectionToken();
hongzuo liu95785e22022-09-06 02:51:35 +00004045
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004046 for (size_t i = 0; i < cancelationEvents.size(); i++) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004047 std::unique_ptr<EventEntry> cancelationEventEntry = std::move(cancelationEvents[i]);
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00004048 std::vector<InputTarget> targets{};
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00004049
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004050 switch (cancelationEventEntry->type) {
4051 case EventEntry::Type::KEY: {
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00004052 const auto& keyEntry = static_cast<const KeyEntry&>(*cancelationEventEntry);
Prabir Pradhan16463382023-10-12 23:03:19 +00004053 const std::optional<int32_t> targetDisplay = keyEntry.displayId != ADISPLAY_ID_NONE
4054 ? std::make_optional(keyEntry.displayId)
4055 : std::nullopt;
4056 if (const auto& window = getWindowHandleLocked(token, targetDisplay); window) {
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00004057 addWindowTargetLocked(window, InputTarget::DispatchMode::AS_IS,
4058 /*targetFlags=*/{}, keyEntry.downTime, targets);
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00004059 } else {
4060 targets.emplace_back(fallbackTarget);
4061 }
4062 logOutboundKeyDetails("cancel - ", keyEntry);
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004063 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004064 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004065 case EventEntry::Type::MOTION: {
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00004066 const auto& motionEntry = static_cast<const MotionEntry&>(*cancelationEventEntry);
Prabir Pradhan16463382023-10-12 23:03:19 +00004067 const std::optional<int32_t> targetDisplay =
4068 motionEntry.displayId != ADISPLAY_ID_NONE
4069 ? std::make_optional(motionEntry.displayId)
4070 : std::nullopt;
4071 if (const auto& window = getWindowHandleLocked(token, targetDisplay); window) {
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00004072 std::bitset<MAX_POINTER_ID + 1> pointerIds;
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004073 for (uint32_t pointerIndex = 0; pointerIndex < motionEntry.getPointerCount();
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00004074 pointerIndex++) {
4075 pointerIds.set(motionEntry.pointerProperties[pointerIndex].id);
4076 }
Vaibhav Devmurari110ba322023-11-17 10:47:16 +00004077 if (mDragState && mDragState->dragWindow->getToken() == token &&
4078 pointerIds.test(mDragState->pointerId)) {
4079 LOG(INFO) << __func__
4080 << ": Canceling drag and drop because the pointers for the drag "
4081 "window are being canceled.";
4082 sendDropWindowCommandLocked(nullptr, /*x=*/0, /*y=*/0);
4083 mDragState.reset();
4084 }
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00004085 addPointerWindowTargetLocked(window, InputTarget::DispatchMode::AS_IS,
4086 ftl::Flags<InputTarget::Flags>(), pointerIds,
4087 motionEntry.downTime, targets);
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00004088 } else {
4089 targets.emplace_back(fallbackTarget);
4090 const auto it = mDisplayInfos.find(motionEntry.displayId);
4091 if (it != mDisplayInfos.end()) {
4092 targets.back().displayTransform = it->second.transform;
4093 targets.back().setDefaultPointerTransform(it->second.transform);
4094 }
4095 }
4096 logOutboundMotionDetails("cancel - ", motionEntry);
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004097 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004098 }
Prabir Pradhan99987712020-11-10 18:43:05 -08004099 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07004100 case EventEntry::Type::TOUCH_MODE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08004101 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
4102 case EventEntry::Type::DRAG: {
Prabir Pradhan99987712020-11-10 18:43:05 -08004103 LOG_ALWAYS_FATAL("Canceling %s events is not supported",
Dominik Laskowski75788452021-02-09 18:51:25 -08004104 ftl::enum_string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004105 break;
4106 }
4107 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07004108 case EventEntry::Type::DEVICE_RESET:
4109 case EventEntry::Type::SENSOR: {
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004110 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Dominik Laskowski75788452021-02-09 18:51:25 -08004111 ftl::enum_string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004112 break;
4113 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004114 }
4115
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00004116 if (targets.size() != 1) LOG(FATAL) << __func__ << ": InputTarget not created";
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00004117 enqueueDispatchEntryLocked(connection, std::move(cancelationEventEntry), targets[0]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004118 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004119
hongzuo liu95785e22022-09-06 02:51:35 +00004120 // If the outbound queue was previously empty, start the dispatch cycle going.
4121 if (wasEmpty && !connection->outboundQueue.empty()) {
4122 startDispatchCycleLocked(currentTime, connection);
4123 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004124}
4125
Svet Ganov5d3bc372020-01-26 23:11:07 -08004126void InputDispatcher::synthesizePointerDownEventsForConnectionLocked(
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07004127 const nsecs_t downTime, const std::shared_ptr<Connection>& connection,
Arthur Hungc539dbb2022-12-08 07:45:36 +00004128 ftl::Flags<InputTarget::Flags> targetFlags) {
Prabir Pradhan98ca4a22024-01-09 23:51:50 +00004129 if (connection->status != Connection::Status::NORMAL) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08004130 return;
4131 }
4132
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004133 std::vector<std::unique_ptr<EventEntry>> downEvents =
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00004134 connection->inputState.synthesizePointerDownEvents(downTime);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004135
4136 if (downEvents.empty()) {
4137 return;
4138 }
4139
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004140 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08004141 ALOGD("channel '%s' ~ Synthesized %zu down events to ensure consistent event stream.",
4142 connection->getInputChannelName().c_str(), downEvents.size());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004143 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08004144
chaviw98318de2021-05-19 16:45:23 -05004145 sp<WindowInfoHandle> windowHandle =
Svet Ganov5d3bc372020-01-26 23:11:07 -08004146 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
Svet Ganov5d3bc372020-01-26 23:11:07 -08004147
hongzuo liu95785e22022-09-06 02:51:35 +00004148 const bool wasEmpty = connection->outboundQueue.empty();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004149 for (std::unique_ptr<EventEntry>& downEventEntry : downEvents) {
Prabir Pradhan1c29a092023-09-21 10:29:29 +00004150 std::vector<InputTarget> targets{};
Svet Ganov5d3bc372020-01-26 23:11:07 -08004151 switch (downEventEntry->type) {
4152 case EventEntry::Type::MOTION: {
Prabir Pradhan1c29a092023-09-21 10:29:29 +00004153 const auto& motionEntry = static_cast<const MotionEntry&>(*downEventEntry);
4154 if (windowHandle != nullptr) {
4155 std::bitset<MAX_POINTER_ID + 1> pointerIds;
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004156 for (uint32_t pointerIndex = 0; pointerIndex < motionEntry.getPointerCount();
Prabir Pradhan1c29a092023-09-21 10:29:29 +00004157 pointerIndex++) {
4158 pointerIds.set(motionEntry.pointerProperties[pointerIndex].id);
4159 }
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00004160 addPointerWindowTargetLocked(windowHandle, InputTarget::DispatchMode::AS_IS,
4161 targetFlags, pointerIds, motionEntry.downTime,
4162 targets);
Prabir Pradhan1c29a092023-09-21 10:29:29 +00004163 } else {
4164 targets.emplace_back(InputTarget{.inputChannel = connection->inputChannel,
4165 .flags = targetFlags});
4166 const auto it = mDisplayInfos.find(motionEntry.displayId);
4167 if (it != mDisplayInfos.end()) {
4168 targets.back().displayTransform = it->second.transform;
4169 targets.back().setDefaultPointerTransform(it->second.transform);
4170 }
4171 }
4172 logOutboundMotionDetails("down - ", motionEntry);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004173 break;
4174 }
4175
4176 case EventEntry::Type::KEY:
4177 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07004178 case EventEntry::Type::TOUCH_MODE_CHANGED:
Svet Ganov5d3bc372020-01-26 23:11:07 -08004179 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08004180 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07004181 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08004182 case EventEntry::Type::SENSOR:
4183 case EventEntry::Type::DRAG: {
Svet Ganov5d3bc372020-01-26 23:11:07 -08004184 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Dominik Laskowski75788452021-02-09 18:51:25 -08004185 ftl::enum_string(downEventEntry->type).c_str());
Svet Ganov5d3bc372020-01-26 23:11:07 -08004186 break;
4187 }
4188 }
4189
Prabir Pradhan1c29a092023-09-21 10:29:29 +00004190 if (targets.size() != 1) LOG(FATAL) << __func__ << ": InputTarget not created";
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00004191 enqueueDispatchEntryLocked(connection, std::move(downEventEntry), targets[0]);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004192 }
4193
hongzuo liu95785e22022-09-06 02:51:35 +00004194 // If the outbound queue was previously empty, start the dispatch cycle going.
4195 if (wasEmpty && !connection->outboundQueue.empty()) {
4196 startDispatchCycleLocked(downTime, connection);
4197 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08004198}
4199
Arthur Hungc539dbb2022-12-08 07:45:36 +00004200void InputDispatcher::synthesizeCancelationEventsForWindowLocked(
4201 const sp<WindowInfoHandle>& windowHandle, const CancelationOptions& options) {
4202 if (windowHandle != nullptr) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07004203 std::shared_ptr<Connection> wallpaperConnection =
4204 getConnectionLocked(windowHandle->getToken());
Arthur Hungc539dbb2022-12-08 07:45:36 +00004205 if (wallpaperConnection != nullptr) {
4206 synthesizeCancelationEventsForConnectionLocked(wallpaperConnection, options);
4207 }
4208 }
4209}
4210
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004211std::unique_ptr<MotionEntry> InputDispatcher::splitMotionEvent(
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08004212 const MotionEntry& originalMotionEntry, std::bitset<MAX_POINTER_ID + 1> pointerIds,
4213 nsecs_t splitDownTime) {
4214 ALOG_ASSERT(pointerIds.any());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004215
4216 uint32_t splitPointerIndexMap[MAX_POINTERS];
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004217 std::vector<PointerProperties> splitPointerProperties;
4218 std::vector<PointerCoords> splitPointerCoords;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004219
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004220 uint32_t originalPointerCount = originalMotionEntry.getPointerCount();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004221 uint32_t splitPointerCount = 0;
4222
4223 for (uint32_t originalPointerIndex = 0; originalPointerIndex < originalPointerCount;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004224 originalPointerIndex++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004225 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07004226 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08004227 uint32_t pointerId = uint32_t(pointerProperties.id);
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08004228 if (pointerIds.test(pointerId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004229 splitPointerIndexMap[splitPointerCount] = originalPointerIndex;
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004230 splitPointerProperties.push_back(pointerProperties);
4231 splitPointerCoords.push_back(originalMotionEntry.pointerCoords[originalPointerIndex]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004232 splitPointerCount += 1;
4233 }
4234 }
4235
4236 if (splitPointerCount != pointerIds.count()) {
4237 // This is bad. We are missing some of the pointers that we expected to deliver.
4238 // Most likely this indicates that we received an ACTION_MOVE events that has
4239 // different pointer ids than we expected based on the previous ACTION_DOWN
4240 // or ACTION_POINTER_DOWN events that caused us to decide to split the pointers
4241 // in this way.
4242 ALOGW("Dropping split motion event because the pointer count is %d but "
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08004243 "we expected there to be %zu pointers. This probably means we received "
Siarhei Vishniakou16e4fa02023-02-16 17:48:56 -08004244 "a broken sequence of pointer ids from the input device: %s",
4245 splitPointerCount, pointerIds.count(), originalMotionEntry.getDescription().c_str());
Yi Kong9b14ac62018-07-17 13:48:38 -07004246 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004247 }
4248
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07004249 int32_t action = originalMotionEntry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004250 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004251 if (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN ||
4252 maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
Siarhei Vishniakou5b9766d2023-07-18 14:06:29 -07004253 int32_t originalPointerIndex = MotionEvent::getActionIndex(action);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004254 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07004255 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08004256 uint32_t pointerId = uint32_t(pointerProperties.id);
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08004257 if (pointerIds.test(pointerId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004258 if (pointerIds.count() == 1) {
4259 // The first/last pointer went down/up.
4260 action = maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004261 ? AMOTION_EVENT_ACTION_DOWN
arthurhungea3f4fc2020-12-21 23:18:53 +08004262 : (originalMotionEntry.flags & AMOTION_EVENT_FLAG_CANCELED) != 0
4263 ? AMOTION_EVENT_ACTION_CANCEL
4264 : AMOTION_EVENT_ACTION_UP;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004265 } else {
4266 // A secondary pointer went down/up.
4267 uint32_t splitPointerIndex = 0;
4268 while (pointerId != uint32_t(splitPointerProperties[splitPointerIndex].id)) {
4269 splitPointerIndex += 1;
4270 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004271 action = maskedAction |
4272 (splitPointerIndex << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004273 }
4274 } else {
4275 // An unrelated pointer changed.
4276 action = AMOTION_EVENT_ACTION_MOVE;
4277 }
4278 }
4279
Siarhei Vishniakou59e302b2023-06-05 08:04:53 -07004280 if (action == AMOTION_EVENT_ACTION_DOWN && splitDownTime != originalMotionEntry.eventTime) {
4281 logDispatchStateLocked();
4282 LOG_ALWAYS_FATAL("Split motion event has mismatching downTime and eventTime for "
4283 "ACTION_DOWN, motionEntry=%s, splitDownTime=%" PRId64,
4284 originalMotionEntry.getDescription().c_str(), splitDownTime);
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00004285 }
4286
Garfield Tanff1f1bb2020-01-28 13:24:04 -08004287 int32_t newId = mIdGenerator.nextId();
Prabir Pradhan2dac8b82023-09-06 01:11:51 +00004288 ATRACE_NAME_IF(ATRACE_ENABLED(),
4289 StringPrintf("Split MotionEvent(id=0x%" PRIx32 ") to MotionEvent(id=0x%" PRIx32
4290 ").",
4291 originalMotionEntry.id, newId));
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004292 std::unique_ptr<MotionEntry> splitMotionEntry =
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00004293 std::make_unique<MotionEntry>(newId, originalMotionEntry.injectionState,
4294 originalMotionEntry.eventTime,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004295 originalMotionEntry.deviceId, originalMotionEntry.source,
4296 originalMotionEntry.displayId,
4297 originalMotionEntry.policyFlags, action,
4298 originalMotionEntry.actionButton,
4299 originalMotionEntry.flags, originalMotionEntry.metaState,
4300 originalMotionEntry.buttonState,
4301 originalMotionEntry.classification,
4302 originalMotionEntry.edgeFlags,
4303 originalMotionEntry.xPrecision,
4304 originalMotionEntry.yPrecision,
4305 originalMotionEntry.xCursorPosition,
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00004306 originalMotionEntry.yCursorPosition, splitDownTime,
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004307 splitPointerProperties, splitPointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004308
Michael Wrightd02c5b62014-02-10 15:10:22 -08004309 return splitMotionEntry;
4310}
4311
Asmita Poddardd9a6cd2023-09-26 15:35:12 +00004312void InputDispatcher::notifyInputDevicesChanged(const NotifyInputDevicesChangedArgs& args) {
4313 std::scoped_lock _l(mLock);
4314 mLatencyTracker.setInputDevices(args.inputDeviceInfos);
4315}
4316
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004317void InputDispatcher::notifyConfigurationChanged(const NotifyConfigurationChangedArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004318 if (debugInboundEventDetails()) {
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004319 ALOGD("notifyConfigurationChanged - eventTime=%" PRId64, args.eventTime);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004320 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004321
Antonio Kantekf16f2832021-09-28 04:39:20 +00004322 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004323 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004324 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004325
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004326 std::unique_ptr<ConfigurationChangedEntry> newEntry =
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004327 std::make_unique<ConfigurationChangedEntry>(args.id, args.eventTime);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004328 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004329 } // release lock
4330
4331 if (needWake) {
4332 mLooper->wake();
4333 }
4334}
4335
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004336void InputDispatcher::notifyKey(const NotifyKeyArgs& args) {
Prabir Pradhan96282b02023-02-24 22:36:17 +00004337 ALOGD_IF(debugInboundEventDetails(),
4338 "notifyKey - id=%" PRIx32 ", eventTime=%" PRId64
4339 ", deviceId=%d, source=%s, displayId=%" PRId32
4340 "policyFlags=0x%x, action=%s, flags=0x%x, keyCode=%s, scanCode=0x%x, metaState=0x%x, "
4341 "downTime=%" PRId64,
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004342 args.id, args.eventTime, args.deviceId, inputEventSourceToString(args.source).c_str(),
4343 args.displayId, args.policyFlags, KeyEvent::actionToString(args.action), args.flags,
4344 KeyEvent::getLabel(args.keyCode), args.scanCode, args.metaState, args.downTime);
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004345 Result<void> keyCheck = validateKeyEvent(args.action);
4346 if (!keyCheck.ok()) {
4347 LOG(ERROR) << "invalid key event: " << keyCheck.error();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004348 return;
4349 }
4350
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004351 uint32_t policyFlags = args.policyFlags;
4352 int32_t flags = args.flags;
4353 int32_t metaState = args.metaState;
Siarhei Vishniakou622bd322018-10-29 18:02:27 -07004354 // InputDispatcher tracks and generates key repeats on behalf of
4355 // whatever notifies it, so repeatCount should always be set to 0
4356 constexpr int32_t repeatCount = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004357 if ((policyFlags & POLICY_FLAG_VIRTUAL) || (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY)) {
4358 policyFlags |= POLICY_FLAG_VIRTUAL;
4359 flags |= AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
4360 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004361 if (policyFlags & POLICY_FLAG_FUNCTION) {
4362 metaState |= AMETA_FUNCTION_ON;
4363 }
4364
4365 policyFlags |= POLICY_FLAG_TRUSTED;
4366
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004367 int32_t keyCode = args.keyCode;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004368 KeyEvent event;
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004369 event.initialize(args.id, args.deviceId, args.source, args.displayId, INVALID_HMAC, args.action,
4370 flags, keyCode, args.scanCode, metaState, repeatCount, args.downTime,
4371 args.eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004372
Michael Wright2b3c3302018-03-02 17:19:13 +00004373 android::base::Timer t;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004374 mPolicy.interceptKeyBeforeQueueing(event, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00004375 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4376 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004377 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00004378 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004379
Antonio Kantekf16f2832021-09-28 04:39:20 +00004380 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004381 { // acquire lock
4382 mLock.lock();
4383
4384 if (shouldSendKeyToInputFilterLocked(args)) {
4385 mLock.unlock();
4386
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004387 policyFlags |= POLICY_FLAG_FILTERED;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004388 if (!mPolicy.filterInputEvent(event, policyFlags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004389 return; // event was consumed by the filter
4390 }
4391
4392 mLock.lock();
4393 }
4394
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004395 std::unique_ptr<KeyEntry> newEntry =
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00004396 std::make_unique<KeyEntry>(args.id, /*injectionState=*/nullptr, args.eventTime,
4397 args.deviceId, args.source, args.displayId, policyFlags,
4398 args.action, flags, keyCode, args.scanCode, metaState,
4399 repeatCount, args.downTime);
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00004400 if (mTracer) {
4401 newEntry->traceTracker = mTracer->traceInboundEvent(*newEntry);
4402 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004403
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004404 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004405 mLock.unlock();
4406 } // release lock
4407
4408 if (needWake) {
4409 mLooper->wake();
4410 }
4411}
4412
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004413bool InputDispatcher::shouldSendKeyToInputFilterLocked(const NotifyKeyArgs& args) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004414 return mInputFilterEnabled;
4415}
4416
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004417void InputDispatcher::notifyMotion(const NotifyMotionArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004418 if (debugInboundEventDetails()) {
Prabir Pradhan96282b02023-02-24 22:36:17 +00004419 ALOGD("notifyMotion - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=%s, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004420 "displayId=%" PRId32 ", policyFlags=0x%x, "
Siarhei Vishniakou6ebd0692022-10-20 15:05:45 -07004421 "action=%s, actionButton=0x%x, flags=0x%x, metaState=0x%x, buttonState=0x%x, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004422 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, xCursorPosition=%f, "
4423 "yCursorPosition=%f, downTime=%" PRId64,
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004424 args.id, args.eventTime, args.deviceId, inputEventSourceToString(args.source).c_str(),
4425 args.displayId, args.policyFlags, MotionEvent::actionToString(args.action).c_str(),
4426 args.actionButton, args.flags, args.metaState, args.buttonState, args.edgeFlags,
4427 args.xPrecision, args.yPrecision, args.xCursorPosition, args.yCursorPosition,
4428 args.downTime);
Siarhei Vishniakou3218fc02023-06-15 20:41:02 -07004429 for (uint32_t i = 0; i < args.getPointerCount(); i++) {
Prabir Pradhan96282b02023-02-24 22:36:17 +00004430 ALOGD(" Pointer %d: id=%d, toolType=%s, x=%f, y=%f, pressure=%f, size=%f, "
4431 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, orientation=%f",
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004432 i, args.pointerProperties[i].id,
4433 ftl::enum_string(args.pointerProperties[i].toolType).c_str(),
4434 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
4435 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
4436 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
4437 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
4438 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
4439 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
4440 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
4441 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
4442 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004443 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004444 }
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004445
Siarhei Vishniakou3218fc02023-06-15 20:41:02 -07004446 Result<void> motionCheck =
4447 validateMotionEvent(args.action, args.actionButton, args.getPointerCount(),
4448 args.pointerProperties.data());
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004449 if (!motionCheck.ok()) {
4450 LOG(FATAL) << "Invalid event: " << args.dump() << "; reason: " << motionCheck.error();
4451 return;
4452 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004453
Siarhei Vishniakou5c02a712023-05-15 15:45:02 -07004454 if (DEBUG_VERIFY_EVENTS) {
4455 auto [it, _] =
4456 mVerifiersByDisplay.try_emplace(args.displayId,
4457 StringPrintf("display %" PRId32, args.displayId));
4458 Result<void> result =
Siarhei Vishniakou2d151ac2023-09-19 13:30:24 -07004459 it->second.processMovement(args.deviceId, args.source, args.action,
4460 args.getPointerCount(), args.pointerProperties.data(),
4461 args.pointerCoords.data(), args.flags);
Siarhei Vishniakou5c02a712023-05-15 15:45:02 -07004462 if (!result.ok()) {
4463 LOG(FATAL) << "Bad stream: " << result.error() << " caused by " << args.dump();
4464 }
4465 }
4466
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004467 uint32_t policyFlags = args.policyFlags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004468 policyFlags |= POLICY_FLAG_TRUSTED;
Michael Wright2b3c3302018-03-02 17:19:13 +00004469
4470 android::base::Timer t;
Yeabkal Wubshit88a90412023-12-21 18:23:04 -08004471 mPolicy.interceptMotionBeforeQueueing(args.displayId, args.source, args.action, args.eventTime,
4472 policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00004473 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4474 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004475 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00004476 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004477
Antonio Kantekf16f2832021-09-28 04:39:20 +00004478 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004479 { // acquire lock
4480 mLock.lock();
Siarhei Vishniakou5bf25d92023-02-08 15:43:38 -08004481 if (!(policyFlags & POLICY_FLAG_PASS_TO_USER)) {
4482 // Set the flag anyway if we already have an ongoing gesture. That would allow us to
4483 // complete the processing of the current stroke.
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004484 const auto touchStateIt = mTouchStatesByDisplay.find(args.displayId);
Siarhei Vishniakou5bf25d92023-02-08 15:43:38 -08004485 if (touchStateIt != mTouchStatesByDisplay.end()) {
4486 const TouchState& touchState = touchStateIt->second;
Linnan Li907ae732023-09-05 17:14:21 +08004487 if (touchState.hasTouchingPointers(args.deviceId) ||
4488 touchState.hasHoveringPointers(args.deviceId)) {
Siarhei Vishniakou5bf25d92023-02-08 15:43:38 -08004489 policyFlags |= POLICY_FLAG_PASS_TO_USER;
4490 }
4491 }
4492 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004493
4494 if (shouldSendMotionToInputFilterLocked(args)) {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004495 ui::Transform displayTransform;
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004496 if (const auto it = mDisplayInfos.find(args.displayId); it != mDisplayInfos.end()) {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004497 displayTransform = it->second.transform;
4498 }
4499
Michael Wrightd02c5b62014-02-10 15:10:22 -08004500 mLock.unlock();
4501
4502 MotionEvent event;
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004503 event.initialize(args.id, args.deviceId, args.source, args.displayId, INVALID_HMAC,
4504 args.action, args.actionButton, args.flags, args.edgeFlags,
4505 args.metaState, args.buttonState, args.classification,
4506 displayTransform, args.xPrecision, args.yPrecision,
4507 args.xCursorPosition, args.yCursorPosition, displayTransform,
Siarhei Vishniakou3218fc02023-06-15 20:41:02 -07004508 args.downTime, args.eventTime, args.getPointerCount(),
4509 args.pointerProperties.data(), args.pointerCoords.data());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004510
4511 policyFlags |= POLICY_FLAG_FILTERED;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004512 if (!mPolicy.filterInputEvent(event, policyFlags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004513 return; // event was consumed by the filter
4514 }
4515
4516 mLock.lock();
4517 }
4518
4519 // Just enqueue a new motion event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004520 std::unique_ptr<MotionEntry> newEntry =
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00004521 std::make_unique<MotionEntry>(args.id, /*injectionState=*/nullptr, args.eventTime,
4522 args.deviceId, args.source, args.displayId,
4523 policyFlags, args.action, args.actionButton,
4524 args.flags, args.metaState, args.buttonState,
4525 args.classification, args.edgeFlags, args.xPrecision,
4526 args.yPrecision, args.xCursorPosition,
4527 args.yCursorPosition, args.downTime,
4528 args.pointerProperties, args.pointerCoords);
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00004529 if (mTracer) {
4530 newEntry->traceTracker = mTracer->traceInboundEvent(*newEntry);
4531 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004532
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004533 if (args.id != android::os::IInputConstants::INVALID_INPUT_EVENT_ID &&
4534 IdGenerator::getSource(args.id) == IdGenerator::Source::INPUT_READER &&
Siarhei Vishniakou363e7292021-07-09 03:22:42 +00004535 !mInputFilterEnabled) {
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004536 const bool isDown = args.action == AMOTION_EVENT_ACTION_DOWN;
Asmita Poddardd9a6cd2023-09-26 15:35:12 +00004537 std::set<InputDeviceUsageSource> sources = getUsageSourcesForMotionArgs(args);
4538 mLatencyTracker.trackListener(args.id, isDown, args.eventTime, args.readTime,
4539 args.deviceId, sources);
Siarhei Vishniakou363e7292021-07-09 03:22:42 +00004540 }
4541
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004542 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004543 mLock.unlock();
4544 } // release lock
4545
4546 if (needWake) {
4547 mLooper->wake();
4548 }
4549}
4550
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004551void InputDispatcher::notifySensor(const NotifySensorArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004552 if (debugInboundEventDetails()) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004553 ALOGD("notifySensor - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=0x%x, "
4554 " sensorType=%s",
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004555 args.id, args.eventTime, args.deviceId, args.source,
4556 ftl::enum_string(args.sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004557 }
Chris Yef59a2f42020-10-16 12:55:26 -07004558
Antonio Kantekf16f2832021-09-28 04:39:20 +00004559 bool needWake = false;
Chris Yef59a2f42020-10-16 12:55:26 -07004560 { // acquire lock
4561 mLock.lock();
4562
4563 // Just enqueue a new sensor event.
4564 std::unique_ptr<SensorEntry> newEntry =
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004565 std::make_unique<SensorEntry>(args.id, args.eventTime, args.deviceId, args.source,
4566 /* policyFlags=*/0, args.hwTimestamp, args.sensorType,
4567 args.accuracy, args.accuracyChanged, args.values);
Chris Yef59a2f42020-10-16 12:55:26 -07004568
4569 needWake = enqueueInboundEventLocked(std::move(newEntry));
4570 mLock.unlock();
4571 } // release lock
4572
4573 if (needWake) {
4574 mLooper->wake();
4575 }
4576}
4577
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004578void InputDispatcher::notifyVibratorState(const NotifyVibratorStateArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004579 if (debugInboundEventDetails()) {
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004580 ALOGD("notifyVibratorState - eventTime=%" PRId64 ", device=%d, isOn=%d", args.eventTime,
4581 args.deviceId, args.isOn);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004582 }
Prabir Pradhana41d2442023-04-20 21:30:40 +00004583 mPolicy.notifyVibratorState(args.deviceId, args.isOn);
Chris Yefb552902021-02-03 17:18:37 -08004584}
4585
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004586bool InputDispatcher::shouldSendMotionToInputFilterLocked(const NotifyMotionArgs& args) {
Jackal Guof9696682018-10-05 12:23:23 +08004587 return mInputFilterEnabled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004588}
4589
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004590void InputDispatcher::notifySwitch(const NotifySwitchArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004591 if (debugInboundEventDetails()) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004592 ALOGD("notifySwitch - eventTime=%" PRId64 ", policyFlags=0x%x, switchValues=0x%08x, "
4593 "switchMask=0x%08x",
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004594 args.eventTime, args.policyFlags, args.switchValues, args.switchMask);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004595 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004596
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004597 uint32_t policyFlags = args.policyFlags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004598 policyFlags |= POLICY_FLAG_TRUSTED;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004599 mPolicy.notifySwitch(args.eventTime, args.switchValues, args.switchMask, policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004600}
4601
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004602void InputDispatcher::notifyDeviceReset(const NotifyDeviceResetArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004603 if (debugInboundEventDetails()) {
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004604 ALOGD("notifyDeviceReset - eventTime=%" PRId64 ", deviceId=%d", args.eventTime,
4605 args.deviceId);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004606 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004607
Antonio Kantekf16f2832021-09-28 04:39:20 +00004608 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004609 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004610 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004611
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004612 std::unique_ptr<DeviceResetEntry> newEntry =
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004613 std::make_unique<DeviceResetEntry>(args.id, args.eventTime, args.deviceId);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004614 needWake = enqueueInboundEventLocked(std::move(newEntry));
Siarhei Vishniakou1160ecd2023-06-28 15:57:47 -07004615
4616 for (auto& [_, verifier] : mVerifiersByDisplay) {
4617 verifier.resetDevice(args.deviceId);
4618 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004619 } // release lock
4620
4621 if (needWake) {
4622 mLooper->wake();
4623 }
4624}
4625
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004626void InputDispatcher::notifyPointerCaptureChanged(const NotifyPointerCaptureChangedArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004627 if (debugInboundEventDetails()) {
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004628 ALOGD("notifyPointerCaptureChanged - eventTime=%" PRId64 ", enabled=%s", args.eventTime,
4629 args.request.enable ? "true" : "false");
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004630 }
Prabir Pradhan7e186182020-11-10 13:56:45 -08004631
Antonio Kantekf16f2832021-09-28 04:39:20 +00004632 bool needWake = false;
Prabir Pradhan99987712020-11-10 18:43:05 -08004633 { // acquire lock
4634 std::scoped_lock _l(mLock);
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004635 auto entry =
4636 std::make_unique<PointerCaptureChangedEntry>(args.id, args.eventTime, args.request);
Prabir Pradhan99987712020-11-10 18:43:05 -08004637 needWake = enqueueInboundEventLocked(std::move(entry));
4638 } // release lock
4639
4640 if (needWake) {
4641 mLooper->wake();
4642 }
Prabir Pradhan7e186182020-11-10 13:56:45 -08004643}
4644
Prabir Pradhan5735a322022-04-11 17:23:34 +00004645InputEventInjectionResult InputDispatcher::injectInputEvent(const InputEvent* event,
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00004646 std::optional<gui::Uid> targetUid,
Prabir Pradhan5735a322022-04-11 17:23:34 +00004647 InputEventInjectionSync syncMode,
4648 std::chrono::milliseconds timeout,
4649 uint32_t policyFlags) {
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004650 Result<void> eventValidation = validateInputEvent(*event);
4651 if (!eventValidation.ok()) {
4652 LOG(INFO) << "Injection failed: invalid event: " << eventValidation.error();
4653 return InputEventInjectionResult::FAILED;
4654 }
4655
Prabir Pradhan65613802023-02-22 23:36:58 +00004656 if (debugInboundEventDetails()) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07004657 LOG(INFO) << __func__ << ": targetUid=" << toString(targetUid, &uidString)
4658 << ", syncMode=" << ftl::enum_string(syncMode) << ", timeout=" << timeout.count()
4659 << "ms, policyFlags=0x" << std::hex << policyFlags << std::dec
4660 << ", event=" << *event;
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004661 }
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07004662 nsecs_t endTime = now() + std::chrono::duration_cast<std::chrono::nanoseconds>(timeout).count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004663
Prabir Pradhan5735a322022-04-11 17:23:34 +00004664 policyFlags |= POLICY_FLAG_INJECTED | POLICY_FLAG_TRUSTED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004665
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004666 // For all injected events, set device id = VIRTUAL_KEYBOARD_ID. The only exception is events
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004667 // that have gone through the InputFilter. If the event passed through the InputFilter, assign
4668 // the provided device id. If the InputFilter is accessibility, and it modifies or synthesizes
4669 // the injected event, it is responsible for setting POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY.
4670 // For those events, we will set FLAG_IS_ACCESSIBILITY_EVENT to allow apps to distinguish them
4671 // from events that originate from actual hardware.
Siarhei Vishniakouf4043212023-09-18 19:33:03 -07004672 DeviceId resolvedDeviceId = VIRTUAL_KEYBOARD_ID;
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004673 if (policyFlags & POLICY_FLAG_FILTERED) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004674 resolvedDeviceId = event->getDeviceId();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004675 }
4676
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00004677 const bool isAsync = syncMode == InputEventInjectionSync::NONE;
4678 auto injectionState = std::make_shared<InjectionState>(targetUid, isAsync);
4679
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004680 std::queue<std::unique_ptr<EventEntry>> injectedEntries;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004681 switch (event->getType()) {
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004682 case InputEventType::KEY: {
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004683 const KeyEvent& incomingKey = static_cast<const KeyEvent&>(*event);
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004684 const int32_t action = incomingKey.getAction();
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004685 int32_t flags = incomingKey.getFlags();
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004686 if (policyFlags & POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY) {
4687 flags |= AKEY_EVENT_FLAG_IS_ACCESSIBILITY_EVENT;
4688 }
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004689 int32_t keyCode = incomingKey.getKeyCode();
4690 int32_t metaState = incomingKey.getMetaState();
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004691 KeyEvent keyEvent;
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004692 keyEvent.initialize(incomingKey.getId(), resolvedDeviceId, incomingKey.getSource(),
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004693 incomingKey.getDisplayId(), INVALID_HMAC, action, flags, keyCode,
4694 incomingKey.getScanCode(), metaState, incomingKey.getRepeatCount(),
4695 incomingKey.getDownTime(), incomingKey.getEventTime());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004696
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004697 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
4698 policyFlags |= POLICY_FLAG_VIRTUAL;
Michael Wright2b3c3302018-03-02 17:19:13 +00004699 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004700
4701 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
4702 android::base::Timer t;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004703 mPolicy.interceptKeyBeforeQueueing(keyEvent, /*byref*/ policyFlags);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004704 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4705 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
4706 std::to_string(t.duration().count()).c_str());
4707 }
4708 }
4709
4710 mLock.lock();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004711 std::unique_ptr<KeyEntry> injectedEntry =
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00004712 std::make_unique<KeyEntry>(incomingKey.getId(), injectionState,
4713 incomingKey.getEventTime(), resolvedDeviceId,
4714 incomingKey.getSource(), incomingKey.getDisplayId(),
4715 policyFlags, action, flags, keyCode,
4716 incomingKey.getScanCode(), metaState,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004717 incomingKey.getRepeatCount(),
4718 incomingKey.getDownTime());
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00004719 if (mTracer) {
4720 injectedEntry->traceTracker = mTracer->traceInboundEvent(*injectedEntry);
4721 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004722 injectedEntries.push(std::move(injectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004723 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004724 }
4725
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004726 case InputEventType::MOTION: {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004727 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(*event);
Prabir Pradhanaa561d12021-09-24 06:57:33 -07004728 const bool isPointerEvent =
4729 isFromSource(event->getSource(), AINPUT_SOURCE_CLASS_POINTER);
4730 // If a pointer event has no displayId specified, inject it to the default display.
4731 const uint32_t displayId = isPointerEvent && (event->getDisplayId() == ADISPLAY_ID_NONE)
4732 ? ADISPLAY_ID_DEFAULT
4733 : event->getDisplayId();
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004734 int32_t flags = motionEvent.getFlags();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004735
4736 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004737 nsecs_t eventTime = motionEvent.getEventTime();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004738 android::base::Timer t;
Yeabkal Wubshit88a90412023-12-21 18:23:04 -08004739 mPolicy.interceptMotionBeforeQueueing(displayId, motionEvent.getSource(),
4740 motionEvent.getAction(), eventTime,
4741 /*byref*/ policyFlags);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004742 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4743 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
4744 std::to_string(t.duration().count()).c_str());
4745 }
4746 }
4747
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004748 if (policyFlags & POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY) {
4749 flags |= AMOTION_EVENT_FLAG_IS_ACCESSIBILITY_EVENT;
4750 }
4751
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004752 mLock.lock();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004753 const nsecs_t* sampleEventTimes = motionEvent.getSampleEventTimes();
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004754 const size_t pointerCount = motionEvent.getPointerCount();
4755 const std::vector<PointerProperties>
4756 pointerProperties(motionEvent.getPointerProperties(),
4757 motionEvent.getPointerProperties() + pointerCount);
4758
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004759 const PointerCoords* samplePointerCoords = motionEvent.getSamplePointerCoords();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004760 std::unique_ptr<MotionEntry> injectedEntry =
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00004761 std::make_unique<MotionEntry>(motionEvent.getId(), injectionState,
4762 *sampleEventTimes, resolvedDeviceId,
4763 motionEvent.getSource(), displayId, policyFlags,
4764 motionEvent.getAction(),
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004765 motionEvent.getActionButton(), flags,
4766 motionEvent.getMetaState(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004767 motionEvent.getButtonState(),
4768 motionEvent.getClassification(),
4769 motionEvent.getEdgeFlags(),
4770 motionEvent.getXPrecision(),
4771 motionEvent.getYPrecision(),
4772 motionEvent.getRawXCursorPosition(),
4773 motionEvent.getRawYCursorPosition(),
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004774 motionEvent.getDownTime(), pointerProperties,
4775 std::vector<PointerCoords>(samplePointerCoords,
4776 samplePointerCoords +
4777 pointerCount));
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004778 transformMotionEntryForInjectionLocked(*injectedEntry, motionEvent.getTransform());
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00004779 if (mTracer) {
4780 injectedEntry->traceTracker = mTracer->traceInboundEvent(*injectedEntry);
4781 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004782 injectedEntries.push(std::move(injectedEntry));
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004783 for (size_t i = motionEvent.getHistorySize(); i > 0; i--) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004784 sampleEventTimes += 1;
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004785 samplePointerCoords += motionEvent.getPointerCount();
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004786 std::unique_ptr<MotionEntry> nextInjectedEntry = std::make_unique<
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00004787 MotionEntry>(motionEvent.getId(), injectionState, *sampleEventTimes,
4788 resolvedDeviceId, motionEvent.getSource(), displayId,
4789 policyFlags, motionEvent.getAction(),
4790 motionEvent.getActionButton(), flags,
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004791 motionEvent.getMetaState(), motionEvent.getButtonState(),
4792 motionEvent.getClassification(), motionEvent.getEdgeFlags(),
4793 motionEvent.getXPrecision(), motionEvent.getYPrecision(),
4794 motionEvent.getRawXCursorPosition(),
4795 motionEvent.getRawYCursorPosition(), motionEvent.getDownTime(),
4796 pointerProperties,
4797 std::vector<PointerCoords>(samplePointerCoords,
4798 samplePointerCoords +
4799 pointerCount));
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004800 transformMotionEntryForInjectionLocked(*nextInjectedEntry,
4801 motionEvent.getTransform());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004802 injectedEntries.push(std::move(nextInjectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004803 }
4804 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004805 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004806
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004807 default:
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004808 LOG(WARNING) << "Cannot inject " << ftl::enum_string(event->getType()) << " events";
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004809 return InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004810 }
4811
Michael Wrightd02c5b62014-02-10 15:10:22 -08004812 bool needWake = false;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004813 while (!injectedEntries.empty()) {
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08004814 if (DEBUG_INJECTION) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07004815 LOG(INFO) << "Injecting " << injectedEntries.front()->getDescription();
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08004816 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004817 needWake |= enqueueInboundEventLocked(std::move(injectedEntries.front()));
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004818 injectedEntries.pop();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004819 }
4820
4821 mLock.unlock();
4822
4823 if (needWake) {
4824 mLooper->wake();
4825 }
4826
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004827 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004828 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004829 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004830
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004831 if (syncMode == InputEventInjectionSync::NONE) {
4832 injectionResult = InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004833 } else {
4834 for (;;) {
4835 injectionResult = injectionState->injectionResult;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004836 if (injectionResult != InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004837 break;
4838 }
4839
4840 nsecs_t remainingTimeout = endTime - now();
4841 if (remainingTimeout <= 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004842 if (DEBUG_INJECTION) {
4843 ALOGD("injectInputEvent - Timed out waiting for injection result "
4844 "to become available.");
4845 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004846 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004847 break;
4848 }
4849
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004850 mInjectionResultAvailable.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004851 }
4852
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004853 if (injectionResult == InputEventInjectionResult::SUCCEEDED &&
4854 syncMode == InputEventInjectionSync::WAIT_FOR_FINISHED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004855 while (injectionState->pendingForegroundDispatches != 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004856 if (DEBUG_INJECTION) {
4857 ALOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
4858 injectionState->pendingForegroundDispatches);
4859 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004860 nsecs_t remainingTimeout = endTime - now();
4861 if (remainingTimeout <= 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004862 if (DEBUG_INJECTION) {
4863 ALOGD("injectInputEvent - Timed out waiting for pending foreground "
4864 "dispatches to finish.");
4865 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004866 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004867 break;
4868 }
4869
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004870 mInjectionSyncFinished.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004871 }
4872 }
4873 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004874 } // release lock
4875
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004876 if (DEBUG_INJECTION) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07004877 LOG(INFO) << "injectInputEvent - Finished with result "
4878 << ftl::enum_string(injectionResult);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004879 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004880
4881 return injectionResult;
4882}
4883
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004884std::unique_ptr<VerifiedInputEvent> InputDispatcher::verifyInputEvent(const InputEvent& event) {
Gang Wange9087892020-01-07 12:17:14 -05004885 std::array<uint8_t, 32> calculatedHmac;
4886 std::unique_ptr<VerifiedInputEvent> result;
4887 switch (event.getType()) {
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004888 case InputEventType::KEY: {
Gang Wange9087892020-01-07 12:17:14 -05004889 const KeyEvent& keyEvent = static_cast<const KeyEvent&>(event);
4890 VerifiedKeyEvent verifiedKeyEvent = verifiedKeyEventFromKeyEvent(keyEvent);
4891 result = std::make_unique<VerifiedKeyEvent>(verifiedKeyEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004892 calculatedHmac = sign(verifiedKeyEvent);
Gang Wange9087892020-01-07 12:17:14 -05004893 break;
4894 }
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004895 case InputEventType::MOTION: {
Gang Wange9087892020-01-07 12:17:14 -05004896 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(event);
4897 VerifiedMotionEvent verifiedMotionEvent =
4898 verifiedMotionEventFromMotionEvent(motionEvent);
4899 result = std::make_unique<VerifiedMotionEvent>(verifiedMotionEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004900 calculatedHmac = sign(verifiedMotionEvent);
Gang Wange9087892020-01-07 12:17:14 -05004901 break;
4902 }
4903 default: {
4904 ALOGE("Cannot verify events of type %" PRId32, event.getType());
4905 return nullptr;
4906 }
4907 }
4908 if (calculatedHmac == INVALID_HMAC) {
4909 return nullptr;
4910 }
tyiu1573a672023-02-21 22:38:32 +00004911 if (0 != CRYPTO_memcmp(calculatedHmac.data(), event.getHmac().data(), calculatedHmac.size())) {
Gang Wange9087892020-01-07 12:17:14 -05004912 return nullptr;
4913 }
4914 return result;
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004915}
4916
Prabir Pradhan24047542023-11-02 17:14:59 +00004917void InputDispatcher::setInjectionResult(const EventEntry& entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004918 InputEventInjectionResult injectionResult) {
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00004919 if (!entry.injectionState) {
4920 // Not an injected event.
4921 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004922 }
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00004923
4924 InjectionState& injectionState = *entry.injectionState;
4925 if (DEBUG_INJECTION) {
4926 LOG(INFO) << "Setting input event injection result to "
4927 << ftl::enum_string(injectionResult);
4928 }
4929
4930 if (injectionState.injectionIsAsync && !(entry.policyFlags & POLICY_FLAG_FILTERED)) {
4931 // Log the outcome since the injector did not wait for the injection result.
4932 switch (injectionResult) {
4933 case InputEventInjectionResult::SUCCEEDED:
4934 ALOGV("Asynchronous input event injection succeeded.");
4935 break;
4936 case InputEventInjectionResult::TARGET_MISMATCH:
4937 ALOGV("Asynchronous input event injection target mismatch.");
4938 break;
4939 case InputEventInjectionResult::FAILED:
4940 ALOGW("Asynchronous input event injection failed.");
4941 break;
4942 case InputEventInjectionResult::TIMED_OUT:
4943 ALOGW("Asynchronous input event injection timed out.");
4944 break;
4945 case InputEventInjectionResult::PENDING:
4946 ALOGE("Setting result to 'PENDING' for asynchronous injection");
4947 break;
4948 }
4949 }
4950
4951 injectionState.injectionResult = injectionResult;
4952 mInjectionResultAvailable.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004953}
4954
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004955void InputDispatcher::transformMotionEntryForInjectionLocked(
4956 MotionEntry& entry, const ui::Transform& injectedTransform) const {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004957 // Input injection works in the logical display coordinate space, but the input pipeline works
4958 // display space, so we need to transform the injected events accordingly.
4959 const auto it = mDisplayInfos.find(entry.displayId);
4960 if (it == mDisplayInfos.end()) return;
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004961 const auto& transformToDisplay = it->second.transform.inverse() * injectedTransform;
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004962
Prabir Pradhand9a2ebe2022-07-20 19:25:13 +00004963 if (entry.xCursorPosition != AMOTION_EVENT_INVALID_CURSOR_POSITION &&
4964 entry.yCursorPosition != AMOTION_EVENT_INVALID_CURSOR_POSITION) {
4965 const vec2 cursor =
4966 MotionEvent::calculateTransformedXY(entry.source, transformToDisplay,
4967 {entry.xCursorPosition, entry.yCursorPosition});
4968 entry.xCursorPosition = cursor.x;
4969 entry.yCursorPosition = cursor.y;
4970 }
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004971 for (uint32_t i = 0; i < entry.getPointerCount(); i++) {
Prabir Pradhan8e6ce222022-02-24 09:08:54 -08004972 entry.pointerCoords[i] =
4973 MotionEvent::calculateTransformedCoords(entry.source, transformToDisplay,
4974 entry.pointerCoords[i]);
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004975 }
4976}
4977
Prabir Pradhan24047542023-11-02 17:14:59 +00004978void InputDispatcher::incrementPendingForegroundDispatches(const EventEntry& entry) {
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00004979 if (entry.injectionState) {
4980 entry.injectionState->pendingForegroundDispatches += 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004981 }
4982}
4983
Prabir Pradhan24047542023-11-02 17:14:59 +00004984void InputDispatcher::decrementPendingForegroundDispatches(const EventEntry& entry) {
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00004985 if (entry.injectionState) {
4986 entry.injectionState->pendingForegroundDispatches -= 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004987
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00004988 if (entry.injectionState->pendingForegroundDispatches == 0) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004989 mInjectionSyncFinished.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004990 }
4991 }
4992}
4993
chaviw98318de2021-05-19 16:45:23 -05004994const std::vector<sp<WindowInfoHandle>>& InputDispatcher::getWindowHandlesLocked(
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004995 int32_t displayId) const {
chaviw98318de2021-05-19 16:45:23 -05004996 static const std::vector<sp<WindowInfoHandle>> EMPTY_WINDOW_HANDLES;
Vishnu Nairad321cd2020-08-20 16:40:21 -07004997 auto it = mWindowHandlesByDisplay.find(displayId);
4998 return it != mWindowHandlesByDisplay.end() ? it->second : EMPTY_WINDOW_HANDLES;
Arthur Hungb92218b2018-08-14 12:00:21 +08004999}
5000
chaviw98318de2021-05-19 16:45:23 -05005001sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(
Prabir Pradhan16463382023-10-12 23:03:19 +00005002 const sp<IBinder>& windowHandleToken, std::optional<int32_t> displayId) const {
arthurhungbe737672020-06-24 12:29:21 +08005003 if (windowHandleToken == nullptr) {
5004 return nullptr;
5005 }
5006
Prabir Pradhan16463382023-10-12 23:03:19 +00005007 if (!displayId) {
5008 // Look through all displays.
5009 for (auto& it : mWindowHandlesByDisplay) {
5010 const std::vector<sp<WindowInfoHandle>>& windowHandles = it.second;
5011 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
5012 if (windowHandle->getToken() == windowHandleToken) {
5013 return windowHandle;
5014 }
Arthur Hungb92218b2018-08-14 12:00:21 +08005015 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005016 }
Vishnu Nairad321cd2020-08-20 16:40:21 -07005017 return nullptr;
5018 }
5019
Prabir Pradhan16463382023-10-12 23:03:19 +00005020 // Only look through the requested display.
5021 for (const sp<WindowInfoHandle>& windowHandle : getWindowHandlesLocked(*displayId)) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07005022 if (windowHandle->getToken() == windowHandleToken) {
5023 return windowHandle;
5024 }
5025 }
5026 return nullptr;
5027}
5028
chaviw98318de2021-05-19 16:45:23 -05005029sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(
5030 const sp<WindowInfoHandle>& windowHandle) const {
Mady Mellor017bcd12020-06-23 19:12:00 +00005031 for (auto& it : mWindowHandlesByDisplay) {
chaviw98318de2021-05-19 16:45:23 -05005032 const std::vector<sp<WindowInfoHandle>>& windowHandles = it.second;
5033 for (const sp<WindowInfoHandle>& handle : windowHandles) {
arthurhungbe737672020-06-24 12:29:21 +08005034 if (handle->getId() == windowHandle->getId() &&
5035 handle->getToken() == windowHandle->getToken()) {
Mady Mellor017bcd12020-06-23 19:12:00 +00005036 if (windowHandle->getInfo()->displayId != it.first) {
5037 ALOGE("Found window %s in display %" PRId32
5038 ", but it should belong to display %" PRId32,
5039 windowHandle->getName().c_str(), it.first,
5040 windowHandle->getInfo()->displayId);
5041 }
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07005042 return handle;
Arthur Hungb92218b2018-08-14 12:00:21 +08005043 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005044 }
5045 }
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07005046 return nullptr;
5047}
5048
chaviw98318de2021-05-19 16:45:23 -05005049sp<WindowInfoHandle> InputDispatcher::getFocusedWindowHandleLocked(int displayId) const {
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07005050 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(displayId);
5051 return getWindowHandleLocked(focusedToken, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005052}
5053
Prabir Pradhan33e3baa2022-12-06 20:30:22 +00005054ui::Transform InputDispatcher::getTransformLocked(int32_t displayId) const {
5055 auto displayInfoIt = mDisplayInfos.find(displayId);
5056 return displayInfoIt != mDisplayInfos.end() ? displayInfoIt->second.transform
5057 : kIdentityTransform;
5058}
5059
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07005060bool InputDispatcher::canWindowReceiveMotionLocked(const sp<WindowInfoHandle>& window,
5061 const MotionEntry& motionEntry) const {
5062 const WindowInfo& info = *window->getInfo();
5063
5064 // Skip spy window targets that are not valid for targeted injection.
5065 if (const auto err = verifyTargetedInjection(window, motionEntry); err) {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005066 return false;
5067 }
5068
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07005069 if (info.inputConfig.test(WindowInfo::InputConfig::PAUSE_DISPATCHING)) {
5070 ALOGI("Not sending touch event to %s because it is paused", window->getName().c_str());
5071 return false;
5072 }
5073
5074 if (info.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL)) {
5075 ALOGW("Not sending touch gesture to %s because it has config NO_INPUT_CHANNEL",
5076 window->getName().c_str());
5077 return false;
5078 }
5079
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07005080 std::shared_ptr<Connection> connection = getConnectionLocked(window->getToken());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005081 if (connection == nullptr) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07005082 ALOGW("Not sending touch to %s because there's no corresponding connection",
5083 window->getName().c_str());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005084 return false;
5085 }
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07005086
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005087 if (!connection->responsive) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07005088 ALOGW("Not sending touch to %s because it is not responsive", window->getName().c_str());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005089 return false;
5090 }
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07005091
5092 // Drop events that can't be trusted due to occlusion
5093 const auto [x, y] = resolveTouchedPosition(motionEntry);
5094 TouchOcclusionInfo occlusionInfo = computeTouchOcclusionInfoLocked(window, x, y);
5095 if (!isTouchTrustedLocked(occlusionInfo)) {
5096 if (DEBUG_TOUCH_OCCLUSION) {
Prabir Pradhan82e081e2022-12-06 09:50:09 +00005097 ALOGD("Stack of obscuring windows during untrusted touch (%.1f, %.1f):", x, y);
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07005098 for (const auto& log : occlusionInfo.debugInfo) {
5099 ALOGD("%s", log.c_str());
5100 }
5101 }
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00005102 ALOGW("Dropping untrusted touch event due to %s/%s", occlusionInfo.obscuringPackage.c_str(),
5103 occlusionInfo.obscuringUid.toString().c_str());
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07005104 return false;
5105 }
5106
5107 // Drop touch events if requested by input feature
5108 if (shouldDropInput(motionEntry, window)) {
5109 return false;
5110 }
5111
Siarhei Vishniakouf77f60a2023-10-23 17:26:05 -07005112 // Ignore touches if stylus is down anywhere on screen
5113 if (info.inputConfig.test(WindowInfo::InputConfig::GLOBAL_STYLUS_BLOCKS_TOUCH) &&
5114 isStylusActiveInDisplay(info.displayId, mTouchStatesByDisplay)) {
5115 LOG(INFO) << "Dropping touch from " << window->getName() << " because stylus is active";
5116 return false;
5117 }
5118
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005119 return true;
5120}
5121
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005122std::shared_ptr<InputChannel> InputDispatcher::getInputChannelLocked(
5123 const sp<IBinder>& token) const {
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005124 auto connectionIt = mConnectionsByToken.find(token);
5125 if (connectionIt == mConnectionsByToken.end()) {
Robert Carr5c8a0262018-10-03 16:30:44 -07005126 return nullptr;
5127 }
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005128 return connectionIt->second->inputChannel;
Robert Carr5c8a0262018-10-03 16:30:44 -07005129}
5130
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005131void InputDispatcher::updateWindowHandlesForDisplayLocked(
chaviw98318de2021-05-19 16:45:23 -05005132 const std::vector<sp<WindowInfoHandle>>& windowInfoHandles, int32_t displayId) {
5133 if (windowInfoHandles.empty()) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005134 // Remove all handles on a display if there are no windows left.
5135 mWindowHandlesByDisplay.erase(displayId);
5136 return;
5137 }
5138
5139 // Since we compare the pointer of input window handles across window updates, we need
5140 // to make sure the handle object for the same window stays unchanged across updates.
chaviw98318de2021-05-19 16:45:23 -05005141 const std::vector<sp<WindowInfoHandle>>& oldHandles = getWindowHandlesLocked(displayId);
5142 std::unordered_map<int32_t /*id*/, sp<WindowInfoHandle>> oldHandlesById;
5143 for (const sp<WindowInfoHandle>& handle : oldHandles) {
chaviwaf87b3e2019-10-01 16:59:28 -07005144 oldHandlesById[handle->getId()] = handle;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005145 }
5146
chaviw98318de2021-05-19 16:45:23 -05005147 std::vector<sp<WindowInfoHandle>> newHandles;
5148 for (const sp<WindowInfoHandle>& handle : windowInfoHandles) {
chaviw98318de2021-05-19 16:45:23 -05005149 const WindowInfo* info = handle->getInfo();
Siarhei Vishniakou64452932020-11-06 17:51:32 -06005150 if (getInputChannelLocked(handle->getToken()) == nullptr) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005151 const bool noInputChannel =
Prabir Pradhan51e7db02022-02-07 06:02:57 -08005152 info->inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005153 const bool canReceiveInput =
5154 !info->inputConfig.test(WindowInfo::InputConfig::NOT_TOUCHABLE) ||
5155 !info->inputConfig.test(WindowInfo::InputConfig::NOT_FOCUSABLE);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005156 if (canReceiveInput && !noInputChannel) {
John Recke0710582019-09-26 13:46:12 -07005157 ALOGV("Window handle %s has no registered input channel",
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005158 handle->getName().c_str());
Robert Carr2984b7a2020-04-13 17:06:45 -07005159 continue;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005160 }
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005161 }
5162
5163 if (info->displayId != displayId) {
5164 ALOGE("Window %s updated by wrong display %d, should belong to display %d",
5165 handle->getName().c_str(), displayId, info->displayId);
5166 continue;
5167 }
5168
Robert Carredd13602020-04-13 17:24:34 -07005169 if ((oldHandlesById.find(handle->getId()) != oldHandlesById.end()) &&
5170 (oldHandlesById.at(handle->getId())->getToken() == handle->getToken())) {
chaviw98318de2021-05-19 16:45:23 -05005171 const sp<WindowInfoHandle>& oldHandle = oldHandlesById.at(handle->getId());
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005172 oldHandle->updateFrom(handle);
5173 newHandles.push_back(oldHandle);
5174 } else {
5175 newHandles.push_back(handle);
5176 }
5177 }
5178
5179 // Insert or replace
5180 mWindowHandlesByDisplay[displayId] = newHandles;
5181}
5182
Arthur Hungb92218b2018-08-14 12:00:21 +08005183/**
5184 * Called from InputManagerService, update window handle list by displayId that can receive input.
5185 * A window handle contains information about InputChannel, Touch Region, Types, Focused,...
5186 * If set an empty list, remove all handles from the specific display.
5187 * For focused handle, check if need to change and send a cancel event to previous one.
5188 * For removed handle, check if need to send a cancel event if already in touch.
5189 */
Arthur Hung72d8dc32020-03-28 00:48:39 +00005190void InputDispatcher::setInputWindowsLocked(
chaviw98318de2021-05-19 16:45:23 -05005191 const std::vector<sp<WindowInfoHandle>>& windowInfoHandles, int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005192 if (DEBUG_FOCUS) {
5193 std::string windowList;
chaviw98318de2021-05-19 16:45:23 -05005194 for (const sp<WindowInfoHandle>& iwh : windowInfoHandles) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005195 windowList += iwh->getName() + " ";
5196 }
Siarhei Vishniakou366fb5b2023-12-06 11:23:41 -08005197 LOG(INFO) << "setInputWindows displayId=" << displayId << " " << windowList;
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005198 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005199
Prabir Pradhand65552b2021-10-07 11:23:50 -07005200 // Check preconditions for new input windows
chaviw98318de2021-05-19 16:45:23 -05005201 for (const sp<WindowInfoHandle>& window : windowInfoHandles) {
Prabir Pradhand65552b2021-10-07 11:23:50 -07005202 const WindowInfo& info = *window->getInfo();
5203
5204 // Ensure all tokens are null if the window has feature NO_INPUT_CHANNEL
Prabir Pradhan51e7db02022-02-07 06:02:57 -08005205 const bool noInputWindow = info.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005206 if (noInputWindow && window->getToken() != nullptr) {
5207 ALOGE("%s has feature NO_INPUT_WINDOW, but a non-null token. Clearing",
5208 window->getName().c_str());
5209 window->releaseChannel();
5210 }
Prabir Pradhand65552b2021-10-07 11:23:50 -07005211
Prabir Pradhan5c85e052021-12-22 02:27:12 -08005212 // Ensure all spy windows are trusted overlays
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005213 LOG_ALWAYS_FATAL_IF(info.isSpy() &&
5214 !info.inputConfig.test(
5215 WindowInfo::InputConfig::TRUSTED_OVERLAY),
Prabir Pradhan5c85e052021-12-22 02:27:12 -08005216 "%s has feature SPY, but is not a trusted overlay.",
5217 window->getName().c_str());
5218
Prabir Pradhand65552b2021-10-07 11:23:50 -07005219 // Ensure all stylus interceptors are trusted overlays
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005220 LOG_ALWAYS_FATAL_IF(info.interceptsStylus() &&
5221 !info.inputConfig.test(
5222 WindowInfo::InputConfig::TRUSTED_OVERLAY),
Prabir Pradhand65552b2021-10-07 11:23:50 -07005223 "%s has feature INTERCEPTS_STYLUS, but is not a trusted overlay.",
5224 window->getName().c_str());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005225 }
5226
Arthur Hung72d8dc32020-03-28 00:48:39 +00005227 // Copy old handles for release if they are no longer present.
chaviw98318de2021-05-19 16:45:23 -05005228 const std::vector<sp<WindowInfoHandle>> oldWindowHandles = getWindowHandlesLocked(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005229
chaviw98318de2021-05-19 16:45:23 -05005230 updateWindowHandlesForDisplayLocked(windowInfoHandles, displayId);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005231
chaviw98318de2021-05-19 16:45:23 -05005232 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Arthur Hung72d8dc32020-03-28 00:48:39 +00005233
Vishnu Nairc519ff72021-01-21 08:23:08 -08005234 std::optional<FocusResolver::FocusChanges> changes =
5235 mFocusResolver.setInputWindows(displayId, windowHandles);
5236 if (changes) {
5237 onFocusChangedLocked(*changes);
Arthur Hung72d8dc32020-03-28 00:48:39 +00005238 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005239
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005240 std::unordered_map<int32_t, TouchState>::iterator stateIt =
5241 mTouchStatesByDisplay.find(displayId);
5242 if (stateIt != mTouchStatesByDisplay.end()) {
5243 TouchState& state = stateIt->second;
Arthur Hung72d8dc32020-03-28 00:48:39 +00005244 for (size_t i = 0; i < state.windows.size();) {
5245 TouchedWindow& touchedWindow = state.windows[i];
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07005246 if (getWindowHandleLocked(touchedWindow.windowHandle) == nullptr) {
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07005247 LOG(INFO) << "Touched window was removed: " << touchedWindow.windowHandle->getName()
5248 << " in display %" << displayId;
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005249 std::shared_ptr<InputChannel> touchedInputChannel =
Arthur Hung72d8dc32020-03-28 00:48:39 +00005250 getInputChannelLocked(touchedWindow.windowHandle->getToken());
5251 if (touchedInputChannel != nullptr) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00005252 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
Arthur Hung72d8dc32020-03-28 00:48:39 +00005253 "touched window was removed");
5254 synthesizeCancelationEventsForInputChannelLocked(touchedInputChannel, options);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00005255 // Since we are about to drop the touch, cancel the events for the wallpaper as
5256 // well.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005257 if (touchedWindow.targetFlags.test(InputTarget::Flags::FOREGROUND) &&
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005258 touchedWindow.windowHandle->getInfo()->inputConfig.test(
5259 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER)) {
Siarhei Vishniakouca205502021-07-16 21:31:58 +00005260 sp<WindowInfoHandle> wallpaper = state.getWallpaperWindow();
Arthur Hungc539dbb2022-12-08 07:45:36 +00005261 synthesizeCancelationEventsForWindowLocked(wallpaper, options);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00005262 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005263 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00005264 state.windows.erase(state.windows.begin() + i);
5265 } else {
5266 ++i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005267 }
5268 }
arthurhungb89ccb02020-12-30 16:19:01 +08005269
arthurhung6d4bed92021-03-17 11:59:33 +08005270 // If drag window is gone, it would receive a cancel event and broadcast the DRAG_END. We
arthurhungb89ccb02020-12-30 16:19:01 +08005271 // could just clear the state here.
Arthur Hung3915c1f2022-05-31 07:17:17 +00005272 if (mDragState && mDragState->dragWindow->getInfo()->displayId == displayId &&
arthurhung6d4bed92021-03-17 11:59:33 +08005273 std::find(windowHandles.begin(), windowHandles.end(), mDragState->dragWindow) ==
arthurhungb89ccb02020-12-30 16:19:01 +08005274 windowHandles.end()) {
Arthur Hung3915c1f2022-05-31 07:17:17 +00005275 ALOGI("Drag window went away: %s", mDragState->dragWindow->getName().c_str());
5276 sendDropWindowCommandLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08005277 mDragState.reset();
arthurhungb89ccb02020-12-30 16:19:01 +08005278 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00005279 }
Arthur Hung25e2af12020-03-26 12:58:37 +00005280
Arthur Hung72d8dc32020-03-28 00:48:39 +00005281 // Release information for windows that are no longer present.
5282 // This ensures that unused input channels are released promptly.
5283 // Otherwise, they might stick around until the window handle is destroyed
5284 // which might not happen until the next GC.
chaviw98318de2021-05-19 16:45:23 -05005285 for (const sp<WindowInfoHandle>& oldWindowHandle : oldWindowHandles) {
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07005286 if (getWindowHandleLocked(oldWindowHandle) == nullptr) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00005287 if (DEBUG_FOCUS) {
5288 ALOGD("Window went away: %s", oldWindowHandle->getName().c_str());
Arthur Hung25e2af12020-03-26 12:58:37 +00005289 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00005290 oldWindowHandle->releaseChannel();
Arthur Hung25e2af12020-03-26 12:58:37 +00005291 }
chaviw291d88a2019-02-14 10:33:58 -08005292 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005293}
5294
5295void InputDispatcher::setFocusedApplication(
Chris Yea209fde2020-07-22 13:54:51 -07005296 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005297 if (DEBUG_FOCUS) {
5298 ALOGD("setFocusedApplication displayId=%" PRId32 " %s", displayId,
5299 inputApplicationHandle ? inputApplicationHandle->getName().c_str() : "<nullptr>");
5300 }
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05005301 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005302 std::scoped_lock _l(mLock);
Vishnu Nair599f1412021-06-21 10:39:58 -07005303 setFocusedApplicationLocked(displayId, inputApplicationHandle);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005304 } // release lock
5305
5306 // Wake up poll loop since it may need to make new input dispatching choices.
5307 mLooper->wake();
5308}
5309
Vishnu Nair599f1412021-06-21 10:39:58 -07005310void InputDispatcher::setFocusedApplicationLocked(
5311 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
5312 std::shared_ptr<InputApplicationHandle> oldFocusedApplicationHandle =
5313 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
5314
5315 if (sharedPointersEqual(oldFocusedApplicationHandle, inputApplicationHandle)) {
5316 return; // This application is already focused. No need to wake up or change anything.
5317 }
5318
5319 // Set the new application handle.
5320 if (inputApplicationHandle != nullptr) {
5321 mFocusedApplicationHandlesByDisplay[displayId] = inputApplicationHandle;
5322 } else {
5323 mFocusedApplicationHandlesByDisplay.erase(displayId);
5324 }
5325
5326 // No matter what the old focused application was, stop waiting on it because it is
5327 // no longer focused.
5328 resetNoFocusedWindowTimeoutLocked();
5329}
5330
Yeabkal Wubshitb8aadfa2024-01-17 17:03:42 -08005331void InputDispatcher::setMinTimeBetweenUserActivityPokes(std::chrono::milliseconds interval) {
5332 if (interval.count() < 0) {
5333 LOG_ALWAYS_FATAL("Minimum time between user activity pokes should be >= 0");
5334 }
5335 std::scoped_lock _l(mLock);
5336 mMinTimeBetweenUserActivityPokes = interval;
5337}
5338
Tiger Huang721e26f2018-07-24 22:26:19 +08005339/**
5340 * Sets the focused display, which is responsible for receiving focus-dispatched input events where
5341 * the display not specified.
5342 *
5343 * We track any unreleased events for each window. If a window loses the ability to receive the
5344 * released event, we will send a cancel event to it. So when the focused display is changed, we
5345 * cancel all the unreleased display-unspecified events for the focused window on the old focused
5346 * display. The display-specified events won't be affected.
5347 */
5348void InputDispatcher::setFocusedDisplay(int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005349 if (DEBUG_FOCUS) {
5350 ALOGD("setFocusedDisplay displayId=%" PRId32, displayId);
5351 }
Tiger Huang721e26f2018-07-24 22:26:19 +08005352 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005353 std::scoped_lock _l(mLock);
Tiger Huang721e26f2018-07-24 22:26:19 +08005354
5355 if (mFocusedDisplayId != displayId) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07005356 sp<IBinder> oldFocusedWindowToken =
Vishnu Nairc519ff72021-01-21 08:23:08 -08005357 mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07005358 if (oldFocusedWindowToken != nullptr) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005359 std::shared_ptr<InputChannel> inputChannel =
Vishnu Nairad321cd2020-08-20 16:40:21 -07005360 getInputChannelLocked(oldFocusedWindowToken);
Tiger Huang721e26f2018-07-24 22:26:19 +08005361 if (inputChannel != nullptr) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005362 CancelationOptions
Michael Wrightfb04fd52022-11-24 22:31:11 +00005363 options(CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005364 "The display which contains this window no longer has focus.");
Michael Wright3dd60e22019-03-27 22:06:44 +00005365 options.displayId = ADISPLAY_ID_NONE;
Tiger Huang721e26f2018-07-24 22:26:19 +08005366 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
5367 }
5368 }
5369 mFocusedDisplayId = displayId;
5370
Chris Ye3c2d6f52020-08-09 10:39:48 -07005371 // Find new focused window and validate
Vishnu Nairc519ff72021-01-21 08:23:08 -08005372 sp<IBinder> newFocusedWindowToken = mFocusResolver.getFocusedWindowToken(displayId);
Prabir Pradhancef936d2021-07-21 16:17:52 +00005373 sendFocusChangedCommandLocked(oldFocusedWindowToken, newFocusedWindowToken);
Robert Carrf759f162018-11-13 12:57:11 -08005374
Vishnu Nairad321cd2020-08-20 16:40:21 -07005375 if (newFocusedWindowToken == nullptr) {
Tiger Huang721e26f2018-07-24 22:26:19 +08005376 ALOGW("Focused display #%" PRId32 " does not have a focused window.", displayId);
Vishnu Nairc519ff72021-01-21 08:23:08 -08005377 if (mFocusResolver.hasFocusedWindowTokens()) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07005378 ALOGE("But another display has a focused window\n%s",
Vishnu Nairc519ff72021-01-21 08:23:08 -08005379 mFocusResolver.dumpFocusedWindows().c_str());
Tiger Huang721e26f2018-07-24 22:26:19 +08005380 }
5381 }
5382 }
Tiger Huang721e26f2018-07-24 22:26:19 +08005383 } // release lock
5384
5385 // Wake up poll loop since it may need to make new input dispatching choices.
5386 mLooper->wake();
5387}
5388
Michael Wrightd02c5b62014-02-10 15:10:22 -08005389void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005390 if (DEBUG_FOCUS) {
5391 ALOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
5392 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005393
5394 bool changed;
5395 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005396 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005397
5398 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
5399 if (mDispatchFrozen && !frozen) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005400 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005401 }
5402
5403 if (mDispatchEnabled && !enabled) {
5404 resetAndDropEverythingLocked("dispatcher is being disabled");
5405 }
5406
5407 mDispatchEnabled = enabled;
5408 mDispatchFrozen = frozen;
5409 changed = true;
5410 } else {
5411 changed = false;
5412 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005413 } // release lock
5414
5415 if (changed) {
5416 // Wake up poll loop since it may need to make new input dispatching choices.
5417 mLooper->wake();
5418 }
5419}
5420
5421void InputDispatcher::setInputFilterEnabled(bool enabled) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005422 if (DEBUG_FOCUS) {
5423 ALOGD("setInputFilterEnabled: enabled=%d", enabled);
5424 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005425
5426 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005427 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005428
5429 if (mInputFilterEnabled == enabled) {
5430 return;
5431 }
5432
5433 mInputFilterEnabled = enabled;
5434 resetAndDropEverythingLocked("input filter is being enabled or disabled");
5435 } // release lock
5436
5437 // Wake up poll loop since there might be work to do to drop everything.
5438 mLooper->wake();
5439}
5440
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005441bool InputDispatcher::setInTouchMode(bool inTouchMode, gui::Pid pid, gui::Uid uid,
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00005442 bool hasPermission, int32_t displayId) {
Antonio Kantekf16f2832021-09-28 04:39:20 +00005443 bool needWake = false;
5444 {
5445 std::scoped_lock lock(mLock);
Antonio Kantek15beb512022-06-13 22:35:41 +00005446 ALOGD_IF(DEBUG_TOUCH_MODE,
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005447 "Request to change touch mode to %s (calling pid=%s, uid=%s, "
Antonio Kantek15beb512022-06-13 22:35:41 +00005448 "hasPermission=%s, target displayId=%d, mTouchModePerDisplay[displayId]=%s)",
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005449 toString(inTouchMode), pid.toString().c_str(), uid.toString().c_str(),
5450 toString(hasPermission), displayId,
Antonio Kantek15beb512022-06-13 22:35:41 +00005451 mTouchModePerDisplay.count(displayId) == 0
5452 ? "not set"
5453 : std::to_string(mTouchModePerDisplay[displayId]).c_str());
5454
Antonio Kantek15beb512022-06-13 22:35:41 +00005455 auto touchModeIt = mTouchModePerDisplay.find(displayId);
5456 if (touchModeIt != mTouchModePerDisplay.end() && touchModeIt->second == inTouchMode) {
Antonio Kantekea47acb2021-12-23 12:41:25 -08005457 return false;
Antonio Kantekf16f2832021-09-28 04:39:20 +00005458 }
Antonio Kantekea47acb2021-12-23 12:41:25 -08005459 if (!hasPermission) {
Antonio Kantek48710e42022-03-24 14:19:30 -07005460 if (!focusedWindowIsOwnedByLocked(pid, uid) &&
5461 !recentWindowsAreOwnedByLocked(pid, uid)) {
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005462 ALOGD("Touch mode switch rejected, caller (pid=%s, uid=%s) doesn't own the focused "
Antonio Kantek48710e42022-03-24 14:19:30 -07005463 "window nor none of the previously interacted window",
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005464 pid.toString().c_str(), uid.toString().c_str());
Antonio Kantekea47acb2021-12-23 12:41:25 -08005465 return false;
5466 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00005467 }
Antonio Kantek15beb512022-06-13 22:35:41 +00005468 mTouchModePerDisplay[displayId] = inTouchMode;
5469 auto entry = std::make_unique<TouchModeEntry>(mIdGenerator.nextId(), now(), inTouchMode,
5470 displayId);
Antonio Kantekf16f2832021-09-28 04:39:20 +00005471 needWake = enqueueInboundEventLocked(std::move(entry));
5472 } // release lock
5473
5474 if (needWake) {
5475 mLooper->wake();
5476 }
Antonio Kantekea47acb2021-12-23 12:41:25 -08005477 return true;
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -08005478}
5479
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005480bool InputDispatcher::focusedWindowIsOwnedByLocked(gui::Pid pid, gui::Uid uid) {
Antonio Kantek48710e42022-03-24 14:19:30 -07005481 const sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
5482 if (focusedToken == nullptr) {
5483 return false;
5484 }
5485 sp<WindowInfoHandle> windowHandle = getWindowHandleLocked(focusedToken);
5486 return isWindowOwnedBy(windowHandle, pid, uid);
5487}
5488
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005489bool InputDispatcher::recentWindowsAreOwnedByLocked(gui::Pid pid, gui::Uid uid) {
Antonio Kantek48710e42022-03-24 14:19:30 -07005490 return std::find_if(mInteractionConnectionTokens.begin(), mInteractionConnectionTokens.end(),
5491 [&](const sp<IBinder>& connectionToken) REQUIRES(mLock) {
5492 const sp<WindowInfoHandle> windowHandle =
5493 getWindowHandleLocked(connectionToken);
5494 return isWindowOwnedBy(windowHandle, pid, uid);
5495 }) != mInteractionConnectionTokens.end();
5496}
5497
Bernardo Rufinoea97d182020-08-19 14:43:14 +01005498void InputDispatcher::setMaximumObscuringOpacityForTouch(float opacity) {
5499 if (opacity < 0 || opacity > 1) {
5500 LOG_ALWAYS_FATAL("Maximum obscuring opacity for touch should be >= 0 and <= 1");
5501 return;
5502 }
5503
5504 std::scoped_lock lock(mLock);
5505 mMaximumObscuringOpacityForTouch = opacity;
5506}
5507
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005508std::tuple<TouchState*, TouchedWindow*, int32_t /*displayId*/>
5509InputDispatcher::findTouchStateWindowAndDisplayLocked(const sp<IBinder>& token) {
Arthur Hungabbb9d82021-09-01 14:52:30 +00005510 for (auto& [displayId, state] : mTouchStatesByDisplay) {
5511 for (TouchedWindow& w : state.windows) {
5512 if (w.windowHandle->getToken() == token) {
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005513 return std::make_tuple(&state, &w, displayId);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005514 }
5515 }
5516 }
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005517 return std::make_tuple(nullptr, nullptr, ADISPLAY_ID_DEFAULT);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005518}
5519
arthurhungb89ccb02020-12-30 16:19:01 +08005520bool InputDispatcher::transferTouchFocus(const sp<IBinder>& fromToken, const sp<IBinder>& toToken,
5521 bool isDragDrop) {
chaviwfbe5d9c2018-12-26 12:23:37 -08005522 if (fromToken == toToken) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005523 if (DEBUG_FOCUS) {
5524 ALOGD("Trivial transfer to same window.");
5525 }
chaviwfbe5d9c2018-12-26 12:23:37 -08005526 return true;
5527 }
5528
Michael Wrightd02c5b62014-02-10 15:10:22 -08005529 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005530 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005531
Arthur Hungabbb9d82021-09-01 14:52:30 +00005532 // Find the target touch state and touched window by fromToken.
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005533 auto [state, touchedWindow, displayId] = findTouchStateWindowAndDisplayLocked(fromToken);
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005534
Arthur Hungabbb9d82021-09-01 14:52:30 +00005535 if (state == nullptr || touchedWindow == nullptr) {
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005536 ALOGD("Touch transfer failed because from window is not being touched.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005537 return false;
5538 }
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005539 std::set<int32_t> deviceIds = touchedWindow->getTouchingDeviceIds();
5540 if (deviceIds.size() != 1) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07005541 LOG(INFO) << "Can't transfer touch. Currently touching devices: " << dumpSet(deviceIds)
5542 << " for window: " << touchedWindow->dump();
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005543 return false;
5544 }
5545 const int32_t deviceId = *deviceIds.begin();
Arthur Hungabbb9d82021-09-01 14:52:30 +00005546
Arthur Hungabbb9d82021-09-01 14:52:30 +00005547 sp<WindowInfoHandle> toWindowHandle = getWindowHandleLocked(toToken, displayId);
5548 if (toWindowHandle == nullptr) {
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005549 ALOGW("Cannot transfer touch because to window not found.");
Arthur Hungabbb9d82021-09-01 14:52:30 +00005550 return false;
5551 }
5552
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005553 if (DEBUG_FOCUS) {
5554 ALOGD("transferTouchFocus: fromWindowHandle=%s, toWindowHandle=%s",
Arthur Hungabbb9d82021-09-01 14:52:30 +00005555 touchedWindow->windowHandle->getName().c_str(),
5556 toWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005557 }
5558
Arthur Hungabbb9d82021-09-01 14:52:30 +00005559 // Erase old window.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005560 ftl::Flags<InputTarget::Flags> oldTargetFlags = touchedWindow->targetFlags;
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08005561 std::vector<PointerProperties> pointers = touchedWindow->getTouchingPointers(deviceId);
Arthur Hungc539dbb2022-12-08 07:45:36 +00005562 sp<WindowInfoHandle> fromWindowHandle = touchedWindow->windowHandle;
Arthur Hungabbb9d82021-09-01 14:52:30 +00005563 state->removeWindowByToken(fromToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005564
Arthur Hungabbb9d82021-09-01 14:52:30 +00005565 // Add new window.
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00005566 nsecs_t downTimeInTarget = now();
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005567 ftl::Flags<InputTarget::Flags> newTargetFlags =
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00005568 oldTargetFlags & (InputTarget::Flags::SPLIT);
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00005569 if (canReceiveForegroundTouches(*toWindowHandle->getInfo())) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005570 newTargetFlags |= InputTarget::Flags::FOREGROUND;
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00005571 }
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00005572 state->addOrUpdateWindow(toWindowHandle, InputTarget::DispatchMode::AS_IS, newTargetFlags,
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08005573 deviceId, pointers, downTimeInTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005574
Arthur Hungabbb9d82021-09-01 14:52:30 +00005575 // Store the dragging window.
5576 if (isDragDrop) {
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08005577 if (pointers.size() != 1) {
Arthur Hungb75c2aa2022-07-15 09:35:36 +00005578 ALOGW("The drag and drop cannot be started when there is no pointer or more than 1"
5579 " pointer on the window.");
Arthur Hung54745652022-04-20 07:17:41 +00005580 return false;
5581 }
Arthur Hungb75c2aa2022-07-15 09:35:36 +00005582 // Track the pointer id for drag window and generate the drag state.
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08005583 const size_t id = pointers.begin()->id;
Arthur Hung54745652022-04-20 07:17:41 +00005584 mDragState = std::make_unique<DragState>(toWindowHandle, id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005585 }
5586
Arthur Hungabbb9d82021-09-01 14:52:30 +00005587 // Synthesize cancel for old window and down for new window.
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07005588 std::shared_ptr<Connection> fromConnection = getConnectionLocked(fromToken);
5589 std::shared_ptr<Connection> toConnection = getConnectionLocked(toToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005590 if (fromConnection != nullptr && toConnection != nullptr) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08005591 fromConnection->inputState.mergePointerStateTo(toConnection->inputState);
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005592 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
5593 "transferring touch from this window to another window");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005594 synthesizeCancelationEventsForConnectionLocked(fromConnection, options);
Arthur Hungc539dbb2022-12-08 07:45:36 +00005595 synthesizePointerDownEventsForConnectionLocked(downTimeInTarget, toConnection,
5596 newTargetFlags);
5597
5598 // Check if the wallpaper window should deliver the corresponding event.
5599 transferWallpaperTouch(oldTargetFlags, newTargetFlags, fromWindowHandle, toWindowHandle,
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08005600 *state, deviceId, pointers);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005601 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005602 } // release lock
5603
5604 // Wake up poll loop since it may need to make new input dispatching choices.
5605 mLooper->wake();
5606 return true;
5607}
5608
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005609/**
5610 * Get the touched foreground window on the given display.
5611 * Return null if there are no windows touched on that display, or if more than one foreground
5612 * window is being touched.
5613 */
5614sp<WindowInfoHandle> InputDispatcher::findTouchedForegroundWindowLocked(int32_t displayId) const {
5615 auto stateIt = mTouchStatesByDisplay.find(displayId);
5616 if (stateIt == mTouchStatesByDisplay.end()) {
5617 ALOGI("No touch state on display %" PRId32, displayId);
5618 return nullptr;
5619 }
5620
5621 const TouchState& state = stateIt->second;
5622 sp<WindowInfoHandle> touchedForegroundWindow;
5623 // If multiple foreground windows are touched, return nullptr
5624 for (const TouchedWindow& window : state.windows) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005625 if (window.targetFlags.test(InputTarget::Flags::FOREGROUND)) {
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005626 if (touchedForegroundWindow != nullptr) {
5627 ALOGI("Two or more foreground windows: %s and %s",
5628 touchedForegroundWindow->getName().c_str(),
5629 window.windowHandle->getName().c_str());
5630 return nullptr;
5631 }
5632 touchedForegroundWindow = window.windowHandle;
5633 }
5634 }
5635 return touchedForegroundWindow;
5636}
5637
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005638// Binder call
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005639bool InputDispatcher::transferTouch(const sp<IBinder>& destChannelToken, int32_t displayId) {
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005640 sp<IBinder> fromToken;
5641 { // acquire lock
5642 std::scoped_lock _l(mLock);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005643 sp<WindowInfoHandle> toWindowHandle = getWindowHandleLocked(destChannelToken, displayId);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005644 if (toWindowHandle == nullptr) {
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005645 ALOGW("Could not find window associated with token=%p on display %" PRId32,
5646 destChannelToken.get(), displayId);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005647 return false;
5648 }
5649
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005650 sp<WindowInfoHandle> from = findTouchedForegroundWindowLocked(displayId);
5651 if (from == nullptr) {
5652 ALOGE("Could not find a source window in %s for %p", __func__, destChannelToken.get());
5653 return false;
5654 }
5655
5656 fromToken = from->getToken();
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005657 } // release lock
5658
5659 return transferTouchFocus(fromToken, destChannelToken);
5660}
5661
Michael Wrightd02c5b62014-02-10 15:10:22 -08005662void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005663 if (DEBUG_FOCUS) {
5664 ALOGD("Resetting and dropping all events (%s).", reason);
5665 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005666
Michael Wrightfb04fd52022-11-24 22:31:11 +00005667 CancelationOptions options(CancelationOptions::Mode::CANCEL_ALL_EVENTS, reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005668 synthesizeCancelationEventsForAllConnectionsLocked(options);
5669
5670 resetKeyRepeatLocked();
5671 releasePendingEventLocked();
5672 drainInboundQueueLocked();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005673 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005674
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005675 mAnrTracker.clear();
Jeff Brownf086ddb2014-02-11 14:28:48 -08005676 mTouchStatesByDisplay.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005677}
5678
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005679void InputDispatcher::logDispatchStateLocked() const {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005680 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005681 dumpDispatchStateLocked(dump);
5682
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005683 std::istringstream stream(dump);
5684 std::string line;
5685
5686 while (std::getline(stream, line, '\n')) {
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07005687 ALOGI("%s", line.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005688 }
5689}
5690
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005691std::string InputDispatcher::dumpPointerCaptureStateLocked() const {
Prabir Pradhan99987712020-11-10 18:43:05 -08005692 std::string dump;
5693
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005694 dump += StringPrintf(INDENT "Pointer Capture Requested: %s\n",
5695 toString(mCurrentPointerCaptureRequest.enable));
Prabir Pradhan99987712020-11-10 18:43:05 -08005696
5697 std::string windowName = "None";
5698 if (mWindowTokenWithPointerCapture) {
chaviw98318de2021-05-19 16:45:23 -05005699 const sp<WindowInfoHandle> captureWindowHandle =
Prabir Pradhan99987712020-11-10 18:43:05 -08005700 getWindowHandleLocked(mWindowTokenWithPointerCapture);
5701 windowName = captureWindowHandle ? captureWindowHandle->getName().c_str()
5702 : "token has capture without window";
5703 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005704 dump += StringPrintf(INDENT "Current Window with Pointer Capture: %s\n", windowName.c_str());
Prabir Pradhan99987712020-11-10 18:43:05 -08005705
5706 return dump;
5707}
5708
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005709void InputDispatcher::dumpDispatchStateLocked(std::string& dump) const {
Siarhei Vishniakou043a3ec2019-05-01 11:30:46 -07005710 dump += StringPrintf(INDENT "DispatchEnabled: %s\n", toString(mDispatchEnabled));
5711 dump += StringPrintf(INDENT "DispatchFrozen: %s\n", toString(mDispatchFrozen));
5712 dump += StringPrintf(INDENT "InputFilterEnabled: %s\n", toString(mInputFilterEnabled));
Tiger Huang721e26f2018-07-24 22:26:19 +08005713 dump += StringPrintf(INDENT "FocusedDisplayId: %" PRId32 "\n", mFocusedDisplayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005714
Tiger Huang721e26f2018-07-24 22:26:19 +08005715 if (!mFocusedApplicationHandlesByDisplay.empty()) {
5716 dump += StringPrintf(INDENT "FocusedApplications:\n");
5717 for (auto& it : mFocusedApplicationHandlesByDisplay) {
5718 const int32_t displayId = it.first;
Chris Yea209fde2020-07-22 13:54:51 -07005719 const std::shared_ptr<InputApplicationHandle>& applicationHandle = it.second;
Siarhei Vishniakou70622952020-07-30 11:17:23 -05005720 const std::chrono::duration timeout =
5721 applicationHandle->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005722 dump += StringPrintf(INDENT2 "displayId=%" PRId32
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005723 ", name='%s', dispatchingTimeout=%" PRId64 "ms\n",
Siarhei Vishniakou70622952020-07-30 11:17:23 -05005724 displayId, applicationHandle->getName().c_str(), millis(timeout));
Tiger Huang721e26f2018-07-24 22:26:19 +08005725 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005726 } else {
Tiger Huang721e26f2018-07-24 22:26:19 +08005727 dump += StringPrintf(INDENT "FocusedApplications: <none>\n");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005728 }
Tiger Huang721e26f2018-07-24 22:26:19 +08005729
Vishnu Nairc519ff72021-01-21 08:23:08 -08005730 dump += mFocusResolver.dump();
Prabir Pradhan99987712020-11-10 18:43:05 -08005731 dump += dumpPointerCaptureStateLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005732
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005733 if (!mTouchStatesByDisplay.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005734 dump += StringPrintf(INDENT "TouchStatesByDisplay:\n");
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005735 for (const auto& [displayId, state] : mTouchStatesByDisplay) {
Siarhei Vishniakou6e1e9872022-11-08 17:51:35 -08005736 std::string touchStateDump = addLinePrefix(state.dump(), INDENT2);
5737 dump += INDENT2 + std::to_string(displayId) + " : " + touchStateDump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005738 }
5739 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005740 dump += INDENT "TouchStates: <no displays touched>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005741 }
5742
arthurhung6d4bed92021-03-17 11:59:33 +08005743 if (mDragState) {
5744 dump += StringPrintf(INDENT "DragState:\n");
5745 mDragState->dump(dump, INDENT2);
5746 }
5747
Arthur Hungb92218b2018-08-14 12:00:21 +08005748 if (!mWindowHandlesByDisplay.empty()) {
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005749 for (const auto& [displayId, windowHandles] : mWindowHandlesByDisplay) {
5750 dump += StringPrintf(INDENT "Display: %" PRId32 "\n", displayId);
5751 if (const auto& it = mDisplayInfos.find(displayId); it != mDisplayInfos.end()) {
5752 const auto& displayInfo = it->second;
5753 dump += StringPrintf(INDENT2 "logicalSize=%dx%d\n", displayInfo.logicalWidth,
5754 displayInfo.logicalHeight);
5755 displayInfo.transform.dump(dump, "transform", INDENT4);
5756 } else {
5757 dump += INDENT2 "No DisplayInfo found!\n";
5758 }
5759
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08005760 if (!windowHandles.empty()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08005761 dump += INDENT2 "Windows:\n";
5762 for (size_t i = 0; i < windowHandles.size(); i++) {
Siarhei Vishniakou366fb5b2023-12-06 11:23:41 -08005763 dump += StringPrintf(INDENT3 "%zu: %s", i,
5764 streamableToString(*windowHandles[i]).c_str());
Arthur Hungb92218b2018-08-14 12:00:21 +08005765 }
5766 } else {
5767 dump += INDENT2 "Windows: <none>\n";
5768 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005769 }
5770 } else {
Arthur Hungb92218b2018-08-14 12:00:21 +08005771 dump += INDENT "Displays: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005772 }
5773
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005774 if (!mGlobalMonitorsByDisplay.empty()) {
5775 for (const auto& [displayId, monitors] : mGlobalMonitorsByDisplay) {
5776 dump += StringPrintf(INDENT "Global monitors on display %d:\n", displayId);
Michael Wright3dd60e22019-03-27 22:06:44 +00005777 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005778 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005779 } else {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005780 dump += INDENT "Global Monitors: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005781 }
5782
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005783 const nsecs_t currentTime = now();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005784
5785 // Dump recently dispatched or dropped events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005786 if (!mRecentQueue.empty()) {
5787 dump += StringPrintf(INDENT "RecentQueue: length=%zu\n", mRecentQueue.size());
Prabir Pradhan24047542023-11-02 17:14:59 +00005788 for (const std::shared_ptr<const EventEntry>& entry : mRecentQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005789 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005790 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005791 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005792 }
5793 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005794 dump += INDENT "RecentQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005795 }
5796
5797 // Dump event currently being dispatched.
5798 if (mPendingEvent) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005799 dump += INDENT "PendingEvent:\n";
5800 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005801 dump += mPendingEvent->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005802 dump += StringPrintf(", age=%" PRId64 "ms\n",
5803 ns2ms(currentTime - mPendingEvent->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005804 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005805 dump += INDENT "PendingEvent: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005806 }
5807
5808 // Dump inbound events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005809 if (!mInboundQueue.empty()) {
5810 dump += StringPrintf(INDENT "InboundQueue: length=%zu\n", mInboundQueue.size());
Prabir Pradhan24047542023-11-02 17:14:59 +00005811 for (const std::shared_ptr<const EventEntry>& entry : mInboundQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005812 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005813 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005814 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005815 }
5816 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005817 dump += INDENT "InboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005818 }
5819
Prabir Pradhancef936d2021-07-21 16:17:52 +00005820 if (!mCommandQueue.empty()) {
5821 dump += StringPrintf(INDENT "CommandQueue: size=%zu\n", mCommandQueue.size());
5822 } else {
5823 dump += INDENT "CommandQueue: <empty>\n";
5824 }
5825
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005826 if (!mConnectionsByToken.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005827 dump += INDENT "Connections:\n";
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005828 for (const auto& [token, connection] : mConnectionsByToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005829 dump += StringPrintf(INDENT2 "%i: channelName='%s', windowName='%s', "
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005830 "status=%s, monitor=%s, responsive=%s\n",
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005831 connection->inputChannel->getFd().get(),
5832 connection->getInputChannelName().c_str(),
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08005833 connection->getWindowName().c_str(),
5834 ftl::enum_string(connection->status).c_str(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005835 toString(connection->monitor), toString(connection->responsive));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005836
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005837 if (!connection->outboundQueue.empty()) {
5838 dump += StringPrintf(INDENT3 "OutboundQueue: length=%zu\n",
5839 connection->outboundQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005840 dump += dumpQueue(connection->outboundQueue, currentTime);
5841
Michael Wrightd02c5b62014-02-10 15:10:22 -08005842 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005843 dump += INDENT3 "OutboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005844 }
5845
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005846 if (!connection->waitQueue.empty()) {
5847 dump += StringPrintf(INDENT3 "WaitQueue: length=%zu\n",
5848 connection->waitQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005849 dump += dumpQueue(connection->waitQueue, currentTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005850 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005851 dump += INDENT3 "WaitQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005852 }
Siarhei Vishniakou366fb5b2023-12-06 11:23:41 -08005853 std::string inputStateDump = streamableToString(connection->inputState);
5854 if (!inputStateDump.empty()) {
Siarhei Vishniakoud38a1e02023-07-18 11:55:17 -07005855 dump += INDENT3 "InputState: ";
Siarhei Vishniakou366fb5b2023-12-06 11:23:41 -08005856 dump += inputStateDump + "\n";
Siarhei Vishniakoud38a1e02023-07-18 11:55:17 -07005857 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005858 }
5859 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005860 dump += INDENT "Connections: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005861 }
5862
Antonio Kantek15beb512022-06-13 22:35:41 +00005863 if (!mTouchModePerDisplay.empty()) {
5864 dump += INDENT "TouchModePerDisplay:\n";
5865 for (const auto& [displayId, touchMode] : mTouchModePerDisplay) {
5866 dump += StringPrintf(INDENT2 "Display: %" PRId32 " TouchMode: %s\n", displayId,
5867 std::to_string(touchMode).c_str());
5868 }
5869 } else {
5870 dump += INDENT "TouchModePerDisplay: <none>\n";
5871 }
5872
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005873 dump += INDENT "Configuration:\n";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005874 dump += StringPrintf(INDENT2 "KeyRepeatDelay: %" PRId64 "ms\n", ns2ms(mConfig.keyRepeatDelay));
5875 dump += StringPrintf(INDENT2 "KeyRepeatTimeout: %" PRId64 "ms\n",
5876 ns2ms(mConfig.keyRepeatTimeout));
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00005877 dump += mLatencyTracker.dump(INDENT2);
Siarhei Vishniakoua04181f2021-03-26 05:56:49 +00005878 dump += mLatencyAggregator.dump(INDENT2);
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00005879 dump += INDENT "InputTracer: ";
5880 dump += mTracer == nullptr ? "Disabled" : "Enabled";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005881}
5882
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005883void InputDispatcher::dumpMonitors(std::string& dump, const std::vector<Monitor>& monitors) const {
Michael Wright3dd60e22019-03-27 22:06:44 +00005884 const size_t numMonitors = monitors.size();
5885 for (size_t i = 0; i < numMonitors; i++) {
5886 const Monitor& monitor = monitors[i];
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005887 const std::shared_ptr<InputChannel>& channel = monitor.inputChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005888 dump += StringPrintf(INDENT2 "%zu: '%s', ", i, channel->getName().c_str());
5889 dump += "\n";
5890 }
5891}
5892
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005893class LooperEventCallback : public LooperCallback {
5894public:
5895 LooperEventCallback(std::function<int(int events)> callback) : mCallback(callback) {}
5896 int handleEvent(int /*fd*/, int events, void* /*data*/) override { return mCallback(events); }
5897
5898private:
5899 std::function<int(int events)> mCallback;
5900};
5901
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005902Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputChannel(const std::string& name) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00005903 if (DEBUG_CHANNEL_CREATION) {
5904 ALOGD("channel '%s' ~ createInputChannel", name.c_str());
5905 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005906
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005907 std::unique_ptr<InputChannel> serverChannel;
Garfield Tan15601662020-09-22 15:32:38 -07005908 std::unique_ptr<InputChannel> clientChannel;
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005909 status_t result = InputChannel::openInputChannelPair(name, serverChannel, clientChannel);
Garfield Tan15601662020-09-22 15:32:38 -07005910
5911 if (result) {
5912 return base::Error(result) << "Failed to open input channel pair with name " << name;
5913 }
5914
Michael Wrightd02c5b62014-02-10 15:10:22 -08005915 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005916 std::scoped_lock _l(mLock);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005917 const sp<IBinder>& token = serverChannel->getConnectionToken();
Tomasz Wasilczyk32024602023-11-16 10:17:54 -08005918 auto&& fd = serverChannel->getFd();
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07005919 std::shared_ptr<Connection> connection =
5920 std::make_shared<Connection>(std::move(serverChannel), /*monitor=*/false,
5921 mIdGenerator);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005922
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005923 if (mConnectionsByToken.find(token) != mConnectionsByToken.end()) {
5924 ALOGE("Created a new connection, but the token %p is already known", token.get());
5925 }
5926 mConnectionsByToken.emplace(token, connection);
5927
5928 std::function<int(int events)> callback = std::bind(&InputDispatcher::handleReceiveCallback,
5929 this, std::placeholders::_1, token);
5930
Tomasz Wasilczyk32024602023-11-16 10:17:54 -08005931 mLooper->addFd(fd.get(), 0, ALOOPER_EVENT_INPUT, sp<LooperEventCallback>::make(callback),
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005932 nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005933 } // release lock
5934
5935 // Wake the looper because some connections have changed.
5936 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07005937 return clientChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005938}
5939
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005940Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputMonitor(int32_t displayId,
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005941 const std::string& name,
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005942 gui::Pid pid) {
Garfield Tan15601662020-09-22 15:32:38 -07005943 std::shared_ptr<InputChannel> serverChannel;
5944 std::unique_ptr<InputChannel> clientChannel;
5945 status_t result = openInputChannelPair(name, serverChannel, clientChannel);
5946 if (result) {
5947 return base::Error(result) << "Failed to open input channel pair with name " << name;
5948 }
5949
Michael Wright3dd60e22019-03-27 22:06:44 +00005950 { // acquire lock
5951 std::scoped_lock _l(mLock);
5952
5953 if (displayId < 0) {
Garfield Tan15601662020-09-22 15:32:38 -07005954 return base::Error(BAD_VALUE) << "Attempted to create input monitor with name " << name
5955 << " without a specified display.";
Michael Wright3dd60e22019-03-27 22:06:44 +00005956 }
5957
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07005958 std::shared_ptr<Connection> connection =
5959 std::make_shared<Connection>(serverChannel, /*monitor=*/true, mIdGenerator);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005960 const sp<IBinder>& token = serverChannel->getConnectionToken();
Tomasz Wasilczyk32024602023-11-16 10:17:54 -08005961 auto&& fd = serverChannel->getFd();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005962
5963 if (mConnectionsByToken.find(token) != mConnectionsByToken.end()) {
5964 ALOGE("Created a new connection, but the token %p is already known", token.get());
5965 }
5966 mConnectionsByToken.emplace(token, connection);
5967 std::function<int(int events)> callback = std::bind(&InputDispatcher::handleReceiveCallback,
5968 this, std::placeholders::_1, token);
Michael Wright3dd60e22019-03-27 22:06:44 +00005969
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005970 mGlobalMonitorsByDisplay[displayId].emplace_back(serverChannel, pid);
Michael Wright3dd60e22019-03-27 22:06:44 +00005971
Tomasz Wasilczyk32024602023-11-16 10:17:54 -08005972 mLooper->addFd(fd.get(), 0, ALOOPER_EVENT_INPUT, sp<LooperEventCallback>::make(callback),
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005973 nullptr);
Michael Wright3dd60e22019-03-27 22:06:44 +00005974 }
Garfield Tan15601662020-09-22 15:32:38 -07005975
Michael Wright3dd60e22019-03-27 22:06:44 +00005976 // Wake the looper because some connections have changed.
5977 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07005978 return clientChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005979}
5980
Garfield Tan15601662020-09-22 15:32:38 -07005981status_t InputDispatcher::removeInputChannel(const sp<IBinder>& connectionToken) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005982 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005983 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005984
Harry Cutts33476232023-01-30 19:57:29 +00005985 status_t status = removeInputChannelLocked(connectionToken, /*notify=*/false);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005986 if (status) {
5987 return status;
5988 }
5989 } // release lock
5990
5991 // Wake the poll loop because removing the connection may have changed the current
5992 // synchronization state.
5993 mLooper->wake();
5994 return OK;
5995}
5996
Garfield Tan15601662020-09-22 15:32:38 -07005997status_t InputDispatcher::removeInputChannelLocked(const sp<IBinder>& connectionToken,
5998 bool notify) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07005999 std::shared_ptr<Connection> connection = getConnectionLocked(connectionToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07006000 if (connection == nullptr) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00006001 // Connection can be removed via socket hang up or an explicit call to 'removeInputChannel'
Michael Wrightd02c5b62014-02-10 15:10:22 -08006002 return BAD_VALUE;
6003 }
6004
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07006005 removeConnectionLocked(connection);
Robert Carr5c8a0262018-10-03 16:30:44 -07006006
Michael Wrightd02c5b62014-02-10 15:10:22 -08006007 if (connection->monitor) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05006008 removeMonitorChannelLocked(connectionToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006009 }
6010
Tomasz Wasilczyk32024602023-11-16 10:17:54 -08006011 mLooper->removeFd(connection->inputChannel->getFd().get());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006012
6013 nsecs_t currentTime = now();
6014 abortBrokenDispatchCycleLocked(currentTime, connection, notify);
6015
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08006016 connection->status = Connection::Status::ZOMBIE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006017 return OK;
6018}
6019
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05006020void InputDispatcher::removeMonitorChannelLocked(const sp<IBinder>& connectionToken) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006021 for (auto it = mGlobalMonitorsByDisplay.begin(); it != mGlobalMonitorsByDisplay.end();) {
6022 auto& [displayId, monitors] = *it;
6023 std::erase_if(monitors, [connectionToken](const Monitor& monitor) {
6024 return monitor.inputChannel->getConnectionToken() == connectionToken;
6025 });
Michael Wright3dd60e22019-03-27 22:06:44 +00006026
Michael Wright3dd60e22019-03-27 22:06:44 +00006027 if (monitors.empty()) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006028 it = mGlobalMonitorsByDisplay.erase(it);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08006029 } else {
6030 ++it;
6031 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006032 }
6033}
6034
Michael Wright3dd60e22019-03-27 22:06:44 +00006035status_t InputDispatcher::pilferPointers(const sp<IBinder>& token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006036 std::scoped_lock _l(mLock);
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00006037 return pilferPointersLocked(token);
6038}
Michael Wright3dd60e22019-03-27 22:06:44 +00006039
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00006040status_t InputDispatcher::pilferPointersLocked(const sp<IBinder>& token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006041 const std::shared_ptr<InputChannel> requestingChannel = getInputChannelLocked(token);
6042 if (!requestingChannel) {
Siarhei Vishniakou8384e0d2023-09-18 18:48:27 -07006043 LOG(WARNING)
6044 << "Attempted to pilfer pointers from an un-registered channel or invalid token";
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006045 return BAD_VALUE;
Michael Wright3dd60e22019-03-27 22:06:44 +00006046 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006047
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07006048 auto [statePtr, windowPtr, displayId] = findTouchStateWindowAndDisplayLocked(token);
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07006049 if (statePtr == nullptr || windowPtr == nullptr) {
Siarhei Vishniakou8384e0d2023-09-18 18:48:27 -07006050 LOG(WARNING)
6051 << "Attempted to pilfer points from a channel without any on-going pointer streams."
6052 " Ignoring.";
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006053 return BAD_VALUE;
6054 }
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07006055 std::set<int32_t> deviceIds = windowPtr->getTouchingDeviceIds();
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07006056 if (deviceIds.empty()) {
6057 LOG(WARNING) << "Can't pilfer: no touching devices in window: " << windowPtr->dump();
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07006058 return BAD_VALUE;
6059 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006060
Siarhei Vishniakou8384e0d2023-09-18 18:48:27 -07006061 for (const DeviceId deviceId : deviceIds) {
6062 TouchState& state = *statePtr;
6063 TouchedWindow& window = *windowPtr;
6064 // Send cancel events to all the input channels we're stealing from.
6065 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
6066 "input channel stole pointer stream");
6067 options.deviceId = deviceId;
6068 options.displayId = displayId;
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08006069 std::vector<PointerProperties> pointers = window.getTouchingPointers(deviceId);
6070 std::bitset<MAX_POINTER_ID + 1> pointerIds = getPointerIds(pointers);
Siarhei Vishniakou8384e0d2023-09-18 18:48:27 -07006071 options.pointerIds = pointerIds;
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08006072
Siarhei Vishniakou8384e0d2023-09-18 18:48:27 -07006073 std::string canceledWindows;
6074 for (const TouchedWindow& w : state.windows) {
6075 const std::shared_ptr<InputChannel> channel =
6076 getInputChannelLocked(w.windowHandle->getToken());
6077 if (channel != nullptr && channel->getConnectionToken() != token) {
6078 synthesizeCancelationEventsForInputChannelLocked(channel, options);
6079 canceledWindows += canceledWindows.empty() ? "[" : ", ";
6080 canceledWindows += channel->getName();
6081 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006082 }
Siarhei Vishniakou8384e0d2023-09-18 18:48:27 -07006083 canceledWindows += canceledWindows.empty() ? "[]" : "]";
6084 LOG(INFO) << "Channel " << requestingChannel->getName()
6085 << " is stealing input gesture for device " << deviceId << " from "
6086 << canceledWindows;
6087
6088 // Prevent the gesture from being sent to any other windows.
6089 // This only blocks relevant pointers to be sent to other windows
6090 window.addPilferingPointers(deviceId, pointerIds);
6091
6092 state.cancelPointersForWindowsExcept(deviceId, pointerIds, token);
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006093 }
Michael Wright3dd60e22019-03-27 22:06:44 +00006094 return OK;
6095}
6096
Prabir Pradhan99987712020-11-10 18:43:05 -08006097void InputDispatcher::requestPointerCapture(const sp<IBinder>& windowToken, bool enabled) {
6098 { // acquire lock
6099 std::scoped_lock _l(mLock);
6100 if (DEBUG_FOCUS) {
chaviw98318de2021-05-19 16:45:23 -05006101 const sp<WindowInfoHandle> windowHandle = getWindowHandleLocked(windowToken);
Prabir Pradhan99987712020-11-10 18:43:05 -08006102 ALOGI("Request to %s Pointer Capture from: %s.", enabled ? "enable" : "disable",
6103 windowHandle != nullptr ? windowHandle->getName().c_str()
6104 : "token without window");
6105 }
6106
Vishnu Nairc519ff72021-01-21 08:23:08 -08006107 const sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Prabir Pradhan99987712020-11-10 18:43:05 -08006108 if (focusedToken != windowToken) {
6109 ALOGW("Ignoring request to %s Pointer Capture: window does not have focus.",
6110 enabled ? "enable" : "disable");
6111 return;
6112 }
6113
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006114 if (enabled == mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006115 ALOGW("Ignoring request to %s Pointer Capture: "
6116 "window has %s requested pointer capture.",
6117 enabled ? "enable" : "disable", enabled ? "already" : "not");
6118 return;
6119 }
6120
Christine Franksb768bb42021-11-29 12:11:31 -08006121 if (enabled) {
6122 if (std::find(mIneligibleDisplaysForPointerCapture.begin(),
6123 mIneligibleDisplaysForPointerCapture.end(),
6124 mFocusedDisplayId) != mIneligibleDisplaysForPointerCapture.end()) {
6125 ALOGW("Ignoring request to enable Pointer Capture: display is not eligible");
6126 return;
6127 }
6128 }
6129
Prabir Pradhan99987712020-11-10 18:43:05 -08006130 setPointerCaptureLocked(enabled);
6131 } // release lock
6132
6133 // Wake the thread to process command entries.
6134 mLooper->wake();
6135}
6136
Christine Franksb768bb42021-11-29 12:11:31 -08006137void InputDispatcher::setDisplayEligibilityForPointerCapture(int32_t displayId, bool isEligible) {
6138 { // acquire lock
6139 std::scoped_lock _l(mLock);
6140 std::erase(mIneligibleDisplaysForPointerCapture, displayId);
6141 if (!isEligible) {
6142 mIneligibleDisplaysForPointerCapture.push_back(displayId);
6143 }
6144 } // release lock
6145}
6146
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00006147std::optional<gui::Pid> InputDispatcher::findMonitorPidByTokenLocked(const sp<IBinder>& token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006148 for (const auto& [_, monitors] : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00006149 for (const Monitor& monitor : monitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07006150 if (monitor.inputChannel->getConnectionToken() == token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006151 return monitor.pid;
Michael Wright3dd60e22019-03-27 22:06:44 +00006152 }
6153 }
6154 }
6155 return std::nullopt;
6156}
6157
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006158std::shared_ptr<Connection> InputDispatcher::getConnectionLocked(
6159 const sp<IBinder>& inputConnectionToken) const {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07006160 if (inputConnectionToken == nullptr) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07006161 return nullptr;
Arthur Hung3b413f22018-10-26 18:05:34 +08006162 }
6163
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00006164 for (const auto& [token, connection] : mConnectionsByToken) {
6165 if (token == inputConnectionToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07006166 return connection;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006167 }
6168 }
Robert Carr4e670e52018-08-15 13:26:12 -07006169
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07006170 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006171}
6172
Siarhei Vishniakouad991402020-10-28 11:40:09 -05006173std::string InputDispatcher::getConnectionNameLocked(const sp<IBinder>& connectionToken) const {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006174 std::shared_ptr<Connection> connection = getConnectionLocked(connectionToken);
Siarhei Vishniakouad991402020-10-28 11:40:09 -05006175 if (connection == nullptr) {
6176 return "<nullptr>";
6177 }
6178 return connection->getInputChannelName();
6179}
6180
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006181void InputDispatcher::removeConnectionLocked(const std::shared_ptr<Connection>& connection) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006182 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00006183 mConnectionsByToken.erase(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07006184}
6185
Prabir Pradhancef936d2021-07-21 16:17:52 +00006186void InputDispatcher::doDispatchCycleFinishedCommand(nsecs_t finishTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006187 const std::shared_ptr<Connection>& connection,
6188 uint32_t seq, bool handled,
6189 nsecs_t consumeTime) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006190 // Handle post-event policy actions.
Prabir Pradhan24047542023-11-02 17:14:59 +00006191 std::unique_ptr<const KeyEntry> fallbackKeyEntry;
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006192
6193 { // Start critical section
6194 auto dispatchEntryIt =
6195 std::find_if(connection->waitQueue.begin(), connection->waitQueue.end(),
6196 [seq](auto& e) { return e->seq == seq; });
6197 if (dispatchEntryIt == connection->waitQueue.end()) {
6198 return;
6199 }
6200
6201 DispatchEntry& dispatchEntry = **dispatchEntryIt;
6202
6203 const nsecs_t eventDuration = finishTime - dispatchEntry.deliveryTime;
6204 if (eventDuration > SLOW_EVENT_PROCESSING_WARNING_TIMEOUT) {
6205 ALOGI("%s spent %" PRId64 "ms processing %s", connection->getWindowName().c_str(),
6206 ns2ms(eventDuration), dispatchEntry.eventEntry->getDescription().c_str());
6207 }
6208 if (shouldReportFinishedEvent(dispatchEntry, *connection)) {
6209 mLatencyTracker.trackFinishedEvent(dispatchEntry.eventEntry->id,
6210 connection->inputChannel->getConnectionToken(),
6211 dispatchEntry.deliveryTime, consumeTime, finishTime);
6212 }
6213
6214 if (dispatchEntry.eventEntry->type == EventEntry::Type::KEY) {
Prabir Pradhanb9dd1642023-11-02 18:05:36 +00006215 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(*(dispatchEntry.eventEntry));
6216 fallbackKeyEntry =
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006217 afterKeyEventLockedInterruptable(connection, dispatchEntry, keyEntry, handled);
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006218 }
6219 } // End critical section: The -LockedInterruptable methods may have released the lock.
Prabir Pradhancef936d2021-07-21 16:17:52 +00006220
6221 // Dequeue the event and start the next cycle.
6222 // Because the lock might have been released, it is possible that the
6223 // contents of the wait queue to have been drained, so we need to double-check
6224 // a few things.
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006225 auto entryIt = std::find_if(connection->waitQueue.begin(), connection->waitQueue.end(),
6226 [seq](auto& e) { return e->seq == seq; });
6227 if (entryIt != connection->waitQueue.end()) {
6228 std::unique_ptr<DispatchEntry> dispatchEntry = std::move(*entryIt);
6229 connection->waitQueue.erase(entryIt);
6230
Prabir Pradhancef936d2021-07-21 16:17:52 +00006231 const sp<IBinder>& connectionToken = connection->inputChannel->getConnectionToken();
6232 mAnrTracker.erase(dispatchEntry->timeoutTime, connectionToken);
6233 if (!connection->responsive) {
6234 connection->responsive = isConnectionResponsive(*connection);
6235 if (connection->responsive) {
6236 // The connection was unresponsive, and now it's responsive.
6237 processConnectionResponsiveLocked(*connection);
6238 }
6239 }
6240 traceWaitQueueLength(*connection);
Prabir Pradhanb9dd1642023-11-02 18:05:36 +00006241 if (fallbackKeyEntry && connection->status == Connection::Status::NORMAL) {
6242 const InputTarget target{.inputChannel = connection->inputChannel,
6243 .flags = dispatchEntry->targetFlags};
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00006244 enqueueDispatchEntryLocked(connection, std::move(fallbackKeyEntry), target);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006245 }
Prabir Pradhanb9dd1642023-11-02 18:05:36 +00006246 releaseDispatchEntry(std::move(dispatchEntry));
Prabir Pradhancef936d2021-07-21 16:17:52 +00006247 }
6248
6249 // Start the next dispatch cycle for this connection.
6250 startDispatchCycleLocked(now(), connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006251}
6252
Prabir Pradhancef936d2021-07-21 16:17:52 +00006253void InputDispatcher::sendFocusChangedCommandLocked(const sp<IBinder>& oldToken,
6254 const sp<IBinder>& newToken) {
6255 auto command = [this, oldToken, newToken]() REQUIRES(mLock) {
6256 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00006257 mPolicy.notifyFocusChanged(oldToken, newToken);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006258 };
6259 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08006260}
6261
Prabir Pradhancef936d2021-07-21 16:17:52 +00006262void InputDispatcher::sendDropWindowCommandLocked(const sp<IBinder>& token, float x, float y) {
6263 auto command = [this, token, x, y]() REQUIRES(mLock) {
6264 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00006265 mPolicy.notifyDropWindow(token, x, y);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006266 };
6267 postCommandLocked(std::move(command));
Robert Carrf759f162018-11-13 12:57:11 -08006268}
6269
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006270void InputDispatcher::onAnrLocked(const std::shared_ptr<Connection>& connection) {
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006271 if (connection == nullptr) {
6272 LOG_ALWAYS_FATAL("Caller must check for nullness");
6273 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006274 // Since we are allowing the policy to extend the timeout, maybe the waitQueue
6275 // is already healthy again. Don't raise ANR in this situation
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006276 if (connection->waitQueue.empty()) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006277 ALOGI("Not raising ANR because the connection %s has recovered",
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006278 connection->inputChannel->getName().c_str());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006279 return;
6280 }
6281 /**
6282 * The "oldestEntry" is the entry that was first sent to the application. That entry, however,
6283 * may not be the one that caused the timeout to occur. One possibility is that window timeout
6284 * has changed. This could cause newer entries to time out before the already dispatched
6285 * entries. In that situation, the newest entries caused ANR. But in all likelihood, the app
6286 * processes the events linearly. So providing information about the oldest entry seems to be
6287 * most useful.
6288 */
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006289 DispatchEntry& oldestEntry = *connection->waitQueue.front();
6290 const nsecs_t currentWait = now() - oldestEntry.deliveryTime;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006291 std::string reason =
6292 android::base::StringPrintf("%s is not responding. Waited %" PRId64 "ms for %s",
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006293 connection->inputChannel->getName().c_str(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006294 ns2ms(currentWait),
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006295 oldestEntry.eventEntry->getDescription().c_str());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006296 sp<IBinder> connectionToken = connection->inputChannel->getConnectionToken();
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -06006297 updateLastAnrStateLocked(getWindowHandleLocked(connectionToken), reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006298
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006299 processConnectionUnresponsiveLocked(*connection, std::move(reason));
6300
6301 // Stop waking up for events on this connection, it is already unresponsive
6302 cancelEventsForAnrLocked(connection);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006303}
6304
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05006305void InputDispatcher::onAnrLocked(std::shared_ptr<InputApplicationHandle> application) {
6306 std::string reason =
6307 StringPrintf("%s does not have a focused window", application->getName().c_str());
6308 updateLastAnrStateLocked(*application, reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006309
Yabin Cui8eb9c552023-06-08 18:05:07 +00006310 auto command = [this, app = std::move(application)]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006311 scoped_unlock unlock(mLock);
Yabin Cuiced952f2023-06-09 21:12:51 +00006312 mPolicy.notifyNoFocusedWindowAnr(app);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006313 };
6314 postCommandLocked(std::move(command));
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00006315}
6316
chaviw98318de2021-05-19 16:45:23 -05006317void InputDispatcher::updateLastAnrStateLocked(const sp<WindowInfoHandle>& window,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006318 const std::string& reason) {
6319 const std::string windowLabel = getApplicationWindowLabel(nullptr, window);
6320 updateLastAnrStateLocked(windowLabel, reason);
6321}
6322
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05006323void InputDispatcher::updateLastAnrStateLocked(const InputApplicationHandle& application,
6324 const std::string& reason) {
6325 const std::string windowLabel = getApplicationWindowLabel(&application, nullptr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006326 updateLastAnrStateLocked(windowLabel, reason);
6327}
6328
6329void InputDispatcher::updateLastAnrStateLocked(const std::string& windowLabel,
6330 const std::string& reason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006331 // Capture a record of the InputDispatcher state at the time of the ANR.
Yi Kong9b14ac62018-07-17 13:48:38 -07006332 time_t t = time(nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006333 struct tm tm;
6334 localtime_r(&t, &tm);
6335 char timestr[64];
6336 strftime(timestr, sizeof(timestr), "%F %T", &tm);
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006337 mLastAnrState.clear();
6338 mLastAnrState += INDENT "ANR:\n";
6339 mLastAnrState += StringPrintf(INDENT2 "Time: %s\n", timestr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006340 mLastAnrState += StringPrintf(INDENT2 "Reason: %s\n", reason.c_str());
6341 mLastAnrState += StringPrintf(INDENT2 "Window: %s\n", windowLabel.c_str());
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006342 dumpDispatchStateLocked(mLastAnrState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006343}
6344
Prabir Pradhancef936d2021-07-21 16:17:52 +00006345void InputDispatcher::doInterceptKeyBeforeDispatchingCommand(const sp<IBinder>& focusedWindowToken,
Prabir Pradhan24047542023-11-02 17:14:59 +00006346 const KeyEntry& entry) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006347 const KeyEvent event = createKeyEvent(entry);
6348 nsecs_t delay = 0;
6349 { // release lock
6350 scoped_unlock unlock(mLock);
6351 android::base::Timer t;
Prabir Pradhana41d2442023-04-20 21:30:40 +00006352 delay = mPolicy.interceptKeyBeforeDispatching(focusedWindowToken, event, entry.policyFlags);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006353 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
6354 ALOGW("Excessive delay in interceptKeyBeforeDispatching; took %s ms",
6355 std::to_string(t.duration().count()).c_str());
6356 }
6357 } // acquire lock
Michael Wrightd02c5b62014-02-10 15:10:22 -08006358
6359 if (delay < 0) {
Michael Wright5caf55a2022-11-24 22:31:42 +00006360 entry.interceptKeyResult = KeyEntry::InterceptKeyResult::SKIP;
Prabir Pradhancef936d2021-07-21 16:17:52 +00006361 } else if (delay == 0) {
Michael Wright5caf55a2022-11-24 22:31:42 +00006362 entry.interceptKeyResult = KeyEntry::InterceptKeyResult::CONTINUE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006363 } else {
Michael Wright5caf55a2022-11-24 22:31:42 +00006364 entry.interceptKeyResult = KeyEntry::InterceptKeyResult::TRY_AGAIN_LATER;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006365 entry.interceptKeyWakeupTime = now() + delay;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006366 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006367}
6368
Prabir Pradhancef936d2021-07-21 16:17:52 +00006369void InputDispatcher::sendWindowUnresponsiveCommandLocked(const sp<IBinder>& token,
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00006370 std::optional<gui::Pid> pid,
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006371 std::string reason) {
Yabin Cui8eb9c552023-06-08 18:05:07 +00006372 auto command = [this, token, pid, r = std::move(reason)]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006373 scoped_unlock unlock(mLock);
Yabin Cuiced952f2023-06-09 21:12:51 +00006374 mPolicy.notifyWindowUnresponsive(token, pid, r);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006375 };
6376 postCommandLocked(std::move(command));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006377}
6378
Prabir Pradhanedd96402022-02-15 01:46:16 -08006379void InputDispatcher::sendWindowResponsiveCommandLocked(const sp<IBinder>& token,
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00006380 std::optional<gui::Pid> pid) {
Prabir Pradhanedd96402022-02-15 01:46:16 -08006381 auto command = [this, token, pid]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006382 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00006383 mPolicy.notifyWindowResponsive(token, pid);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006384 };
6385 postCommandLocked(std::move(command));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006386}
6387
6388/**
6389 * Tell the policy that a connection has become unresponsive so that it can start ANR.
6390 * Check whether the connection of interest is a monitor or a window, and add the corresponding
6391 * command entry to the command queue.
6392 */
6393void InputDispatcher::processConnectionUnresponsiveLocked(const Connection& connection,
6394 std::string reason) {
6395 const sp<IBinder>& connectionToken = connection.inputChannel->getConnectionToken();
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00006396 std::optional<gui::Pid> pid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006397 if (connection.monitor) {
6398 ALOGW("Monitor %s is unresponsive: %s", connection.inputChannel->getName().c_str(),
6399 reason.c_str());
Prabir Pradhanedd96402022-02-15 01:46:16 -08006400 pid = findMonitorPidByTokenLocked(connectionToken);
6401 } else {
6402 // The connection is a window
6403 ALOGW("Window %s is unresponsive: %s", connection.inputChannel->getName().c_str(),
6404 reason.c_str());
6405 const sp<WindowInfoHandle> handle = getWindowHandleLocked(connectionToken);
6406 if (handle != nullptr) {
6407 pid = handle->getInfo()->ownerPid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006408 }
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006409 }
Prabir Pradhanedd96402022-02-15 01:46:16 -08006410 sendWindowUnresponsiveCommandLocked(connectionToken, pid, std::move(reason));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006411}
6412
6413/**
6414 * Tell the policy that a connection has become responsive so that it can stop ANR.
6415 */
6416void InputDispatcher::processConnectionResponsiveLocked(const Connection& connection) {
6417 const sp<IBinder>& connectionToken = connection.inputChannel->getConnectionToken();
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00006418 std::optional<gui::Pid> pid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006419 if (connection.monitor) {
Prabir Pradhanedd96402022-02-15 01:46:16 -08006420 pid = findMonitorPidByTokenLocked(connectionToken);
6421 } else {
6422 // The connection is a window
6423 const sp<WindowInfoHandle> handle = getWindowHandleLocked(connectionToken);
6424 if (handle != nullptr) {
6425 pid = handle->getInfo()->ownerPid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006426 }
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006427 }
Prabir Pradhanedd96402022-02-15 01:46:16 -08006428 sendWindowResponsiveCommandLocked(connectionToken, pid);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006429}
6430
Prabir Pradhan24047542023-11-02 17:14:59 +00006431std::unique_ptr<const KeyEntry> InputDispatcher::afterKeyEventLockedInterruptable(
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006432 const std::shared_ptr<Connection>& connection, DispatchEntry& dispatchEntry,
Prabir Pradhanb9dd1642023-11-02 18:05:36 +00006433 const KeyEntry& keyEntry, bool handled) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006434 if (keyEntry.flags & AKEY_EVENT_FLAG_FALLBACK) {
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006435 if (!handled) {
6436 // Report the key as unhandled, since the fallback was not handled.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006437 mReporter->reportUnhandledKey(keyEntry.id);
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006438 }
Prabir Pradhanb9dd1642023-11-02 18:05:36 +00006439 return {};
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006440 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006441
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006442 // Get the fallback key state.
6443 // Clear it out after dispatching the UP.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006444 int32_t originalKeyCode = keyEntry.keyCode;
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006445 std::optional<int32_t> fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006446 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006447 connection->inputState.removeFallbackKey(originalKeyCode);
6448 }
6449
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006450 if (handled || !dispatchEntry.hasForegroundTarget()) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006451 // If the application handles the original key for which we previously
6452 // generated a fallback or if the window is not a foreground window,
6453 // then cancel the associated fallback key, if any.
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006454 if (fallbackKeyCode) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006455 // Dispatch the unhandled key to the policy with the cancel flag.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006456 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6457 ALOGD("Unhandled key event: Asking policy to cancel fallback action. "
6458 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6459 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount,
6460 keyEntry.policyFlags);
6461 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006462 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006463 event.setFlags(event.getFlags() | AKEY_EVENT_FLAG_CANCELED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006464
6465 mLock.unlock();
6466
Prabir Pradhana41d2442023-04-20 21:30:40 +00006467 if (const auto unhandledKeyFallback =
6468 mPolicy.dispatchUnhandledKey(connection->inputChannel->getConnectionToken(),
6469 event, keyEntry.policyFlags);
6470 unhandledKeyFallback) {
6471 event = *unhandledKeyFallback;
6472 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006473
6474 mLock.lock();
6475
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006476 // Cancel the fallback key.
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006477 if (*fallbackKeyCode != AKEYCODE_UNKNOWN) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00006478 CancelationOptions options(CancelationOptions::Mode::CANCEL_FALLBACK_EVENTS,
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006479 "application handled the original non-fallback key "
6480 "or is no longer a foreground target, "
6481 "canceling previously dispatched fallback key");
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006482 options.keyCode = *fallbackKeyCode;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006483 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006484 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006485 connection->inputState.removeFallbackKey(originalKeyCode);
6486 }
6487 } else {
6488 // If the application did not handle a non-fallback key, first check
6489 // that we are in a good state to perform unhandled key event processing
6490 // Then ask the policy what to do with it.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006491 bool initialDown = keyEntry.action == AKEY_EVENT_ACTION_DOWN && keyEntry.repeatCount == 0;
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006492 if (!fallbackKeyCode && !initialDown) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006493 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6494 ALOGD("Unhandled key event: Skipping unhandled key event processing "
6495 "since this is not an initial down. "
6496 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6497 originalKeyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
6498 }
Prabir Pradhanb9dd1642023-11-02 18:05:36 +00006499 return {};
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006500 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006501
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006502 // Dispatch the unhandled key to the policy.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006503 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6504 ALOGD("Unhandled key event: Asking policy to perform fallback action. "
6505 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6506 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
6507 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006508 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006509
6510 mLock.unlock();
6511
Prabir Pradhana41d2442023-04-20 21:30:40 +00006512 bool fallback = false;
6513 if (auto fb = mPolicy.dispatchUnhandledKey(connection->inputChannel->getConnectionToken(),
6514 event, keyEntry.policyFlags);
6515 fb) {
6516 fallback = true;
6517 event = *fb;
6518 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006519
6520 mLock.lock();
6521
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08006522 if (connection->status != Connection::Status::NORMAL) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006523 connection->inputState.removeFallbackKey(originalKeyCode);
Prabir Pradhanb9dd1642023-11-02 18:05:36 +00006524 return {};
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006525 }
6526
6527 // Latch the fallback keycode for this key on an initial down.
6528 // The fallback keycode cannot change at any other point in the lifecycle.
6529 if (initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006530 if (fallback) {
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006531 *fallbackKeyCode = event.getKeyCode();
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006532 } else {
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006533 *fallbackKeyCode = AKEYCODE_UNKNOWN;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006534 }
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006535 connection->inputState.setFallbackKey(originalKeyCode, *fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006536 }
6537
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006538 ALOG_ASSERT(fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006539
6540 // Cancel the fallback key if the policy decides not to send it anymore.
6541 // We will continue to dispatch the key to the policy but we will no
6542 // longer dispatch a fallback key to the application.
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006543 if (*fallbackKeyCode != AKEYCODE_UNKNOWN &&
6544 (!fallback || *fallbackKeyCode != event.getKeyCode())) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006545 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6546 if (fallback) {
6547 ALOGD("Unhandled key event: Policy requested to send key %d"
6548 "as a fallback for %d, but on the DOWN it had requested "
6549 "to send %d instead. Fallback canceled.",
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006550 event.getKeyCode(), originalKeyCode, *fallbackKeyCode);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006551 } else {
6552 ALOGD("Unhandled key event: Policy did not request fallback for %d, "
6553 "but on the DOWN it had requested to send %d. "
6554 "Fallback canceled.",
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006555 originalKeyCode, *fallbackKeyCode);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006556 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006557 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006558
Michael Wrightfb04fd52022-11-24 22:31:11 +00006559 CancelationOptions options(CancelationOptions::Mode::CANCEL_FALLBACK_EVENTS,
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006560 "canceling fallback, policy no longer desires it");
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006561 options.keyCode = *fallbackKeyCode;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006562 synthesizeCancelationEventsForConnectionLocked(connection, options);
6563
6564 fallback = false;
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006565 *fallbackKeyCode = AKEYCODE_UNKNOWN;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006566 if (keyEntry.action != AKEY_EVENT_ACTION_UP) {
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006567 connection->inputState.setFallbackKey(originalKeyCode, *fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006568 }
6569 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006570
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006571 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6572 {
6573 std::string msg;
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006574 const std::map<int32_t, int32_t>& fallbackKeys =
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006575 connection->inputState.getFallbackKeys();
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006576 for (const auto& [key, value] : fallbackKeys) {
6577 msg += StringPrintf(", %d->%d", key, value);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006578 }
6579 ALOGD("Unhandled key event: %zu currently tracked fallback keys%s.",
6580 fallbackKeys.size(), msg.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006581 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006582 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006583
6584 if (fallback) {
Prabir Pradhanb9dd1642023-11-02 18:05:36 +00006585 // Return the fallback key that we want dispatched to the channel.
6586 std::unique_ptr<KeyEntry> newEntry =
6587 std::make_unique<KeyEntry>(mIdGenerator.nextId(), keyEntry.injectionState,
6588 event.getEventTime(), event.getDeviceId(),
6589 event.getSource(), event.getDisplayId(),
6590 keyEntry.policyFlags, keyEntry.action,
6591 event.getFlags() | AKEY_EVENT_FLAG_FALLBACK,
6592 *fallbackKeyCode, event.getScanCode(),
6593 event.getMetaState(), event.getRepeatCount(),
6594 event.getDownTime());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006595 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6596 ALOGD("Unhandled key event: Dispatching fallback key. "
6597 "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006598 originalKeyCode, *fallbackKeyCode, keyEntry.metaState);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006599 }
Prabir Pradhanb9dd1642023-11-02 18:05:36 +00006600 return newEntry;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006601 } else {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006602 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6603 ALOGD("Unhandled key event: No fallback key.");
6604 }
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006605
6606 // Report the key as unhandled, since there is no fallback key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006607 mReporter->reportUnhandledKey(keyEntry.id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006608 }
6609 }
Prabir Pradhanb9dd1642023-11-02 18:05:36 +00006610 return {};
Michael Wrightd02c5b62014-02-10 15:10:22 -08006611}
6612
Michael Wrightd02c5b62014-02-10 15:10:22 -08006613void InputDispatcher::traceInboundQueueLengthLocked() {
6614 if (ATRACE_ENABLED()) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07006615 ATRACE_INT("iq", mInboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006616 }
6617}
6618
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006619void InputDispatcher::traceOutboundQueueLength(const Connection& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006620 if (ATRACE_ENABLED()) {
6621 char counterName[40];
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006622 snprintf(counterName, sizeof(counterName), "oq:%s", connection.getWindowName().c_str());
6623 ATRACE_INT(counterName, connection.outboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006624 }
6625}
6626
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006627void InputDispatcher::traceWaitQueueLength(const Connection& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006628 if (ATRACE_ENABLED()) {
6629 char counterName[40];
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006630 snprintf(counterName, sizeof(counterName), "wq:%s", connection.getWindowName().c_str());
6631 ATRACE_INT(counterName, connection.waitQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006632 }
6633}
6634
Siarhei Vishniakou5e20f272023-06-08 17:24:44 -07006635void InputDispatcher::dump(std::string& dump) const {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006636 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006637
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006638 dump += "Input Dispatcher State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08006639 dumpDispatchStateLocked(dump);
6640
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006641 if (!mLastAnrState.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006642 dump += "\nInput Dispatcher State at time of last ANR:\n";
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006643 dump += mLastAnrState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006644 }
6645}
6646
6647void InputDispatcher::monitor() {
6648 // Acquire and release the lock to ensure that the dispatcher has not deadlocked.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006649 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006650 mLooper->wake();
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006651 mDispatcherIsAlive.wait(_l);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006652}
6653
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08006654/**
6655 * Wake up the dispatcher and wait until it processes all events and commands.
6656 * The notification of mDispatcherEnteredIdle is guaranteed to happen after wake(), so
6657 * this method can be safely called from any thread, as long as you've ensured that
6658 * the work you are interested in completing has already been queued.
6659 */
Siarhei Vishniakoua66d65e2023-06-16 10:32:51 -07006660bool InputDispatcher::waitForIdle() const {
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08006661 /**
6662 * Timeout should represent the longest possible time that a device might spend processing
6663 * events and commands.
6664 */
6665 constexpr std::chrono::duration TIMEOUT = 100ms;
6666 std::unique_lock lock(mLock);
6667 mLooper->wake();
6668 std::cv_status result = mDispatcherEnteredIdle.wait_for(lock, TIMEOUT);
6669 return result == std::cv_status::no_timeout;
6670}
6671
Vishnu Naire798b472020-07-23 13:52:21 -07006672/**
6673 * Sets focus to the window identified by the token. This must be called
6674 * after updating any input window handles.
6675 *
6676 * Params:
6677 * request.token - input channel token used to identify the window that should gain focus.
6678 * request.focusedToken - the token that the caller expects currently to be focused. If the
6679 * specified token does not match the currently focused window, this request will be dropped.
6680 * If the specified focused token matches the currently focused window, the call will succeed.
6681 * Set this to "null" if this call should succeed no matter what the currently focused token is.
6682 * request.timestamp - SYSTEM_TIME_MONOTONIC timestamp in nanos set by the client (wm)
6683 * when requesting the focus change. This determines which request gets
6684 * precedence if there is a focus change request from another source such as pointer down.
6685 */
Vishnu Nair958da932020-08-21 17:12:37 -07006686void InputDispatcher::setFocusedWindow(const FocusRequest& request) {
6687 { // acquire lock
6688 std::scoped_lock _l(mLock);
Vishnu Nairc519ff72021-01-21 08:23:08 -08006689 std::optional<FocusResolver::FocusChanges> changes =
6690 mFocusResolver.setFocusedWindow(request, getWindowHandlesLocked(request.displayId));
6691 if (changes) {
6692 onFocusChangedLocked(*changes);
Vishnu Nair958da932020-08-21 17:12:37 -07006693 }
6694 } // release lock
6695 // Wake up poll loop since it may need to make new input dispatching choices.
6696 mLooper->wake();
6697}
6698
Vishnu Nairc519ff72021-01-21 08:23:08 -08006699void InputDispatcher::onFocusChangedLocked(const FocusResolver::FocusChanges& changes) {
6700 if (changes.oldFocus) {
6701 std::shared_ptr<InputChannel> focusedInputChannel = getInputChannelLocked(changes.oldFocus);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006702 if (focusedInputChannel) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00006703 CancelationOptions options(CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS,
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006704 "focus left window");
6705 synthesizeCancelationEventsForInputChannelLocked(focusedInputChannel, options);
Harry Cutts33476232023-01-30 19:57:29 +00006706 enqueueFocusEventLocked(changes.oldFocus, /*hasFocus=*/false, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006707 }
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006708 }
Vishnu Nairc519ff72021-01-21 08:23:08 -08006709 if (changes.newFocus) {
Siarhei Vishniakouc033dfb2023-10-03 10:45:16 -07006710 resetNoFocusedWindowTimeoutLocked();
Harry Cutts33476232023-01-30 19:57:29 +00006711 enqueueFocusEventLocked(changes.newFocus, /*hasFocus=*/true, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006712 }
6713
Prabir Pradhan99987712020-11-10 18:43:05 -08006714 // If a window has pointer capture, then it must have focus. We need to ensure that this
6715 // contract is upheld when pointer capture is being disabled due to a loss of window focus.
6716 // If the window loses focus before it loses pointer capture, then the window can be in a state
6717 // where it has pointer capture but not focus, violating the contract. Therefore we must
6718 // dispatch the pointer capture event before the focus event. Since focus events are added to
6719 // the front of the queue (above), we add the pointer capture event to the front of the queue
6720 // after the focus events are added. This ensures the pointer capture event ends up at the
6721 // front.
6722 disablePointerCaptureForcedLocked();
6723
Vishnu Nairc519ff72021-01-21 08:23:08 -08006724 if (mFocusedDisplayId == changes.displayId) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006725 sendFocusChangedCommandLocked(changes.oldFocus, changes.newFocus);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006726 }
6727}
Vishnu Nair958da932020-08-21 17:12:37 -07006728
Prabir Pradhan99987712020-11-10 18:43:05 -08006729void InputDispatcher::disablePointerCaptureForcedLocked() {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006730 if (!mCurrentPointerCaptureRequest.enable && !mWindowTokenWithPointerCapture) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006731 return;
6732 }
6733
6734 ALOGD_IF(DEBUG_FOCUS, "Disabling Pointer Capture because the window lost focus.");
6735
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006736 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006737 setPointerCaptureLocked(false);
6738 }
6739
6740 if (!mWindowTokenWithPointerCapture) {
6741 // No need to send capture changes because no window has capture.
6742 return;
6743 }
6744
6745 if (mPendingEvent != nullptr) {
6746 // Move the pending event to the front of the queue. This will give the chance
6747 // for the pending event to be dropped if it is a captured event.
6748 mInboundQueue.push_front(mPendingEvent);
6749 mPendingEvent = nullptr;
6750 }
6751
6752 auto entry = std::make_unique<PointerCaptureChangedEntry>(mIdGenerator.nextId(), now(),
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006753 mCurrentPointerCaptureRequest);
Prabir Pradhan99987712020-11-10 18:43:05 -08006754 mInboundQueue.push_front(std::move(entry));
6755}
6756
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006757void InputDispatcher::setPointerCaptureLocked(bool enable) {
6758 mCurrentPointerCaptureRequest.enable = enable;
6759 mCurrentPointerCaptureRequest.seq++;
6760 auto command = [this, request = mCurrentPointerCaptureRequest]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006761 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00006762 mPolicy.setPointerCapture(request);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006763 };
6764 postCommandLocked(std::move(command));
Prabir Pradhan99987712020-11-10 18:43:05 -08006765}
6766
Vishnu Nair599f1412021-06-21 10:39:58 -07006767void InputDispatcher::displayRemoved(int32_t displayId) {
6768 { // acquire lock
6769 std::scoped_lock _l(mLock);
6770 // Set an empty list to remove all handles from the specific display.
Harry Cutts101ee9b2023-07-06 18:04:14 +00006771 setInputWindowsLocked(/*windowInfoHandles=*/{}, displayId);
Vishnu Nair599f1412021-06-21 10:39:58 -07006772 setFocusedApplicationLocked(displayId, nullptr);
6773 // Call focus resolver to clean up stale requests. This must be called after input windows
6774 // have been removed for the removed display.
6775 mFocusResolver.displayRemoved(displayId);
Christine Franksb768bb42021-11-29 12:11:31 -08006776 // Reset pointer capture eligibility, regardless of previous state.
6777 std::erase(mIneligibleDisplaysForPointerCapture, displayId);
Antonio Kantek15beb512022-06-13 22:35:41 +00006778 // Remove the associated touch mode state.
6779 mTouchModePerDisplay.erase(displayId);
Siarhei Vishniakou5c02a712023-05-15 15:45:02 -07006780 mVerifiersByDisplay.erase(displayId);
Vishnu Nair599f1412021-06-21 10:39:58 -07006781 } // release lock
6782
6783 // Wake up poll loop since it may need to make new input dispatching choices.
6784 mLooper->wake();
6785}
6786
Patrick Williamsd828f302023-04-28 17:52:08 -05006787void InputDispatcher::onWindowInfosChanged(const gui::WindowInfosUpdate& update) {
Siarhei Vishniakouaeed0da2024-01-09 08:57:13 -08006788 if (auto result = validateWindowInfosUpdate(update); !result.ok()) {
6789 {
6790 // acquire lock
6791 std::scoped_lock _l(mLock);
6792 logDispatchStateLocked();
6793 }
6794 LOG_ALWAYS_FATAL("Incorrect WindowInfosUpdate provided: %s",
6795 result.error().message().c_str());
6796 };
chaviw15fab6f2021-06-07 14:15:52 -05006797 // The listener sends the windows as a flattened array. Separate the windows by display for
6798 // more convenient parsing.
6799 std::unordered_map<int32_t, std::vector<sp<WindowInfoHandle>>> handlesPerDisplay;
Patrick Williamsd828f302023-04-28 17:52:08 -05006800 for (const auto& info : update.windowInfos) {
chaviw15fab6f2021-06-07 14:15:52 -05006801 handlesPerDisplay.emplace(info.displayId, std::vector<sp<WindowInfoHandle>>());
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07006802 handlesPerDisplay[info.displayId].push_back(sp<WindowInfoHandle>::make(info));
chaviw15fab6f2021-06-07 14:15:52 -05006803 }
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006804
6805 { // acquire lock
6806 std::scoped_lock _l(mLock);
Prabir Pradhan814fe082022-07-22 20:22:18 +00006807
6808 // Ensure that we have an entry created for all existing displays so that if a displayId has
6809 // no windows, we can tell that the windows were removed from the display.
6810 for (const auto& [displayId, _] : mWindowHandlesByDisplay) {
6811 handlesPerDisplay[displayId];
6812 }
6813
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006814 mDisplayInfos.clear();
Patrick Williamsd828f302023-04-28 17:52:08 -05006815 for (const auto& displayInfo : update.displayInfos) {
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006816 mDisplayInfos.emplace(displayInfo.displayId, displayInfo);
6817 }
6818
6819 for (const auto& [displayId, handles] : handlesPerDisplay) {
6820 setInputWindowsLocked(handles, displayId);
6821 }
Patrick Williams9464b2c2023-05-23 11:22:04 -05006822
6823 if (update.vsyncId < mWindowInfosVsyncId) {
6824 ALOGE("Received out of order window infos update. Last update vsync id: %" PRId64
6825 ", current update vsync id: %" PRId64,
6826 mWindowInfosVsyncId, update.vsyncId);
6827 }
6828 mWindowInfosVsyncId = update.vsyncId;
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006829 }
6830 // Wake up poll loop since it may need to make new input dispatching choices.
6831 mLooper->wake();
chaviw15fab6f2021-06-07 14:15:52 -05006832}
6833
Vishnu Nair062a8672021-09-03 16:07:44 -07006834bool InputDispatcher::shouldDropInput(
6835 const EventEntry& entry, const sp<android::gui::WindowInfoHandle>& windowHandle) const {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006836 if (windowHandle->getInfo()->inputConfig.test(WindowInfo::InputConfig::DROP_INPUT) ||
6837 (windowHandle->getInfo()->inputConfig.test(
6838 WindowInfo::InputConfig::DROP_INPUT_IF_OBSCURED) &&
Vishnu Nair062a8672021-09-03 16:07:44 -07006839 isWindowObscuredLocked(windowHandle))) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006840 ALOGW("Dropping %s event targeting %s as requested by the input configuration {%s} on "
6841 "display %" PRId32 ".",
Vishnu Nair062a8672021-09-03 16:07:44 -07006842 ftl::enum_string(entry.type).c_str(), windowHandle->getName().c_str(),
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006843 windowHandle->getInfo()->inputConfig.string().c_str(),
Vishnu Nair062a8672021-09-03 16:07:44 -07006844 windowHandle->getInfo()->displayId);
6845 return true;
6846 }
6847 return false;
6848}
6849
Siarhei Vishniakou18050092021-09-01 13:32:49 -07006850void InputDispatcher::DispatcherWindowListener::onWindowInfosChanged(
Patrick Williamsd828f302023-04-28 17:52:08 -05006851 const gui::WindowInfosUpdate& update) {
6852 mDispatcher.onWindowInfosChanged(update);
Siarhei Vishniakou18050092021-09-01 13:32:49 -07006853}
6854
Arthur Hungdfd528e2021-12-08 13:23:04 +00006855void InputDispatcher::cancelCurrentTouch() {
6856 {
6857 std::scoped_lock _l(mLock);
6858 ALOGD("Canceling all ongoing pointer gestures on all displays.");
Michael Wrightfb04fd52022-11-24 22:31:11 +00006859 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
Arthur Hungdfd528e2021-12-08 13:23:04 +00006860 "cancel current touch");
6861 synthesizeCancelationEventsForAllConnectionsLocked(options);
6862
6863 mTouchStatesByDisplay.clear();
Arthur Hungdfd528e2021-12-08 13:23:04 +00006864 }
6865 // Wake up poll loop since there might be work to do.
6866 mLooper->wake();
6867}
6868
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006869void InputDispatcher::setMonitorDispatchingTimeoutForTest(std::chrono::nanoseconds timeout) {
6870 std::scoped_lock _l(mLock);
6871 mMonitorDispatchingTimeout = timeout;
6872}
6873
Arthur Hungc539dbb2022-12-08 07:45:36 +00006874void InputDispatcher::slipWallpaperTouch(ftl::Flags<InputTarget::Flags> targetFlags,
6875 const sp<WindowInfoHandle>& oldWindowHandle,
6876 const sp<WindowInfoHandle>& newWindowHandle,
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08006877 TouchState& state, int32_t deviceId,
6878 const PointerProperties& pointerProperties,
Siarhei Vishniakoubf880522023-05-01 11:03:22 -07006879 std::vector<InputTarget>& targets) const {
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08006880 std::vector<PointerProperties> pointers{pointerProperties};
Arthur Hungc539dbb2022-12-08 07:45:36 +00006881 const bool oldHasWallpaper = oldWindowHandle->getInfo()->inputConfig.test(
6882 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
6883 const bool newHasWallpaper = targetFlags.test(InputTarget::Flags::FOREGROUND) &&
6884 newWindowHandle->getInfo()->inputConfig.test(
6885 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
6886 const sp<WindowInfoHandle> oldWallpaper =
6887 oldHasWallpaper ? state.getWallpaperWindow() : nullptr;
6888 const sp<WindowInfoHandle> newWallpaper =
6889 newHasWallpaper ? findWallpaperWindowBelow(newWindowHandle) : nullptr;
6890 if (oldWallpaper == newWallpaper) {
6891 return;
6892 }
6893
6894 if (oldWallpaper != nullptr) {
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08006895 const TouchedWindow& oldTouchedWindow = state.getTouchedWindow(oldWallpaper);
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00006896 addPointerWindowTargetLocked(oldWallpaper, InputTarget::DispatchMode::SLIPPERY_EXIT,
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08006897 oldTouchedWindow.targetFlags, getPointerIds(pointers),
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00006898 oldTouchedWindow.getDownTimeInTarget(deviceId), targets);
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08006899 state.removeTouchingPointerFromWindow(deviceId, pointerProperties.id, oldWallpaper);
Arthur Hungc539dbb2022-12-08 07:45:36 +00006900 }
6901
6902 if (newWallpaper != nullptr) {
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00006903 state.addOrUpdateWindow(newWallpaper, InputTarget::DispatchMode::SLIPPERY_ENTER,
6904 InputTarget::Flags::WINDOW_IS_OBSCURED |
Arthur Hungc539dbb2022-12-08 07:45:36 +00006905 InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED,
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08006906 deviceId, pointers);
Arthur Hungc539dbb2022-12-08 07:45:36 +00006907 }
6908}
6909
6910void InputDispatcher::transferWallpaperTouch(ftl::Flags<InputTarget::Flags> oldTargetFlags,
6911 ftl::Flags<InputTarget::Flags> newTargetFlags,
6912 const sp<WindowInfoHandle> fromWindowHandle,
6913 const sp<WindowInfoHandle> toWindowHandle,
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07006914 TouchState& state, int32_t deviceId,
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08006915 const std::vector<PointerProperties>& pointers) {
Arthur Hungc539dbb2022-12-08 07:45:36 +00006916 const bool oldHasWallpaper = oldTargetFlags.test(InputTarget::Flags::FOREGROUND) &&
6917 fromWindowHandle->getInfo()->inputConfig.test(
6918 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
6919 const bool newHasWallpaper = newTargetFlags.test(InputTarget::Flags::FOREGROUND) &&
6920 toWindowHandle->getInfo()->inputConfig.test(
6921 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
6922
6923 const sp<WindowInfoHandle> oldWallpaper =
6924 oldHasWallpaper ? state.getWallpaperWindow() : nullptr;
6925 const sp<WindowInfoHandle> newWallpaper =
6926 newHasWallpaper ? findWallpaperWindowBelow(toWindowHandle) : nullptr;
6927 if (oldWallpaper == newWallpaper) {
6928 return;
6929 }
6930
6931 if (oldWallpaper != nullptr) {
6932 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
6933 "transferring touch focus to another window");
6934 state.removeWindowByToken(oldWallpaper->getToken());
6935 synthesizeCancelationEventsForWindowLocked(oldWallpaper, options);
6936 }
6937
6938 if (newWallpaper != nullptr) {
6939 nsecs_t downTimeInTarget = now();
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00006940 ftl::Flags<InputTarget::Flags> wallpaperFlags = oldTargetFlags & InputTarget::Flags::SPLIT;
Arthur Hungc539dbb2022-12-08 07:45:36 +00006941 wallpaperFlags |= InputTarget::Flags::WINDOW_IS_OBSCURED |
6942 InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED;
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00006943 state.addOrUpdateWindow(newWallpaper, InputTarget::DispatchMode::AS_IS, wallpaperFlags,
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08006944 deviceId, pointers, downTimeInTarget);
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006945 std::shared_ptr<Connection> wallpaperConnection =
6946 getConnectionLocked(newWallpaper->getToken());
Arthur Hungc539dbb2022-12-08 07:45:36 +00006947 if (wallpaperConnection != nullptr) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006948 std::shared_ptr<Connection> toConnection =
6949 getConnectionLocked(toWindowHandle->getToken());
Arthur Hungc539dbb2022-12-08 07:45:36 +00006950 toConnection->inputState.mergePointerStateTo(wallpaperConnection->inputState);
6951 synthesizePointerDownEventsForConnectionLocked(downTimeInTarget, wallpaperConnection,
6952 wallpaperFlags);
6953 }
6954 }
6955}
6956
6957sp<WindowInfoHandle> InputDispatcher::findWallpaperWindowBelow(
6958 const sp<WindowInfoHandle>& windowHandle) const {
6959 const std::vector<sp<WindowInfoHandle>>& windowHandles =
6960 getWindowHandlesLocked(windowHandle->getInfo()->displayId);
6961 bool foundWindow = false;
6962 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
6963 if (!foundWindow && otherHandle != windowHandle) {
6964 continue;
6965 }
6966 if (windowHandle == otherHandle) {
6967 foundWindow = true;
6968 continue;
6969 }
6970
6971 if (otherHandle->getInfo()->inputConfig.test(WindowInfo::InputConfig::IS_WALLPAPER)) {
6972 return otherHandle;
6973 }
6974 }
6975 return nullptr;
6976}
6977
Siarhei Vishniakoufa2a0492023-11-14 13:13:18 -08006978void InputDispatcher::setKeyRepeatConfiguration(std::chrono::nanoseconds timeout,
6979 std::chrono::nanoseconds delay) {
Nergi Rahardi730cf3c2023-04-13 12:41:17 +09006980 std::scoped_lock _l(mLock);
6981
Siarhei Vishniakoufa2a0492023-11-14 13:13:18 -08006982 mConfig.keyRepeatTimeout = timeout.count();
6983 mConfig.keyRepeatDelay = delay.count();
Nergi Rahardi730cf3c2023-04-13 12:41:17 +09006984}
6985
Prabir Pradhan64f21d22023-11-28 21:19:42 +00006986bool InputDispatcher::isPointerInWindow(const sp<android::IBinder>& token, int32_t displayId,
6987 DeviceId deviceId, int32_t pointerId) {
6988 std::scoped_lock _l(mLock);
6989 auto touchStateIt = mTouchStatesByDisplay.find(displayId);
6990 if (touchStateIt == mTouchStatesByDisplay.end()) {
6991 return false;
6992 }
6993 for (const TouchedWindow& window : touchStateIt->second.windows) {
6994 if (window.windowHandle->getToken() == token &&
6995 (window.hasTouchingPointer(deviceId, pointerId) ||
6996 window.hasHoveringPointer(deviceId, pointerId))) {
6997 return true;
6998 }
6999 }
7000 return false;
7001}
7002
Garfield Tane84e6f92019-08-29 17:28:41 -07007003} // namespace android::inputdispatcher