blob: 619ecdc7736f55ed3cc3d74a565f0e313f489f8e [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>
Dominik Laskowski75788452021-02-09 18:51:25 -080028#include <ftl/enum.h>
Siarhei Vishniakou5c02a712023-05-15 15:45:02 -070029#include <log/log_event_list.h>
Siarhei Vishniakou31977182022-09-30 08:51:23 -070030#if defined(__ANDROID__)
chaviw15fab6f2021-06-07 14:15:52 -050031#include <gui/SurfaceComposerClient.h>
Siarhei Vishniakou31977182022-09-30 08:51:23 -070032#endif
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -080033#include <input/InputDevice.h>
Siarhei Vishniakou6e1e9872022-11-08 17:51:35 -080034#include <input/PrintTools.h>
tyiu1573a672023-02-21 22:38:32 +000035#include <openssl/mem.h>
Garfield Tan0fc2fa72019-08-29 17:22:15 -070036#include <powermanager/PowerManager.h>
Michael Wright44753b12020-07-08 13:48:11 +010037#include <unistd.h>
Garfield Tan0fc2fa72019-08-29 17:22:15 -070038#include <utils/Trace.h>
Michael Wrightd02c5b62014-02-10 15:10:22 -080039
Michael Wright44753b12020-07-08 13:48:11 +010040#include <cerrno>
41#include <cinttypes>
42#include <climits>
43#include <cstddef>
44#include <ctime>
45#include <queue>
46#include <sstream>
47
48#include "Connection.h"
Arthur Hung1a1007b2022-05-11 07:15:01 +000049#include "DebugConfig.h"
Chris Yef59a2f42020-10-16 12:55:26 -070050#include "InputDispatcher.h"
Michael Wright44753b12020-07-08 13:48:11 +010051
Michael Wrightd02c5b62014-02-10 15:10:22 -080052#define INDENT " "
53#define INDENT2 " "
54#define INDENT3 " "
55#define INDENT4 " "
56
Siarhei Vishniakou253f4642022-11-09 13:42:06 -080057using namespace android::ftl::flag_operators;
Siarhei Vishniakou23740b92023-04-21 11:30:20 -070058using android::base::Error;
Peter Collingbourneb04b9b82021-02-08 12:09:47 -080059using android::base::HwTimeoutMultiplier;
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +000060using android::base::Result;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080061using android::base::StringPrintf;
Prabir Pradhan48f8cb92021-08-26 14:05:36 -070062using android::gui::DisplayInfo;
chaviw98318de2021-05-19 16:45:23 -050063using android::gui::FocusRequest;
64using android::gui::TouchOcclusionMode;
65using android::gui::WindowInfo;
66using android::gui::WindowInfoHandle;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -080067using android::os::InputEventInjectionResult;
68using android::os::InputEventInjectionSync;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080069
Garfield Tane84e6f92019-08-29 17:28:41 -070070namespace android::inputdispatcher {
Michael Wrightd02c5b62014-02-10 15:10:22 -080071
Prabir Pradhancef936d2021-07-21 16:17:52 +000072namespace {
Prabir Pradhancef936d2021-07-21 16:17:52 +000073// Temporarily releases a held mutex for the lifetime of the instance.
74// Named to match std::scoped_lock
75class scoped_unlock {
76public:
77 explicit scoped_unlock(std::mutex& mutex) : mMutex(mutex) { mMutex.unlock(); }
78 ~scoped_unlock() { mMutex.lock(); }
79
80private:
81 std::mutex& mMutex;
82};
83
Michael Wrightd02c5b62014-02-10 15:10:22 -080084// Default input dispatching timeout if there is no focused application or paused window
85// from which to determine an appropriate dispatching timeout.
Peter Collingbourneb04b9b82021-02-08 12:09:47 -080086const std::chrono::duration DEFAULT_INPUT_DISPATCHING_TIMEOUT = std::chrono::milliseconds(
87 android::os::IInputConstants::UNMULTIPLIED_DEFAULT_DISPATCHING_TIMEOUT_MILLIS *
88 HwTimeoutMultiplier());
Michael Wrightd02c5b62014-02-10 15:10:22 -080089
90// Amount of time to allow for all pending events to be processed when an app switch
91// key is on the way. This is used to preempt input dispatch and drop input events
92// when an application takes too long to respond and the user has pressed an app switch key.
Michael Wright2b3c3302018-03-02 17:19:13 +000093constexpr nsecs_t APP_SWITCH_TIMEOUT = 500 * 1000000LL; // 0.5sec
Michael Wrightd02c5b62014-02-10 15:10:22 -080094
Siarhei Vishniakou289e9242022-02-15 14:50:16 -080095const std::chrono::duration STALE_EVENT_TIMEOUT = std::chrono::seconds(10) * HwTimeoutMultiplier();
Michael Wrightd02c5b62014-02-10 15:10:22 -080096
Michael Wrightd02c5b62014-02-10 15:10:22 -080097// 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 +000098constexpr nsecs_t SLOW_EVENT_PROCESSING_WARNING_TIMEOUT = 2000 * 1000000LL; // 2sec
99
100// Log a warning when an interception call takes longer than this to process.
101constexpr std::chrono::milliseconds SLOW_INTERCEPTION_THRESHOLD = 50ms;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800102
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700103// Additional key latency in case a connection is still processing some motion events.
104// This will help with the case when a user touched a button that opens a new window,
105// and gives us the chance to dispatch the key to this new window.
106constexpr std::chrono::nanoseconds KEY_WAITING_FOR_EVENTS_TIMEOUT = 500ms;
107
Michael Wrightd02c5b62014-02-10 15:10:22 -0800108// Number of recent events to keep for debugging purposes.
Michael Wright2b3c3302018-03-02 17:19:13 +0000109constexpr size_t RECENT_QUEUE_MAX_SIZE = 10;
110
Antonio Kantekea47acb2021-12-23 12:41:25 -0800111// Event log tags. See EventLogTags.logtags for reference.
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +0000112constexpr int LOGTAG_INPUT_INTERACTION = 62000;
113constexpr int LOGTAG_INPUT_FOCUS = 62001;
Arthur Hungb3307ee2021-10-14 10:57:37 +0000114constexpr int LOGTAG_INPUT_CANCEL = 62003;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +0000115
Prabir Pradhan33e3baa2022-12-06 20:30:22 +0000116const ui::Transform kIdentityTransform;
117
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000118inline nsecs_t now() {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800119 return systemTime(SYSTEM_TIME_MONOTONIC);
120}
121
Siarhei Vishniakoud38a1e02023-07-18 11:55:17 -0700122bool isEmpty(const std::stringstream& ss) {
123 return ss.rdbuf()->in_avail() == 0;
124}
125
Siarhei Vishniakou63b63612023-04-12 11:00:23 -0700126inline const std::string binderToString(const sp<IBinder>& binder) {
Bernardo Rufino49d99e42021-01-18 15:16:59 +0000127 if (binder == nullptr) {
128 return "<null>";
129 }
130 return StringPrintf("%p", binder.get());
131}
132
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +0000133static std::string uidString(const gui::Uid& uid) {
134 return uid.toString();
135}
136
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700137Result<void> checkKeyAction(int32_t action) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800138 switch (action) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700139 case AKEY_EVENT_ACTION_DOWN:
140 case AKEY_EVENT_ACTION_UP:
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700141 return {};
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700142 default:
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700143 return Error() << "Key event has invalid action code " << action;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800144 }
145}
146
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700147Result<void> validateKeyEvent(int32_t action) {
148 return checkKeyAction(action);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800149}
150
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700151Result<void> checkMotionAction(int32_t action, int32_t actionButton, int32_t pointerCount) {
Siarhei Vishniakou2f61bdc2022-12-02 08:55:51 -0800152 switch (MotionEvent::getActionMasked(action)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700153 case AMOTION_EVENT_ACTION_DOWN:
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700154 case AMOTION_EVENT_ACTION_UP: {
155 if (pointerCount != 1) {
156 return Error() << "invalid pointer count " << pointerCount;
157 }
158 return {};
159 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700160 case AMOTION_EVENT_ACTION_MOVE:
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700161 case AMOTION_EVENT_ACTION_HOVER_ENTER:
162 case AMOTION_EVENT_ACTION_HOVER_MOVE:
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700163 case AMOTION_EVENT_ACTION_HOVER_EXIT: {
164 if (pointerCount < 1) {
165 return Error() << "invalid pointer count " << pointerCount;
166 }
167 return {};
168 }
Siarhei Vishniakou2f61bdc2022-12-02 08:55:51 -0800169 case AMOTION_EVENT_ACTION_CANCEL:
170 case AMOTION_EVENT_ACTION_OUTSIDE:
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700171 case AMOTION_EVENT_ACTION_SCROLL:
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700172 return {};
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700173 case AMOTION_EVENT_ACTION_POINTER_DOWN:
174 case AMOTION_EVENT_ACTION_POINTER_UP: {
Siarhei Vishniakou2f61bdc2022-12-02 08:55:51 -0800175 const int32_t index = MotionEvent::getActionIndex(action);
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700176 if (index < 0) {
177 return Error() << "invalid index " << index << " for "
178 << MotionEvent::actionToString(action);
179 }
180 if (index >= pointerCount) {
181 return Error() << "invalid index " << index << " for pointerCount " << pointerCount;
182 }
183 if (pointerCount <= 1) {
184 return Error() << "invalid pointer count " << pointerCount << " for "
185 << MotionEvent::actionToString(action);
186 }
187 return {};
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700188 }
189 case AMOTION_EVENT_ACTION_BUTTON_PRESS:
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700190 case AMOTION_EVENT_ACTION_BUTTON_RELEASE: {
191 if (actionButton == 0) {
192 return Error() << "action button should be nonzero for "
193 << MotionEvent::actionToString(action);
194 }
195 return {};
196 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700197 default:
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700198 return Error() << "invalid action " << action;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800199 }
200}
201
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000202int64_t millis(std::chrono::nanoseconds t) {
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -0500203 return std::chrono::duration_cast<std::chrono::milliseconds>(t).count();
204}
205
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700206Result<void> validateMotionEvent(int32_t action, int32_t actionButton, size_t pointerCount,
207 const PointerProperties* pointerProperties) {
208 Result<void> actionCheck = checkMotionAction(action, actionButton, pointerCount);
209 if (!actionCheck.ok()) {
210 return actionCheck;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800211 }
212 if (pointerCount < 1 || pointerCount > MAX_POINTERS) {
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700213 return Error() << "Motion event has invalid pointer count " << pointerCount
214 << "; value must be between 1 and " << MAX_POINTERS << ".";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800215 }
Siarhei Vishniakou8a878352023-01-30 14:05:01 -0800216 std::bitset<MAX_POINTER_ID + 1> pointerIdBits;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800217 for (size_t i = 0; i < pointerCount; i++) {
218 int32_t id = pointerProperties[i].id;
219 if (id < 0 || id > MAX_POINTER_ID) {
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700220 return Error() << "Motion event has invalid pointer id " << id
221 << "; value must be between 0 and " << MAX_POINTER_ID;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800222 }
Siarhei Vishniakou8a878352023-01-30 14:05:01 -0800223 if (pointerIdBits.test(id)) {
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700224 return Error() << "Motion event has duplicate pointer id " << id;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800225 }
Siarhei Vishniakou8a878352023-01-30 14:05:01 -0800226 pointerIdBits.set(id);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800227 }
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700228 return {};
229}
230
231Result<void> validateInputEvent(const InputEvent& event) {
232 switch (event.getType()) {
233 case InputEventType::KEY: {
234 const KeyEvent& key = static_cast<const KeyEvent&>(event);
235 const int32_t action = key.getAction();
236 return validateKeyEvent(action);
237 }
238 case InputEventType::MOTION: {
239 const MotionEvent& motion = static_cast<const MotionEvent&>(event);
240 const int32_t action = motion.getAction();
241 const size_t pointerCount = motion.getPointerCount();
242 const PointerProperties* pointerProperties = motion.getPointerProperties();
243 const int32_t actionButton = motion.getActionButton();
244 return validateMotionEvent(action, actionButton, pointerCount, pointerProperties);
245 }
246 default: {
247 return {};
248 }
249 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800250}
251
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000252std::string dumpRegion(const Region& region) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800253 if (region.isEmpty()) {
Bernardo Rufino53fc31e2020-11-03 11:01:07 +0000254 return "<empty>";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800255 }
256
Bernardo Rufino53fc31e2020-11-03 11:01:07 +0000257 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800258 bool first = true;
259 Region::const_iterator cur = region.begin();
260 Region::const_iterator const tail = region.end();
261 while (cur != tail) {
262 if (first) {
263 first = false;
264 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800265 dump += "|";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800266 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800267 dump += StringPrintf("[%d,%d][%d,%d]", cur->left, cur->top, cur->right, cur->bottom);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800268 cur++;
269 }
Bernardo Rufino53fc31e2020-11-03 11:01:07 +0000270 return dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800271}
272
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000273std::string dumpQueue(const std::deque<DispatchEntry*>& queue, nsecs_t currentTime) {
Siarhei Vishniakou14411c92020-09-18 21:15:05 -0500274 constexpr size_t maxEntries = 50; // max events to print
275 constexpr size_t skipBegin = maxEntries / 2;
276 const size_t skipEnd = queue.size() - maxEntries / 2;
277 // skip from maxEntries / 2 ... size() - maxEntries/2
278 // only print from 0 .. skipBegin and then from skipEnd .. size()
279
280 std::string dump;
281 for (size_t i = 0; i < queue.size(); i++) {
282 const DispatchEntry& entry = *queue[i];
283 if (i >= skipBegin && i < skipEnd) {
284 dump += StringPrintf(INDENT4 "<skipped %zu entries>\n", skipEnd - skipBegin);
285 i = skipEnd - 1; // it will be incremented to "skipEnd" by 'continue'
286 continue;
287 }
288 dump.append(INDENT4);
289 dump += entry.eventEntry->getDescription();
Siarhei Vishniakou253f4642022-11-09 13:42:06 -0800290 dump += StringPrintf(", seq=%" PRIu32 ", targetFlags=%s, resolvedAction=%d, age=%" PRId64
291 "ms",
292 entry.seq, entry.targetFlags.string().c_str(), entry.resolvedAction,
Siarhei Vishniakou14411c92020-09-18 21:15:05 -0500293 ns2ms(currentTime - entry.eventEntry->eventTime));
294 if (entry.deliveryTime != 0) {
295 // This entry was delivered, so add information on how long we've been waiting
296 dump += StringPrintf(", wait=%" PRId64 "ms", ns2ms(currentTime - entry.deliveryTime));
297 }
298 dump.append("\n");
299 }
300 return dump;
301}
302
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -0700303/**
304 * Find the entry in std::unordered_map by key, and return it.
305 * If the entry is not found, return a default constructed entry.
306 *
307 * Useful when the entries are vectors, since an empty vector will be returned
308 * if the entry is not found.
309 * Also useful when the entries are sp<>. If an entry is not found, nullptr is returned.
310 */
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700311template <typename K, typename V>
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000312V getValueByKey(const std::unordered_map<K, V>& map, K key) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -0700313 auto it = map.find(key);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700314 return it != map.end() ? it->second : V{};
Tiger Huang721e26f2018-07-24 22:26:19 +0800315}
316
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000317bool haveSameToken(const sp<WindowInfoHandle>& first, const sp<WindowInfoHandle>& second) {
chaviwaf87b3e2019-10-01 16:59:28 -0700318 if (first == second) {
319 return true;
320 }
321
322 if (first == nullptr || second == nullptr) {
323 return false;
324 }
325
326 return first->getToken() == second->getToken();
327}
328
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000329bool haveSameApplicationToken(const WindowInfo* first, const WindowInfo* second) {
Bernardo Rufino1ff9d592021-01-18 16:58:57 +0000330 if (first == nullptr || second == nullptr) {
331 return false;
332 }
333 return first->applicationInfo.token != nullptr &&
334 first->applicationInfo.token == second->applicationInfo.token;
335}
336
Siarhei Vishniakou8a878352023-01-30 14:05:01 -0800337template <typename T>
338size_t firstMarkedBit(T set) {
339 // TODO: replace with std::countr_zero from <bit> when that's available
340 LOG_ALWAYS_FATAL_IF(set.none());
341 size_t i = 0;
342 while (!set.test(i)) {
343 i++;
344 }
345 return i;
346}
347
Siarhei Vishniakou253f4642022-11-09 13:42:06 -0800348std::unique_ptr<DispatchEntry> createDispatchEntry(
349 const InputTarget& inputTarget, std::shared_ptr<EventEntry> eventEntry,
350 ftl::Flags<InputTarget::Flags> inputTargetFlags) {
chaviw1ff3d1e2020-07-01 15:53:47 -0700351 if (inputTarget.useDefaultPointerTransform()) {
352 const ui::Transform& transform = inputTarget.getDefaultPointerTransform();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700353 return std::make_unique<DispatchEntry>(eventEntry, inputTargetFlags, transform,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700354 inputTarget.displayTransform,
355 inputTarget.globalScaleFactor);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000356 }
357
358 ALOG_ASSERT(eventEntry->type == EventEntry::Type::MOTION);
359 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(*eventEntry);
360
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700361 std::vector<PointerCoords> pointerCoords;
362 pointerCoords.resize(motionEntry.pointerCount);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000363
364 // Use the first pointer information to normalize all other pointers. This could be any pointer
365 // as long as all other pointers are normalized to the same value and the final DispatchEntry
chaviw1ff3d1e2020-07-01 15:53:47 -0700366 // uses the transform for the normalized pointer.
367 const ui::Transform& firstPointerTransform =
Siarhei Vishniakou8a878352023-01-30 14:05:01 -0800368 inputTarget.pointerTransforms[firstMarkedBit(inputTarget.pointerIds)];
chaviw1ff3d1e2020-07-01 15:53:47 -0700369 ui::Transform inverseFirstTransform = firstPointerTransform.inverse();
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000370
371 // Iterate through all pointers in the event to normalize against the first.
372 for (uint32_t pointerIndex = 0; pointerIndex < motionEntry.pointerCount; pointerIndex++) {
373 const PointerProperties& pointerProperties = motionEntry.pointerProperties[pointerIndex];
374 uint32_t pointerId = uint32_t(pointerProperties.id);
chaviw1ff3d1e2020-07-01 15:53:47 -0700375 const ui::Transform& currTransform = inputTarget.pointerTransforms[pointerId];
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000376
377 pointerCoords[pointerIndex].copyFrom(motionEntry.pointerCoords[pointerIndex]);
chaviw1ff3d1e2020-07-01 15:53:47 -0700378 // First, apply the current pointer's transform to update the coordinates into
379 // window space.
380 pointerCoords[pointerIndex].transform(currTransform);
381 // Next, apply the inverse transform of the normalized coordinates so the
382 // current coordinates are transformed into the normalized coordinate space.
383 pointerCoords[pointerIndex].transform(inverseFirstTransform);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000384 }
385
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700386 std::unique_ptr<MotionEntry> combinedMotionEntry =
387 std::make_unique<MotionEntry>(motionEntry.id, motionEntry.eventTime,
388 motionEntry.deviceId, motionEntry.source,
389 motionEntry.displayId, motionEntry.policyFlags,
390 motionEntry.action, motionEntry.actionButton,
391 motionEntry.flags, motionEntry.metaState,
392 motionEntry.buttonState, motionEntry.classification,
393 motionEntry.edgeFlags, motionEntry.xPrecision,
394 motionEntry.yPrecision, motionEntry.xCursorPosition,
395 motionEntry.yCursorPosition, motionEntry.downTime,
396 motionEntry.pointerCount, motionEntry.pointerProperties,
Prabir Pradhan5beda762021-12-10 09:30:08 +0000397 pointerCoords.data());
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000398
399 if (motionEntry.injectionState) {
400 combinedMotionEntry->injectionState = motionEntry.injectionState;
401 combinedMotionEntry->injectionState->refCount += 1;
402 }
403
404 std::unique_ptr<DispatchEntry> dispatchEntry =
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700405 std::make_unique<DispatchEntry>(std::move(combinedMotionEntry), inputTargetFlags,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700406 firstPointerTransform, inputTarget.displayTransform,
407 inputTarget.globalScaleFactor);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000408 return dispatchEntry;
409}
410
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000411status_t openInputChannelPair(const std::string& name, std::shared_ptr<InputChannel>& serverChannel,
412 std::unique_ptr<InputChannel>& clientChannel) {
Garfield Tan15601662020-09-22 15:32:38 -0700413 std::unique_ptr<InputChannel> uniqueServerChannel;
414 status_t result = InputChannel::openInputChannelPair(name, uniqueServerChannel, clientChannel);
415
416 serverChannel = std::move(uniqueServerChannel);
417 return result;
418}
419
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -0500420template <typename T>
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000421bool sharedPointersEqual(const std::shared_ptr<T>& lhs, const std::shared_ptr<T>& rhs) {
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -0500422 if (lhs == nullptr && rhs == nullptr) {
423 return true;
424 }
425 if (lhs == nullptr || rhs == nullptr) {
426 return false;
427 }
428 return *lhs == *rhs;
429}
430
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000431KeyEvent createKeyEvent(const KeyEntry& entry) {
Siarhei Vishniakou2e2ea992020-12-15 02:57:19 +0000432 KeyEvent event;
433 event.initialize(entry.id, entry.deviceId, entry.source, entry.displayId, INVALID_HMAC,
434 entry.action, entry.flags, entry.keyCode, entry.scanCode, entry.metaState,
435 entry.repeatCount, entry.downTime, entry.eventTime);
436 return event;
437}
438
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000439bool shouldReportMetricsForConnection(const Connection& connection) {
Siarhei Vishniakouf2652122021-03-05 21:39:46 +0000440 // Do not keep track of gesture monitors. They receive every event and would disproportionately
441 // affect the statistics.
442 if (connection.monitor) {
443 return false;
444 }
445 // If the connection is experiencing ANR, let's skip it. We have separate ANR metrics
446 if (!connection.responsive) {
447 return false;
448 }
449 return true;
450}
451
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000452bool shouldReportFinishedEvent(const DispatchEntry& dispatchEntry, const Connection& connection) {
Siarhei Vishniakouf2652122021-03-05 21:39:46 +0000453 const EventEntry& eventEntry = *dispatchEntry.eventEntry;
454 const int32_t& inputEventId = eventEntry.id;
455 if (inputEventId != dispatchEntry.resolvedEventId) {
456 // Event was transmuted
457 return false;
458 }
459 if (inputEventId == android::os::IInputConstants::INVALID_INPUT_EVENT_ID) {
460 return false;
461 }
462 // Only track latency for events that originated from hardware
463 if (eventEntry.isSynthesized()) {
464 return false;
465 }
466 const EventEntry::Type& inputEventEntryType = eventEntry.type;
467 if (inputEventEntryType == EventEntry::Type::KEY) {
468 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
469 if (keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) {
470 return false;
471 }
472 } else if (inputEventEntryType == EventEntry::Type::MOTION) {
473 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
474 if (motionEntry.action == AMOTION_EVENT_ACTION_CANCEL ||
475 motionEntry.action == AMOTION_EVENT_ACTION_HOVER_EXIT) {
476 return false;
477 }
478 } else {
479 // Not a key or a motion
480 return false;
481 }
482 if (!shouldReportMetricsForConnection(connection)) {
483 return false;
484 }
485 return true;
486}
487
Prabir Pradhancef936d2021-07-21 16:17:52 +0000488/**
489 * Connection is responsive if it has no events in the waitQueue that are older than the
490 * current time.
491 */
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000492bool isConnectionResponsive(const Connection& connection) {
Prabir Pradhancef936d2021-07-21 16:17:52 +0000493 const nsecs_t currentTime = now();
494 for (const DispatchEntry* entry : connection.waitQueue) {
495 if (entry->timeoutTime < currentTime) {
496 return false;
497 }
498 }
499 return true;
500}
501
Antonio Kantekf16f2832021-09-28 04:39:20 +0000502// Returns true if the event type passed as argument represents a user activity.
503bool isUserActivityEvent(const EventEntry& eventEntry) {
504 switch (eventEntry.type) {
Josep del Riob3981622023-04-18 15:49:45 +0000505 case EventEntry::Type::CONFIGURATION_CHANGED:
506 case EventEntry::Type::DEVICE_RESET:
507 case EventEntry::Type::DRAG:
Antonio Kantekf16f2832021-09-28 04:39:20 +0000508 case EventEntry::Type::FOCUS:
509 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
Antonio Kantekf16f2832021-09-28 04:39:20 +0000510 case EventEntry::Type::SENSOR:
Josep del Riob3981622023-04-18 15:49:45 +0000511 case EventEntry::Type::TOUCH_MODE_CHANGED:
Antonio Kantekf16f2832021-09-28 04:39:20 +0000512 return false;
Antonio Kantekf16f2832021-09-28 04:39:20 +0000513 case EventEntry::Type::KEY:
514 case EventEntry::Type::MOTION:
515 return true;
516 }
517}
518
Prabir Pradhan3f90d312021-11-19 03:57:24 -0800519// Returns true if the given window can accept pointer events at the given display location.
Prabir Pradhan82e081e2022-12-06 09:50:09 +0000520bool windowAcceptsTouchAt(const WindowInfo& windowInfo, int32_t displayId, float x, float y,
Prabir Pradhan33e3baa2022-12-06 20:30:22 +0000521 bool isStylus, const ui::Transform& displayTransform) {
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -0800522 const auto inputConfig = windowInfo.inputConfig;
523 if (windowInfo.displayId != displayId ||
524 inputConfig.test(WindowInfo::InputConfig::NOT_VISIBLE)) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -0800525 return false;
526 }
Prabir Pradhand65552b2021-10-07 11:23:50 -0700527 const bool windowCanInterceptTouch = isStylus && windowInfo.interceptsStylus();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -0800528 if (inputConfig.test(WindowInfo::InputConfig::NOT_TOUCHABLE) && !windowCanInterceptTouch) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -0800529 return false;
530 }
Prabir Pradhan33e3baa2022-12-06 20:30:22 +0000531
532 // Window Manager works in the logical display coordinate space. When it specifies bounds for a
533 // window as (l, t, r, b), the range of x in [l, r) and y in [t, b) are considered to be inside
534 // the window. Points on the right and bottom edges should not be inside the window, so we need
535 // to be careful about performing a hit test when the display is rotated, since the "right" and
536 // "bottom" of the window will be different in the display (un-rotated) space compared to in the
537 // logical display in which WM determined the bounds. Perform the hit test in the logical
538 // display space to ensure these edges are considered correctly in all orientations.
539 const auto touchableRegion = displayTransform.transform(windowInfo.touchableRegion);
540 const auto p = displayTransform.transform(x, y);
541 if (!touchableRegion.contains(std::floor(p.x), std::floor(p.y))) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -0800542 return false;
543 }
544 return true;
545}
546
Prabir Pradhand65552b2021-10-07 11:23:50 -0700547bool isPointerFromStylus(const MotionEntry& entry, int32_t pointerIndex) {
548 return isFromSource(entry.source, AINPUT_SOURCE_STYLUS) &&
Prabir Pradhane5626962022-10-27 20:30:53 +0000549 isStylusToolType(entry.pointerProperties[pointerIndex].toolType);
Prabir Pradhand65552b2021-10-07 11:23:50 -0700550}
551
Siarhei Vishniakou253f4642022-11-09 13:42:06 -0800552// Determines if the given window can be targeted as InputTarget::Flags::FOREGROUND.
Prabir Pradhan6dfbf262022-03-14 15:24:30 +0000553// Foreground events are only sent to "foreground targetable" windows, but not all gestures sent to
554// such window are necessarily targeted with the flag. For example, an event with ACTION_OUTSIDE can
555// be sent to such a window, but it is not a foreground event and doesn't use
Siarhei Vishniakou253f4642022-11-09 13:42:06 -0800556// InputTarget::Flags::FOREGROUND.
Prabir Pradhan6dfbf262022-03-14 15:24:30 +0000557bool canReceiveForegroundTouches(const WindowInfo& info) {
558 // A non-touchable window can still receive touch events (e.g. in the case of
559 // STYLUS_INTERCEPTOR), so prevent such windows from receiving foreground events for touches.
560 return !info.inputConfig.test(gui::WindowInfo::InputConfig::NOT_TOUCHABLE) && !info.isSpy();
561}
562
Prabir Pradhanaeebeb42023-06-13 19:53:03 +0000563bool isWindowOwnedBy(const sp<WindowInfoHandle>& windowHandle, gui::Pid pid, gui::Uid uid) {
Antonio Kantek48710e42022-03-24 14:19:30 -0700564 if (windowHandle == nullptr) {
565 return false;
566 }
567 const WindowInfo* windowInfo = windowHandle->getInfo();
568 if (pid == windowInfo->ownerPid && uid == windowInfo->ownerUid) {
569 return true;
570 }
571 return false;
572}
573
Prabir Pradhan5735a322022-04-11 17:23:34 +0000574// Checks targeted injection using the window's owner's uid.
575// Returns an empty string if an entry can be sent to the given window, or an error message if the
576// entry is a targeted injection whose uid target doesn't match the window owner.
577std::optional<std::string> verifyTargetedInjection(const sp<WindowInfoHandle>& window,
578 const EventEntry& entry) {
579 if (entry.injectionState == nullptr || !entry.injectionState->targetUid) {
580 // The event was not injected, or the injected event does not target a window.
581 return {};
582 }
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +0000583 const auto uid = *entry.injectionState->targetUid;
Prabir Pradhan5735a322022-04-11 17:23:34 +0000584 if (window == nullptr) {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +0000585 return StringPrintf("No valid window target for injection into uid %s.",
586 uid.toString().c_str());
Prabir Pradhan5735a322022-04-11 17:23:34 +0000587 }
588 if (entry.injectionState->targetUid != window->getInfo()->ownerUid) {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +0000589 return StringPrintf("Injected event targeted at uid %s would be dispatched to window '%s' "
590 "owned by uid %s.",
591 uid.toString().c_str(), window->getName().c_str(),
592 window->getInfo()->ownerUid.toString().c_str());
Prabir Pradhan5735a322022-04-11 17:23:34 +0000593 }
594 return {};
595}
596
Prabir Pradhan82e081e2022-12-06 09:50:09 +0000597std::pair<float, float> resolveTouchedPosition(const MotionEntry& entry) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -0700598 const bool isFromMouse = isFromSource(entry.source, AINPUT_SOURCE_MOUSE);
599 // Always dispatch mouse events to cursor position.
600 if (isFromMouse) {
Prabir Pradhan82e081e2022-12-06 09:50:09 +0000601 return {entry.xCursorPosition, entry.yCursorPosition};
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -0700602 }
603
Siarhei Vishniakou5b9766d2023-07-18 14:06:29 -0700604 const int32_t pointerIndex = MotionEvent::getActionIndex(entry.action);
Prabir Pradhan82e081e2022-12-06 09:50:09 +0000605 return {entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_X),
606 entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_Y)};
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -0700607}
608
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -0700609std::optional<nsecs_t> getDownTime(const EventEntry& eventEntry) {
610 if (eventEntry.type == EventEntry::Type::KEY) {
611 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
612 return keyEntry.downTime;
613 } else if (eventEntry.type == EventEntry::Type::MOTION) {
614 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
615 return motionEntry.downTime;
616 }
617 return std::nullopt;
618}
619
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000620/**
621 * Compare the old touch state to the new touch state, and generate the corresponding touched
622 * windows (== input targets).
623 * If a window had the hovering pointer, but now it doesn't, produce HOVER_EXIT for that window.
624 * If the pointer just entered the new window, produce HOVER_ENTER.
625 * For pointers remaining in the window, produce HOVER_MOVE.
626 */
627std::vector<TouchedWindow> getHoveringWindowsLocked(const TouchState* oldState,
628 const TouchState& newTouchState,
629 const MotionEntry& entry) {
630 std::vector<TouchedWindow> out;
631 const int32_t maskedAction = MotionEvent::getActionMasked(entry.action);
632 if (maskedAction != AMOTION_EVENT_ACTION_HOVER_ENTER &&
633 maskedAction != AMOTION_EVENT_ACTION_HOVER_MOVE &&
634 maskedAction != AMOTION_EVENT_ACTION_HOVER_EXIT) {
635 // Not a hover event - don't need to do anything
636 return out;
637 }
638
639 // We should consider all hovering pointers here. But for now, just use the first one
640 const int32_t pointerId = entry.pointerProperties[0].id;
641
642 std::set<sp<WindowInfoHandle>> oldWindows;
643 if (oldState != nullptr) {
644 oldWindows = oldState->getWindowsWithHoveringPointer(entry.deviceId, pointerId);
645 }
646
647 std::set<sp<WindowInfoHandle>> newWindows =
648 newTouchState.getWindowsWithHoveringPointer(entry.deviceId, pointerId);
649
650 // If the pointer is no longer in the new window set, send HOVER_EXIT.
651 for (const sp<WindowInfoHandle>& oldWindow : oldWindows) {
652 if (newWindows.find(oldWindow) == newWindows.end()) {
653 TouchedWindow touchedWindow;
654 touchedWindow.windowHandle = oldWindow;
655 touchedWindow.targetFlags = InputTarget::Flags::DISPATCH_AS_HOVER_EXIT;
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000656 out.push_back(touchedWindow);
657 }
658 }
659
660 for (const sp<WindowInfoHandle>& newWindow : newWindows) {
661 TouchedWindow touchedWindow;
662 touchedWindow.windowHandle = newWindow;
663 if (oldWindows.find(newWindow) == oldWindows.end()) {
664 // Any windows that have this pointer now, and didn't have it before, should get
665 // HOVER_ENTER
666 touchedWindow.targetFlags = InputTarget::Flags::DISPATCH_AS_HOVER_ENTER;
667 } else {
668 // This pointer was already sent to the window. Use ACTION_HOVER_MOVE.
Siarhei Vishniakouc2eb8502023-04-11 18:33:36 -0700669 if (CC_UNLIKELY(maskedAction != AMOTION_EVENT_ACTION_HOVER_MOVE)) {
670 LOG(FATAL) << "Expected ACTION_HOVER_MOVE instead of " << entry.getDescription();
671 }
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000672 touchedWindow.targetFlags = InputTarget::Flags::DISPATCH_AS_IS;
673 }
Siarhei Vishniakou0836a302023-05-03 13:54:30 -0700674 touchedWindow.addHoveringPointer(entry.deviceId, pointerId);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000675 if (canReceiveForegroundTouches(*newWindow->getInfo())) {
676 touchedWindow.targetFlags |= InputTarget::Flags::FOREGROUND;
677 }
678 out.push_back(touchedWindow);
679 }
680 return out;
681}
682
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -0800683template <typename T>
684std::vector<T>& operator+=(std::vector<T>& left, const std::vector<T>& right) {
685 left.insert(left.end(), right.begin(), right.end());
686 return left;
687}
688
Harry Cuttsb166c002023-05-09 13:06:05 +0000689// Filter windows in a TouchState and targets in a vector to remove untrusted windows/targets from
690// both.
691void filterUntrustedTargets(TouchState& touchState, std::vector<InputTarget>& targets) {
692 std::erase_if(touchState.windows, [&](const TouchedWindow& window) {
693 if (!window.windowHandle->getInfo()->inputConfig.test(
694 WindowInfo::InputConfig::TRUSTED_OVERLAY)) {
695 // In addition to TouchState, erase this window from the input targets! We don't have a
696 // good way to do this today except by adding a nested loop.
697 // TODO(b/282025641): simplify this code once InputTargets are being identified
698 // separately from TouchedWindows.
699 std::erase_if(targets, [&](const InputTarget& target) {
700 return target.inputChannel->getConnectionToken() == window.windowHandle->getToken();
701 });
702 return true;
703 }
704 return false;
705 });
706}
707
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000708} // namespace
709
Michael Wrightd02c5b62014-02-10 15:10:22 -0800710// --- InputDispatcher ---
711
Prabir Pradhana41d2442023-04-20 21:30:40 +0000712InputDispatcher::InputDispatcher(InputDispatcherPolicyInterface& policy)
Siarhei Vishniakou289e9242022-02-15 14:50:16 -0800713 : InputDispatcher(policy, STALE_EVENT_TIMEOUT) {}
714
Prabir Pradhana41d2442023-04-20 21:30:40 +0000715InputDispatcher::InputDispatcher(InputDispatcherPolicyInterface& policy,
Siarhei Vishniakou289e9242022-02-15 14:50:16 -0800716 std::chrono::nanoseconds staleEventTimeout)
Garfield Tan00f511d2019-06-12 16:55:40 -0700717 : mPolicy(policy),
718 mPendingEvent(nullptr),
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700719 mLastDropReason(DropReason::NOT_DROPPED),
Garfield Tanff1f1bb2020-01-28 13:24:04 -0800720 mIdGenerator(IdGenerator::Source::INPUT_DISPATCHER),
Garfield Tan00f511d2019-06-12 16:55:40 -0700721 mAppSwitchSawKeyDown(false),
Colin Cross5b799302022-10-18 21:52:41 -0700722 mAppSwitchDueTime(LLONG_MAX),
Garfield Tan00f511d2019-06-12 16:55:40 -0700723 mNextUnblockedEvent(nullptr),
Prabir Pradhan1376fcd2022-01-21 09:56:35 -0800724 mMonitorDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT),
Garfield Tan00f511d2019-06-12 16:55:40 -0700725 mDispatchEnabled(false),
726 mDispatchFrozen(false),
727 mInputFilterEnabled(false),
Bernardo Rufinoea97d182020-08-19 14:43:14 +0100728 mMaximumObscuringOpacityForTouch(1.0f),
Siarhei Vishniakou2508b872020-12-03 16:33:53 -1000729 mFocusedDisplayId(ADISPLAY_ID_DEFAULT),
Prabir Pradhan99987712020-11-10 18:43:05 -0800730 mWindowTokenWithPointerCapture(nullptr),
Siarhei Vishniakou289e9242022-02-15 14:50:16 -0800731 mStaleEventTimeout(staleEventTimeout),
Siarhei Vishniakoua04181f2021-03-26 05:56:49 +0000732 mLatencyAggregator(),
Antonio Kantek15beb512022-06-13 22:35:41 +0000733 mLatencyTracker(&mLatencyAggregator) {
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -0700734 mLooper = sp<Looper>::make(false);
Prabir Pradhanf93562f2018-11-29 12:13:37 -0800735 mReporter = createInputReporter();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800736
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -0700737 mWindowInfoListener = sp<DispatcherWindowListener>::make(*this);
Siarhei Vishniakou31977182022-09-30 08:51:23 -0700738#if defined(__ANDROID__)
Siarhei Vishniakou18050092021-09-01 13:32:49 -0700739 SurfaceComposerClient::getDefault()->addWindowInfosListener(mWindowInfoListener);
Siarhei Vishniakou31977182022-09-30 08:51:23 -0700740#endif
Yi Kong9b14ac62018-07-17 13:48:38 -0700741 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800742}
743
744InputDispatcher::~InputDispatcher() {
Prabir Pradhancef936d2021-07-21 16:17:52 +0000745 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800746
Prabir Pradhancef936d2021-07-21 16:17:52 +0000747 resetKeyRepeatLocked();
748 releasePendingEventLocked();
749 drainInboundQueueLocked();
750 mCommandQueue.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800751
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +0000752 while (!mConnectionsByToken.empty()) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -0700753 std::shared_ptr<Connection> connection = mConnectionsByToken.begin()->second;
Harry Cutts33476232023-01-30 19:57:29 +0000754 removeInputChannelLocked(connection->inputChannel->getConnectionToken(), /*notify=*/false);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800755 }
756}
757
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700758status_t InputDispatcher::start() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700759 if (mThread) {
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700760 return ALREADY_EXISTS;
761 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700762 mThread = std::make_unique<InputThread>(
763 "InputDispatcher", [this]() { dispatchOnce(); }, [this]() { mLooper->wake(); });
764 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700765}
766
767status_t InputDispatcher::stop() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700768 if (mThread && mThread->isCallingThread()) {
769 ALOGE("InputDispatcher cannot be stopped from its own thread!");
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700770 return INVALID_OPERATION;
771 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700772 mThread.reset();
773 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700774}
775
Michael Wrightd02c5b62014-02-10 15:10:22 -0800776void InputDispatcher::dispatchOnce() {
Colin Cross5b799302022-10-18 21:52:41 -0700777 nsecs_t nextWakeupTime = LLONG_MAX;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800778 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -0800779 std::scoped_lock _l(mLock);
780 mDispatcherIsAlive.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800781
782 // Run a dispatch loop if there are no pending commands.
783 // The dispatch loop might enqueue commands to run afterwards.
784 if (!haveCommandsLocked()) {
785 dispatchOnceInnerLocked(&nextWakeupTime);
786 }
787
788 // Run all pending commands if there are any.
789 // If any commands were run then force the next poll to wake up immediately.
Prabir Pradhancef936d2021-07-21 16:17:52 +0000790 if (runCommandsLockedInterruptable()) {
Colin Cross5b799302022-10-18 21:52:41 -0700791 nextWakeupTime = LLONG_MIN;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800792 }
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800793
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700794 // If we are still waiting for ack on some events,
795 // we might have to wake up earlier to check if an app is anr'ing.
796 const nsecs_t nextAnrCheck = processAnrsLocked();
797 nextWakeupTime = std::min(nextWakeupTime, nextAnrCheck);
798
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800799 // We are about to enter an infinitely long sleep, because we have no commands or
800 // pending or queued events
Colin Cross5b799302022-10-18 21:52:41 -0700801 if (nextWakeupTime == LLONG_MAX) {
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800802 mDispatcherEnteredIdle.notify_all();
803 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800804 } // release lock
805
806 // Wait for callback or timeout or wake. (make sure we round up, not down)
807 nsecs_t currentTime = now();
808 int timeoutMillis = toMillisecondTimeoutDelay(currentTime, nextWakeupTime);
809 mLooper->pollOnce(timeoutMillis);
810}
811
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700812/**
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500813 * Raise ANR if there is no focused window.
814 * Before the ANR is raised, do a final state check:
815 * 1. The currently focused application must be the same one we are waiting for.
816 * 2. Ensure we still don't have a focused window.
817 */
818void InputDispatcher::processNoFocusedWindowAnrLocked() {
819 // Check if the application that we are waiting for is still focused.
820 std::shared_ptr<InputApplicationHandle> focusedApplication =
821 getValueByKey(mFocusedApplicationHandlesByDisplay, mAwaitedApplicationDisplayId);
822 if (focusedApplication == nullptr ||
823 focusedApplication->getApplicationToken() !=
824 mAwaitedFocusedApplication->getApplicationToken()) {
825 // Unexpected because we should have reset the ANR timer when focused application changed
826 ALOGE("Waited for a focused window, but focused application has already changed to %s",
827 focusedApplication->getName().c_str());
828 return; // The focused application has changed.
829 }
830
chaviw98318de2021-05-19 16:45:23 -0500831 const sp<WindowInfoHandle>& focusedWindowHandle =
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500832 getFocusedWindowHandleLocked(mAwaitedApplicationDisplayId);
833 if (focusedWindowHandle != nullptr) {
834 return; // We now have a focused window. No need for ANR.
835 }
836 onAnrLocked(mAwaitedFocusedApplication);
837}
838
839/**
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700840 * Check if any of the connections' wait queues have events that are too old.
841 * If we waited for events to be ack'ed for more than the window timeout, raise an ANR.
842 * Return the time at which we should wake up next.
843 */
844nsecs_t InputDispatcher::processAnrsLocked() {
845 const nsecs_t currentTime = now();
Colin Cross5b799302022-10-18 21:52:41 -0700846 nsecs_t nextAnrCheck = LLONG_MAX;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700847 // Check if we are waiting for a focused window to appear. Raise ANR if waited too long
848 if (mNoFocusedWindowTimeoutTime.has_value() && mAwaitedFocusedApplication != nullptr) {
849 if (currentTime >= *mNoFocusedWindowTimeoutTime) {
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500850 processNoFocusedWindowAnrLocked();
Chris Yea209fde2020-07-22 13:54:51 -0700851 mAwaitedFocusedApplication.reset();
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500852 mNoFocusedWindowTimeoutTime = std::nullopt;
Colin Cross5b799302022-10-18 21:52:41 -0700853 return LLONG_MIN;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700854 } else {
Siarhei Vishniakou38a6d272020-10-20 20:29:33 -0500855 // Keep waiting. We will drop the event when mNoFocusedWindowTimeoutTime comes.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700856 nextAnrCheck = *mNoFocusedWindowTimeoutTime;
857 }
858 }
859
860 // Check if any connection ANRs are due
861 nextAnrCheck = std::min(nextAnrCheck, mAnrTracker.firstTimeout());
862 if (currentTime < nextAnrCheck) { // most likely scenario
863 return nextAnrCheck; // everything is normal. Let's check again at nextAnrCheck
864 }
865
866 // If we reached here, we have an unresponsive connection.
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -0700867 std::shared_ptr<Connection> connection = getConnectionLocked(mAnrTracker.firstToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700868 if (connection == nullptr) {
869 ALOGE("Could not find connection for entry %" PRId64, mAnrTracker.firstTimeout());
870 return nextAnrCheck;
871 }
872 connection->responsive = false;
873 // Stop waking up for this unresponsive connection
874 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000875 onAnrLocked(connection);
Colin Cross5b799302022-10-18 21:52:41 -0700876 return LLONG_MIN;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700877}
878
Prabir Pradhan1376fcd2022-01-21 09:56:35 -0800879std::chrono::nanoseconds InputDispatcher::getDispatchingTimeoutLocked(
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -0700880 const std::shared_ptr<Connection>& connection) {
Prabir Pradhan1376fcd2022-01-21 09:56:35 -0800881 if (connection->monitor) {
882 return mMonitorDispatchingTimeout;
883 }
884 const sp<WindowInfoHandle> window =
885 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700886 if (window != nullptr) {
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500887 return window->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700888 }
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500889 return DEFAULT_INPUT_DISPATCHING_TIMEOUT;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700890}
891
Michael Wrightd02c5b62014-02-10 15:10:22 -0800892void InputDispatcher::dispatchOnceInnerLocked(nsecs_t* nextWakeupTime) {
893 nsecs_t currentTime = now();
894
Jeff Browndc5992e2014-04-11 01:27:26 -0700895 // Reset the key repeat timer whenever normal dispatch is suspended while the
896 // device is in a non-interactive state. This is to ensure that we abort a key
897 // repeat if the device is just coming out of sleep.
898 if (!mDispatchEnabled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800899 resetKeyRepeatLocked();
900 }
901
902 // If dispatching is frozen, do not process timeouts or try to deliver any new events.
903 if (mDispatchFrozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +0100904 if (DEBUG_FOCUS) {
905 ALOGD("Dispatch frozen. Waiting some more.");
906 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800907 return;
908 }
909
910 // Optimize latency of app switches.
911 // Essentially we start a short timeout when an app switch key (HOME / ENDCALL) has
912 // been pressed. When it expires, we preempt dispatch and drop all other pending events.
913 bool isAppSwitchDue = mAppSwitchDueTime <= currentTime;
914 if (mAppSwitchDueTime < *nextWakeupTime) {
915 *nextWakeupTime = mAppSwitchDueTime;
916 }
917
918 // Ready to start a new event.
919 // If we don't already have a pending event, go grab one.
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700920 if (!mPendingEvent) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700921 if (mInboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800922 if (isAppSwitchDue) {
923 // The inbound queue is empty so the app switch key we were waiting
924 // for will never arrive. Stop waiting for it.
925 resetPendingAppSwitchLocked(false);
926 isAppSwitchDue = false;
927 }
928
929 // Synthesize a key repeat if appropriate.
930 if (mKeyRepeatState.lastKeyEntry) {
931 if (currentTime >= mKeyRepeatState.nextRepeatTime) {
932 mPendingEvent = synthesizeKeyRepeatLocked(currentTime);
933 } else {
934 if (mKeyRepeatState.nextRepeatTime < *nextWakeupTime) {
935 *nextWakeupTime = mKeyRepeatState.nextRepeatTime;
936 }
937 }
938 }
939
940 // Nothing to do if there is no pending event.
941 if (!mPendingEvent) {
942 return;
943 }
944 } else {
945 // Inbound queue has at least one entry.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700946 mPendingEvent = mInboundQueue.front();
947 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800948 traceInboundQueueLengthLocked();
949 }
950
951 // Poke user activity for this event.
952 if (mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700953 pokeUserActivityLocked(*mPendingEvent);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800954 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800955 }
956
957 // Now we have an event to dispatch.
958 // All events are eventually dequeued and processed this way, even if we intend to drop them.
Yi Kong9b14ac62018-07-17 13:48:38 -0700959 ALOG_ASSERT(mPendingEvent != nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800960 bool done = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700961 DropReason dropReason = DropReason::NOT_DROPPED;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800962 if (!(mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700963 dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800964 } else if (!mDispatchEnabled) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700965 dropReason = DropReason::DISABLED;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800966 }
967
968 if (mNextUnblockedEvent == mPendingEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -0700969 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800970 }
971
972 switch (mPendingEvent->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700973 case EventEntry::Type::CONFIGURATION_CHANGED: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700974 const ConfigurationChangedEntry& typedEntry =
975 static_cast<const ConfigurationChangedEntry&>(*mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700976 done = dispatchConfigurationChangedLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700977 dropReason = DropReason::NOT_DROPPED; // configuration changes are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700978 break;
979 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800980
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700981 case EventEntry::Type::DEVICE_RESET: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700982 const DeviceResetEntry& typedEntry =
983 static_cast<const DeviceResetEntry&>(*mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700984 done = dispatchDeviceResetLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700985 dropReason = DropReason::NOT_DROPPED; // device resets are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700986 break;
987 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800988
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100989 case EventEntry::Type::FOCUS: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700990 std::shared_ptr<FocusEntry> typedEntry =
991 std::static_pointer_cast<FocusEntry>(mPendingEvent);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100992 dispatchFocusLocked(currentTime, typedEntry);
993 done = true;
994 dropReason = DropReason::NOT_DROPPED; // focus events are never dropped
995 break;
996 }
997
Antonio Kantek7242d8b2021-08-05 16:07:20 -0700998 case EventEntry::Type::TOUCH_MODE_CHANGED: {
999 const auto typedEntry = std::static_pointer_cast<TouchModeEntry>(mPendingEvent);
1000 dispatchTouchModeChangeLocked(currentTime, typedEntry);
1001 done = true;
1002 dropReason = DropReason::NOT_DROPPED; // touch mode events are never dropped
1003 break;
1004 }
1005
Prabir Pradhan99987712020-11-10 18:43:05 -08001006 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
1007 const auto typedEntry =
1008 std::static_pointer_cast<PointerCaptureChangedEntry>(mPendingEvent);
1009 dispatchPointerCaptureChangedLocked(currentTime, typedEntry, dropReason);
1010 done = true;
1011 break;
1012 }
1013
arthurhungb89ccb02020-12-30 16:19:01 +08001014 case EventEntry::Type::DRAG: {
1015 std::shared_ptr<DragEntry> typedEntry =
1016 std::static_pointer_cast<DragEntry>(mPendingEvent);
1017 dispatchDragLocked(currentTime, typedEntry);
1018 done = true;
1019 break;
1020 }
1021
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001022 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001023 std::shared_ptr<KeyEntry> keyEntry = std::static_pointer_cast<KeyEntry>(mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001024 if (isAppSwitchDue) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001025 if (isAppSwitchKeyEvent(*keyEntry)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001026 resetPendingAppSwitchLocked(true);
1027 isAppSwitchDue = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001028 } else if (dropReason == DropReason::NOT_DROPPED) {
1029 dropReason = DropReason::APP_SWITCH;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001030 }
1031 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001032 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *keyEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001033 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001034 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001035 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
1036 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001037 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001038 done = dispatchKeyLocked(currentTime, keyEntry, &dropReason, nextWakeupTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001039 break;
1040 }
1041
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001042 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001043 std::shared_ptr<MotionEntry> motionEntry =
1044 std::static_pointer_cast<MotionEntry>(mPendingEvent);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001045 if (dropReason == DropReason::NOT_DROPPED && isAppSwitchDue) {
1046 dropReason = DropReason::APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001047 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001048 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *motionEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001049 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001050 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001051 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
1052 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001053 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001054 done = dispatchMotionLocked(currentTime, motionEntry, &dropReason, nextWakeupTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001055 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001056 }
Chris Yef59a2f42020-10-16 12:55:26 -07001057
1058 case EventEntry::Type::SENSOR: {
1059 std::shared_ptr<SensorEntry> sensorEntry =
1060 std::static_pointer_cast<SensorEntry>(mPendingEvent);
1061 if (dropReason == DropReason::NOT_DROPPED && isAppSwitchDue) {
1062 dropReason = DropReason::APP_SWITCH;
1063 }
1064 // Sensor timestamps use SYSTEM_TIME_BOOTTIME time base, so we can't use
1065 // 'currentTime' here, get SYSTEM_TIME_BOOTTIME instead.
1066 nsecs_t bootTime = systemTime(SYSTEM_TIME_BOOTTIME);
1067 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(bootTime, *sensorEntry)) {
1068 dropReason = DropReason::STALE;
1069 }
1070 dispatchSensorLocked(currentTime, sensorEntry, &dropReason, nextWakeupTime);
1071 done = true;
1072 break;
1073 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001074 }
1075
1076 if (done) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001077 if (dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001078 dropInboundEventLocked(*mPendingEvent, dropReason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001079 }
Michael Wright3a981722015-06-10 15:26:13 +01001080 mLastDropReason = dropReason;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001081
1082 releasePendingEventLocked();
Colin Cross5b799302022-10-18 21:52:41 -07001083 *nextWakeupTime = LLONG_MIN; // force next poll to wake up immediately
Michael Wrightd02c5b62014-02-10 15:10:22 -08001084 }
1085}
1086
Siarhei Vishniakou289e9242022-02-15 14:50:16 -08001087bool InputDispatcher::isStaleEvent(nsecs_t currentTime, const EventEntry& entry) {
1088 return std::chrono::nanoseconds(currentTime - entry.eventTime) >= mStaleEventTimeout;
1089}
1090
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001091/**
1092 * Return true if the events preceding this incoming motion event should be dropped
1093 * Return false otherwise (the default behaviour)
1094 */
1095bool InputDispatcher::shouldPruneInboundQueueLocked(const MotionEntry& motionEntry) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001096 const bool isPointerDownEvent = motionEntry.action == AMOTION_EVENT_ACTION_DOWN &&
Prabir Pradhanaa561d12021-09-24 06:57:33 -07001097 isFromSource(motionEntry.source, AINPUT_SOURCE_CLASS_POINTER);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001098
1099 // Optimize case where the current application is unresponsive and the user
1100 // decides to touch a window in a different application.
1101 // If the application takes too long to catch up then we drop all events preceding
1102 // the touch into the other window.
1103 if (isPointerDownEvent && mAwaitedFocusedApplication != nullptr) {
Siarhei Vishniakou9306c382022-09-30 15:30:31 -07001104 const int32_t displayId = motionEntry.displayId;
1105 const auto [x, y] = resolveTouchedPosition(motionEntry);
Harry Cutts33476232023-01-30 19:57:29 +00001106 const bool isStylus = isPointerFromStylus(motionEntry, /*pointerIndex=*/0);
Siarhei Vishniakou9306c382022-09-30 15:30:31 -07001107
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08001108 auto [touchedWindowHandle, _] = findTouchedWindowAtLocked(displayId, x, y, isStylus);
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001109 if (touchedWindowHandle != nullptr &&
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001110 touchedWindowHandle->getApplicationToken() !=
1111 mAwaitedFocusedApplication->getApplicationToken()) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001112 // User touched a different application than the one we are waiting on.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001113 ALOGI("Pruning input queue because user touched a different application while waiting "
1114 "for %s",
1115 mAwaitedFocusedApplication->getName().c_str());
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001116 return true;
1117 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001118
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08001119 // Alternatively, maybe there's a spy window that could handle this event.
1120 const std::vector<sp<WindowInfoHandle>> touchedSpies =
1121 findTouchedSpyWindowsAtLocked(displayId, x, y, isStylus);
1122 for (const auto& windowHandle : touchedSpies) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07001123 const std::shared_ptr<Connection> connection =
1124 getConnectionLocked(windowHandle->getToken());
Siarhei Vishniakou34ed4d42020-06-18 00:43:02 +00001125 if (connection != nullptr && connection->responsive) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08001126 // This spy window could take more input. Drop all events preceding this
1127 // event, so that the spy window can get a chance to receive the stream.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001128 ALOGW("Pruning the input queue because %s is unresponsive, but we have a "
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08001129 "responsive spy window that may handle the event.",
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001130 mAwaitedFocusedApplication->getName().c_str());
1131 return true;
1132 }
1133 }
1134 }
1135
1136 // Prevent getting stuck: if we have a pending key event, and some motion events that have not
1137 // yet been processed by some connections, the dispatcher will wait for these motion
1138 // events to be processed before dispatching the key event. This is because these motion events
1139 // may cause a new window to be launched, which the user might expect to receive focus.
1140 // To prevent waiting forever for such events, just send the key to the currently focused window
1141 if (isPointerDownEvent && mKeyIsWaitingForEventsTimeout) {
1142 ALOGD("Received a new pointer down event, stop waiting for events to process and "
1143 "just send the pending key event to the focused window.");
1144 mKeyIsWaitingForEventsTimeout = now();
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001145 }
1146 return false;
1147}
1148
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001149bool InputDispatcher::enqueueInboundEventLocked(std::unique_ptr<EventEntry> newEntry) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001150 bool needWake = mInboundQueue.empty();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001151 mInboundQueue.push_back(std::move(newEntry));
1152 EventEntry& entry = *(mInboundQueue.back());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001153 traceInboundQueueLengthLocked();
1154
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001155 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001156 case EventEntry::Type::KEY: {
Prabir Pradhan5735a322022-04-11 17:23:34 +00001157 LOG_ALWAYS_FATAL_IF((entry.policyFlags & POLICY_FLAG_TRUSTED) == 0,
1158 "Unexpected untrusted event.");
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001159 // Optimize app switch latency.
1160 // If the application takes too long to catch up then we drop all events preceding
1161 // the app switch key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001162 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001163 if (isAppSwitchKeyEvent(keyEntry)) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001164 if (keyEntry.action == AKEY_EVENT_ACTION_DOWN) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001165 mAppSwitchSawKeyDown = true;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001166 } else if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001167 if (mAppSwitchSawKeyDown) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001168 if (DEBUG_APP_SWITCH) {
1169 ALOGD("App switch is pending!");
1170 }
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001171 mAppSwitchDueTime = keyEntry.eventTime + APP_SWITCH_TIMEOUT;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001172 mAppSwitchSawKeyDown = false;
1173 needWake = true;
1174 }
1175 }
1176 }
Arthur Hung2ee6d0b2022-03-03 20:19:38 +08001177
1178 // If a new up event comes in, and the pending event with same key code has been asked
1179 // to try again later because of the policy. We have to reset the intercept key wake up
1180 // time for it may have been handled in the policy and could be dropped.
1181 if (keyEntry.action == AKEY_EVENT_ACTION_UP && mPendingEvent &&
1182 mPendingEvent->type == EventEntry::Type::KEY) {
1183 KeyEntry& pendingKey = static_cast<KeyEntry&>(*mPendingEvent);
1184 if (pendingKey.keyCode == keyEntry.keyCode &&
1185 pendingKey.interceptKeyResult ==
Michael Wright5caf55a2022-11-24 22:31:42 +00001186 KeyEntry::InterceptKeyResult::TRY_AGAIN_LATER) {
1187 pendingKey.interceptKeyResult = KeyEntry::InterceptKeyResult::UNKNOWN;
Arthur Hung2ee6d0b2022-03-03 20:19:38 +08001188 pendingKey.interceptKeyWakeupTime = 0;
1189 needWake = true;
1190 }
1191 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001192 break;
1193 }
1194
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001195 case EventEntry::Type::MOTION: {
Prabir Pradhan5735a322022-04-11 17:23:34 +00001196 LOG_ALWAYS_FATAL_IF((entry.policyFlags & POLICY_FLAG_TRUSTED) == 0,
1197 "Unexpected untrusted event.");
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001198 if (shouldPruneInboundQueueLocked(static_cast<MotionEntry&>(entry))) {
1199 mNextUnblockedEvent = mInboundQueue.back();
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001200 needWake = true;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001201 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001202 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001203 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001204 case EventEntry::Type::FOCUS: {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001205 LOG_ALWAYS_FATAL("Focus events should be inserted using enqueueFocusEventLocked");
1206 break;
1207 }
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001208 case EventEntry::Type::TOUCH_MODE_CHANGED:
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001209 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08001210 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07001211 case EventEntry::Type::SENSOR:
arthurhungb89ccb02020-12-30 16:19:01 +08001212 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
1213 case EventEntry::Type::DRAG: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001214 // nothing to do
1215 break;
1216 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001217 }
1218
1219 return needWake;
1220}
1221
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001222void InputDispatcher::addRecentEventLocked(std::shared_ptr<EventEntry> entry) {
Chris Yef59a2f42020-10-16 12:55:26 -07001223 // Do not store sensor event in recent queue to avoid flooding the queue.
1224 if (entry->type != EventEntry::Type::SENSOR) {
1225 mRecentQueue.push_back(entry);
1226 }
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001227 if (mRecentQueue.size() > RECENT_QUEUE_MAX_SIZE) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001228 mRecentQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001229 }
1230}
1231
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08001232std::pair<sp<WindowInfoHandle>, std::vector<InputTarget>>
Prabir Pradhan82e081e2022-12-06 09:50:09 +00001233InputDispatcher::findTouchedWindowAtLocked(int32_t displayId, float x, float y, bool isStylus,
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08001234 bool ignoreDragWindow) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001235 // Traverse windows from front to back to find touched window.
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08001236 std::vector<InputTarget> outsideTargets;
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001237 const auto& windowHandles = getWindowHandlesLocked(displayId);
chaviw98318de2021-05-19 16:45:23 -05001238 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
arthurhung6d4bed92021-03-17 11:59:33 +08001239 if (ignoreDragWindow && haveSameToken(windowHandle, mDragState->dragWindow)) {
arthurhungb89ccb02020-12-30 16:19:01 +08001240 continue;
1241 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001242
Prabir Pradhan3f90d312021-11-19 03:57:24 -08001243 const WindowInfo& info = *windowHandle->getInfo();
Prabir Pradhan33e3baa2022-12-06 20:30:22 +00001244 if (!info.isSpy() &&
1245 windowAcceptsTouchAt(info, displayId, x, y, isStylus, getTransformLocked(displayId))) {
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08001246 return {windowHandle, outsideTargets};
Prabir Pradhan3f90d312021-11-19 03:57:24 -08001247 }
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001248
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08001249 if (info.inputConfig.test(WindowInfo::InputConfig::WATCH_OUTSIDE_TOUCH)) {
1250 addWindowTargetLocked(windowHandle, InputTarget::Flags::DISPATCH_AS_OUTSIDE,
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08001251 /*pointerIds=*/{}, /*firstDownTimeInTarget=*/std::nullopt,
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08001252 outsideTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001253 }
1254 }
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08001255 return {nullptr, {}};
Michael Wrightd02c5b62014-02-10 15:10:22 -08001256}
1257
Prabir Pradhand65552b2021-10-07 11:23:50 -07001258std::vector<sp<WindowInfoHandle>> InputDispatcher::findTouchedSpyWindowsAtLocked(
Prabir Pradhan82e081e2022-12-06 09:50:09 +00001259 int32_t displayId, float x, float y, bool isStylus) const {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001260 // Traverse windows from front to back and gather the touched spy windows.
1261 std::vector<sp<WindowInfoHandle>> spyWindows;
1262 const auto& windowHandles = getWindowHandlesLocked(displayId);
1263 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
1264 const WindowInfo& info = *windowHandle->getInfo();
1265
Prabir Pradhan33e3baa2022-12-06 20:30:22 +00001266 if (!windowAcceptsTouchAt(info, displayId, x, y, isStylus, getTransformLocked(displayId))) {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001267 continue;
1268 }
1269 if (!info.isSpy()) {
1270 // The first touched non-spy window was found, so return the spy windows touched so far.
1271 return spyWindows;
1272 }
1273 spyWindows.push_back(windowHandle);
1274 }
1275 return spyWindows;
1276}
1277
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001278void InputDispatcher::dropInboundEventLocked(const EventEntry& entry, DropReason dropReason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001279 const char* reason;
1280 switch (dropReason) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001281 case DropReason::POLICY:
Prabir Pradhan65613802023-02-22 23:36:58 +00001282 if (debugInboundEventDetails()) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001283 ALOGD("Dropped event because policy consumed it.");
1284 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001285 reason = "inbound event was dropped because the policy consumed it";
1286 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001287 case DropReason::DISABLED:
1288 if (mLastDropReason != DropReason::DISABLED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001289 ALOGI("Dropped event because input dispatch is disabled.");
1290 }
1291 reason = "inbound event was dropped because input dispatch is disabled";
1292 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001293 case DropReason::APP_SWITCH:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001294 ALOGI("Dropped event because of pending overdue app switch.");
1295 reason = "inbound event was dropped because of pending overdue app switch";
1296 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001297 case DropReason::BLOCKED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001298 ALOGI("Dropped event because the current application is not responding and the user "
1299 "has started interacting with a different application.");
1300 reason = "inbound event was dropped because the current application is not responding "
1301 "and the user has started interacting with a different application";
1302 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001303 case DropReason::STALE:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001304 ALOGI("Dropped event because it is stale.");
1305 reason = "inbound event was dropped because it is stale";
1306 break;
Prabir Pradhan99987712020-11-10 18:43:05 -08001307 case DropReason::NO_POINTER_CAPTURE:
1308 ALOGI("Dropped event because there is no window with Pointer Capture.");
1309 reason = "inbound event was dropped because there is no window with Pointer Capture";
1310 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001311 case DropReason::NOT_DROPPED: {
1312 LOG_ALWAYS_FATAL("Should not be dropping a NOT_DROPPED event");
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001313 return;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001314 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001315 }
1316
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001317 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001318 case EventEntry::Type::KEY: {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001319 CancelationOptions options(CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS, reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001320 synthesizeCancelationEventsForAllConnectionsLocked(options);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001321 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001322 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001323 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001324 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
1325 if (motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001326 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS, reason);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001327 synthesizeCancelationEventsForAllConnectionsLocked(options);
1328 } else {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001329 CancelationOptions options(CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS,
1330 reason);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001331 synthesizeCancelationEventsForAllConnectionsLocked(options);
1332 }
1333 break;
1334 }
Chris Yef59a2f42020-10-16 12:55:26 -07001335 case EventEntry::Type::SENSOR: {
1336 break;
1337 }
arthurhungb89ccb02020-12-30 16:19:01 +08001338 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
1339 case EventEntry::Type::DRAG: {
Prabir Pradhan99987712020-11-10 18:43:05 -08001340 break;
1341 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001342 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001343 case EventEntry::Type::TOUCH_MODE_CHANGED:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001344 case EventEntry::Type::CONFIGURATION_CHANGED:
1345 case EventEntry::Type::DEVICE_RESET: {
Dominik Laskowski75788452021-02-09 18:51:25 -08001346 LOG_ALWAYS_FATAL("Should not drop %s events", ftl::enum_string(entry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001347 break;
1348 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001349 }
1350}
1351
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08001352static bool isAppSwitchKeyCode(int32_t keyCode) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001353 return keyCode == AKEYCODE_HOME || keyCode == AKEYCODE_ENDCALL ||
1354 keyCode == AKEYCODE_APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001355}
1356
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001357bool InputDispatcher::isAppSwitchKeyEvent(const KeyEntry& keyEntry) {
1358 return !(keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) && isAppSwitchKeyCode(keyEntry.keyCode) &&
1359 (keyEntry.policyFlags & POLICY_FLAG_TRUSTED) &&
1360 (keyEntry.policyFlags & POLICY_FLAG_PASS_TO_USER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001361}
1362
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07001363bool InputDispatcher::isAppSwitchPendingLocked() const {
Colin Cross5b799302022-10-18 21:52:41 -07001364 return mAppSwitchDueTime != LLONG_MAX;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001365}
1366
1367void InputDispatcher::resetPendingAppSwitchLocked(bool handled) {
Colin Cross5b799302022-10-18 21:52:41 -07001368 mAppSwitchDueTime = LLONG_MAX;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001369
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001370 if (DEBUG_APP_SWITCH) {
1371 if (handled) {
1372 ALOGD("App switch has arrived.");
1373 } else {
1374 ALOGD("App switch was abandoned.");
1375 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001376 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001377}
1378
Michael Wrightd02c5b62014-02-10 15:10:22 -08001379bool InputDispatcher::haveCommandsLocked() const {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001380 return !mCommandQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001381}
1382
Prabir Pradhancef936d2021-07-21 16:17:52 +00001383bool InputDispatcher::runCommandsLockedInterruptable() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001384 if (mCommandQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001385 return false;
1386 }
1387
1388 do {
Prabir Pradhancef936d2021-07-21 16:17:52 +00001389 auto command = std::move(mCommandQueue.front());
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001390 mCommandQueue.pop_front();
Prabir Pradhancef936d2021-07-21 16:17:52 +00001391 // Commands are run with the lock held, but may release and re-acquire the lock from within.
1392 command();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001393 } while (!mCommandQueue.empty());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001394 return true;
1395}
1396
Prabir Pradhancef936d2021-07-21 16:17:52 +00001397void InputDispatcher::postCommandLocked(Command&& command) {
1398 mCommandQueue.push_back(command);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001399}
1400
1401void InputDispatcher::drainInboundQueueLocked() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001402 while (!mInboundQueue.empty()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001403 std::shared_ptr<EventEntry> entry = mInboundQueue.front();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001404 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001405 releaseInboundEventLocked(entry);
1406 }
1407 traceInboundQueueLengthLocked();
1408}
1409
1410void InputDispatcher::releasePendingEventLocked() {
1411 if (mPendingEvent) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001412 releaseInboundEventLocked(mPendingEvent);
Yi Kong9b14ac62018-07-17 13:48:38 -07001413 mPendingEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001414 }
1415}
1416
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001417void InputDispatcher::releaseInboundEventLocked(std::shared_ptr<EventEntry> entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001418 InjectionState* injectionState = entry->injectionState;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001419 if (injectionState && injectionState->injectionResult == InputEventInjectionResult::PENDING) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001420 if (DEBUG_DISPATCH_CYCLE) {
1421 ALOGD("Injected inbound event was dropped.");
1422 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001423 setInjectionResult(*entry, InputEventInjectionResult::FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001424 }
1425 if (entry == mNextUnblockedEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001426 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001427 }
1428 addRecentEventLocked(entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001429}
1430
1431void InputDispatcher::resetKeyRepeatLocked() {
1432 if (mKeyRepeatState.lastKeyEntry) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001433 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001434 }
1435}
1436
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001437std::shared_ptr<KeyEntry> InputDispatcher::synthesizeKeyRepeatLocked(nsecs_t currentTime) {
1438 std::shared_ptr<KeyEntry> entry = mKeyRepeatState.lastKeyEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001439
Michael Wright2e732952014-09-24 13:26:59 -07001440 uint32_t policyFlags = entry->policyFlags &
1441 (POLICY_FLAG_RAW_MASK | POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_TRUSTED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001442
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001443 std::shared_ptr<KeyEntry> newEntry =
1444 std::make_unique<KeyEntry>(mIdGenerator.nextId(), currentTime, entry->deviceId,
1445 entry->source, entry->displayId, policyFlags, entry->action,
1446 entry->flags, entry->keyCode, entry->scanCode,
1447 entry->metaState, entry->repeatCount + 1, entry->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001448
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001449 newEntry->syntheticRepeat = true;
1450 mKeyRepeatState.lastKeyEntry = newEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001451 mKeyRepeatState.nextRepeatTime = currentTime + mConfig.keyRepeatDelay;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001452 return newEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001453}
1454
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001455bool InputDispatcher::dispatchConfigurationChangedLocked(nsecs_t currentTime,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001456 const ConfigurationChangedEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001457 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1458 ALOGD("dispatchConfigurationChanged - eventTime=%" PRId64, entry.eventTime);
1459 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001460
1461 // Reset key repeating in case a keyboard device was added or removed or something.
1462 resetKeyRepeatLocked();
1463
1464 // Enqueue a command to run outside the lock to tell the policy that the configuration changed.
Prabir Pradhancef936d2021-07-21 16:17:52 +00001465 auto command = [this, eventTime = entry.eventTime]() REQUIRES(mLock) {
1466 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00001467 mPolicy.notifyConfigurationChanged(eventTime);
Prabir Pradhancef936d2021-07-21 16:17:52 +00001468 };
1469 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001470 return true;
1471}
1472
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001473bool InputDispatcher::dispatchDeviceResetLocked(nsecs_t currentTime,
1474 const DeviceResetEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001475 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1476 ALOGD("dispatchDeviceReset - eventTime=%" PRId64 ", deviceId=%d", entry.eventTime,
1477 entry.deviceId);
1478 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001479
liushenxiang42232912021-05-21 20:24:09 +08001480 // Reset key repeating in case a keyboard device was disabled or enabled.
1481 if (mKeyRepeatState.lastKeyEntry && mKeyRepeatState.lastKeyEntry->deviceId == entry.deviceId) {
1482 resetKeyRepeatLocked();
1483 }
1484
Michael Wrightfb04fd52022-11-24 22:31:11 +00001485 CancelationOptions options(CancelationOptions::Mode::CANCEL_ALL_EVENTS, "device was reset");
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001486 options.deviceId = entry.deviceId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001487 synthesizeCancelationEventsForAllConnectionsLocked(options);
Siarhei Vishniakou0686f0c2023-05-02 11:56:15 -07001488
1489 // Remove all active pointers from this device
1490 for (auto& [_, touchState] : mTouchStatesByDisplay) {
1491 touchState.removeAllPointersForDevice(entry.deviceId);
1492 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001493 return true;
1494}
1495
Vishnu Nairad321cd2020-08-20 16:40:21 -07001496void InputDispatcher::enqueueFocusEventLocked(const sp<IBinder>& windowToken, bool hasFocus,
Vishnu Nairc519ff72021-01-21 08:23:08 -08001497 const std::string& reason) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001498 if (mPendingEvent != nullptr) {
1499 // Move the pending event to the front of the queue. This will give the chance
1500 // for the pending event to get dispatched to the newly focused window
1501 mInboundQueue.push_front(mPendingEvent);
1502 mPendingEvent = nullptr;
1503 }
1504
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001505 std::unique_ptr<FocusEntry> focusEntry =
1506 std::make_unique<FocusEntry>(mIdGenerator.nextId(), now(), windowToken, hasFocus,
1507 reason);
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001508
1509 // This event should go to the front of the queue, but behind all other focus events
1510 // Find the last focus event, and insert right after it
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001511 std::deque<std::shared_ptr<EventEntry>>::reverse_iterator it =
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001512 std::find_if(mInboundQueue.rbegin(), mInboundQueue.rend(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001513 [](const std::shared_ptr<EventEntry>& event) {
1514 return event->type == EventEntry::Type::FOCUS;
1515 });
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001516
1517 // Maintain the order of focus events. Insert the entry after all other focus events.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001518 mInboundQueue.insert(it.base(), std::move(focusEntry));
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001519}
1520
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001521void InputDispatcher::dispatchFocusLocked(nsecs_t currentTime, std::shared_ptr<FocusEntry> entry) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05001522 std::shared_ptr<InputChannel> channel = getInputChannelLocked(entry->connectionToken);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001523 if (channel == nullptr) {
1524 return; // Window has gone away
1525 }
1526 InputTarget target;
1527 target.inputChannel = channel;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08001528 target.flags = InputTarget::Flags::DISPATCH_AS_IS;
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001529 entry->dispatchInProgress = true;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00001530 std::string message = std::string("Focus ") + (entry->hasFocus ? "entering " : "leaving ") +
1531 channel->getName();
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07001532 std::string reason = std::string("reason=").append(entry->reason);
1533 android_log_event_list(LOGTAG_INPUT_FOCUS) << message << reason << LOG_ID_EVENTS;
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001534 dispatchEventLocked(currentTime, entry, {target});
1535}
1536
Prabir Pradhan99987712020-11-10 18:43:05 -08001537void InputDispatcher::dispatchPointerCaptureChangedLocked(
1538 nsecs_t currentTime, const std::shared_ptr<PointerCaptureChangedEntry>& entry,
1539 DropReason& dropReason) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001540 dropReason = DropReason::NOT_DROPPED;
1541
Prabir Pradhan99987712020-11-10 18:43:05 -08001542 const bool haveWindowWithPointerCapture = mWindowTokenWithPointerCapture != nullptr;
Prabir Pradhan99987712020-11-10 18:43:05 -08001543 sp<IBinder> token;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001544
1545 if (entry->pointerCaptureRequest.enable) {
1546 // Enable Pointer Capture.
1547 if (haveWindowWithPointerCapture &&
1548 (entry->pointerCaptureRequest == mCurrentPointerCaptureRequest)) {
Prabir Pradhan7092e262022-05-03 16:51:09 +00001549 // This can happen if pointer capture is disabled and re-enabled before we notify the
1550 // app of the state change, so there is no need to notify the app.
1551 ALOGI("Skipping dispatch of Pointer Capture being enabled: no state change.");
1552 return;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001553 }
1554 if (!mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08001555 // This can happen if a window requests capture and immediately releases capture.
1556 ALOGW("No window requested Pointer Capture.");
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001557 dropReason = DropReason::NO_POINTER_CAPTURE;
Prabir Pradhan99987712020-11-10 18:43:05 -08001558 return;
1559 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001560 if (entry->pointerCaptureRequest.seq != mCurrentPointerCaptureRequest.seq) {
1561 ALOGI("Skipping dispatch of Pointer Capture being enabled: sequence number mismatch.");
1562 return;
1563 }
1564
Vishnu Nairc519ff72021-01-21 08:23:08 -08001565 token = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Prabir Pradhan99987712020-11-10 18:43:05 -08001566 LOG_ALWAYS_FATAL_IF(!token, "Cannot find focused window for Pointer Capture.");
1567 mWindowTokenWithPointerCapture = token;
1568 } else {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001569 // Disable Pointer Capture.
1570 // We do not check if the sequence number matches for requests to disable Pointer Capture
1571 // for two reasons:
1572 // 1. Pointer Capture can be disabled by a focus change, which means we can get two entries
1573 // to disable capture with the same sequence number: one generated by
1574 // disablePointerCaptureForcedLocked() and another as an acknowledgement of Pointer
1575 // Capture being disabled in InputReader.
1576 // 2. We respect any request to disable Pointer Capture generated by InputReader, since the
1577 // actual Pointer Capture state that affects events being generated by input devices is
1578 // in InputReader.
1579 if (!haveWindowWithPointerCapture) {
1580 // Pointer capture was already forcefully disabled because of focus change.
1581 dropReason = DropReason::NOT_DROPPED;
1582 return;
1583 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001584 token = mWindowTokenWithPointerCapture;
1585 mWindowTokenWithPointerCapture = nullptr;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001586 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan7d030382020-12-21 07:58:35 -08001587 setPointerCaptureLocked(false);
1588 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001589 }
1590
1591 auto channel = getInputChannelLocked(token);
1592 if (channel == nullptr) {
1593 // Window has gone away, clean up Pointer Capture state.
1594 mWindowTokenWithPointerCapture = nullptr;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001595 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan7d030382020-12-21 07:58:35 -08001596 setPointerCaptureLocked(false);
1597 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001598 return;
1599 }
1600 InputTarget target;
1601 target.inputChannel = channel;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08001602 target.flags = InputTarget::Flags::DISPATCH_AS_IS;
Prabir Pradhan99987712020-11-10 18:43:05 -08001603 entry->dispatchInProgress = true;
1604 dispatchEventLocked(currentTime, entry, {target});
1605
1606 dropReason = DropReason::NOT_DROPPED;
1607}
1608
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001609void InputDispatcher::dispatchTouchModeChangeLocked(nsecs_t currentTime,
1610 const std::shared_ptr<TouchModeEntry>& entry) {
1611 const std::vector<sp<WindowInfoHandle>>& windowHandles =
Antonio Kantek15beb512022-06-13 22:35:41 +00001612 getWindowHandlesLocked(entry->displayId);
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001613 if (windowHandles.empty()) {
1614 return;
1615 }
1616 const std::vector<InputTarget> inputTargets =
1617 getInputTargetsFromWindowHandlesLocked(windowHandles);
1618 if (inputTargets.empty()) {
1619 return;
1620 }
1621 entry->dispatchInProgress = true;
1622 dispatchEventLocked(currentTime, entry, inputTargets);
1623}
1624
1625std::vector<InputTarget> InputDispatcher::getInputTargetsFromWindowHandlesLocked(
1626 const std::vector<sp<WindowInfoHandle>>& windowHandles) const {
1627 std::vector<InputTarget> inputTargets;
1628 for (const sp<WindowInfoHandle>& handle : windowHandles) {
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001629 const sp<IBinder>& token = handle->getToken();
1630 if (token == nullptr) {
1631 continue;
1632 }
1633 std::shared_ptr<InputChannel> channel = getInputChannelLocked(token);
1634 if (channel == nullptr) {
1635 continue; // Window has gone away
1636 }
1637 InputTarget target;
1638 target.inputChannel = channel;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08001639 target.flags = InputTarget::Flags::DISPATCH_AS_IS;
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001640 inputTargets.push_back(target);
1641 }
1642 return inputTargets;
1643}
1644
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001645bool InputDispatcher::dispatchKeyLocked(nsecs_t currentTime, std::shared_ptr<KeyEntry> entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001646 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001647 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001648 if (!entry->dispatchInProgress) {
1649 if (entry->repeatCount == 0 && entry->action == AKEY_EVENT_ACTION_DOWN &&
1650 (entry->policyFlags & POLICY_FLAG_TRUSTED) &&
1651 (!(entry->policyFlags & POLICY_FLAG_DISABLE_KEY_REPEAT))) {
1652 if (mKeyRepeatState.lastKeyEntry &&
Chris Ye2ad95392020-09-01 13:44:44 -07001653 mKeyRepeatState.lastKeyEntry->keyCode == entry->keyCode &&
Michael Wrightd02c5b62014-02-10 15:10:22 -08001654 // We have seen two identical key downs in a row which indicates that the device
1655 // driver is automatically generating key repeats itself. We take note of the
1656 // repeat here, but we disable our own next key repeat timer since it is clear that
1657 // we will not need to synthesize key repeats ourselves.
Chris Ye2ad95392020-09-01 13:44:44 -07001658 mKeyRepeatState.lastKeyEntry->deviceId == entry->deviceId) {
1659 // Make sure we don't get key down from a different device. If a different
1660 // device Id has same key pressed down, the new device Id will replace the
1661 // current one to hold the key repeat with repeat count reset.
1662 // In the future when got a KEY_UP on the device id, drop it and do not
1663 // stop the key repeat on current device.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001664 entry->repeatCount = mKeyRepeatState.lastKeyEntry->repeatCount + 1;
1665 resetKeyRepeatLocked();
Colin Cross5b799302022-10-18 21:52:41 -07001666 mKeyRepeatState.nextRepeatTime = LLONG_MAX; // don't generate repeats ourselves
Michael Wrightd02c5b62014-02-10 15:10:22 -08001667 } else {
1668 // Not a repeat. Save key down state in case we do see a repeat later.
1669 resetKeyRepeatLocked();
1670 mKeyRepeatState.nextRepeatTime = entry->eventTime + mConfig.keyRepeatTimeout;
1671 }
1672 mKeyRepeatState.lastKeyEntry = entry;
Chris Ye2ad95392020-09-01 13:44:44 -07001673 } else if (entry->action == AKEY_EVENT_ACTION_UP && mKeyRepeatState.lastKeyEntry &&
1674 mKeyRepeatState.lastKeyEntry->deviceId != entry->deviceId) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001675 // The key on device 'deviceId' is still down, do not stop key repeat
Prabir Pradhan65613802023-02-22 23:36:58 +00001676 if (debugInboundEventDetails()) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001677 ALOGD("deviceId=%d got KEY_UP as stale", entry->deviceId);
1678 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001679 } else if (!entry->syntheticRepeat) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001680 resetKeyRepeatLocked();
1681 }
1682
1683 if (entry->repeatCount == 1) {
1684 entry->flags |= AKEY_EVENT_FLAG_LONG_PRESS;
1685 } else {
1686 entry->flags &= ~AKEY_EVENT_FLAG_LONG_PRESS;
1687 }
1688
1689 entry->dispatchInProgress = true;
1690
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001691 logOutboundKeyDetails("dispatchKey - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001692 }
1693
1694 // Handle case where the policy asked us to try again later last time.
Michael Wright5caf55a2022-11-24 22:31:42 +00001695 if (entry->interceptKeyResult == KeyEntry::InterceptKeyResult::TRY_AGAIN_LATER) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001696 if (currentTime < entry->interceptKeyWakeupTime) {
1697 if (entry->interceptKeyWakeupTime < *nextWakeupTime) {
1698 *nextWakeupTime = entry->interceptKeyWakeupTime;
1699 }
1700 return false; // wait until next wakeup
1701 }
Michael Wright5caf55a2022-11-24 22:31:42 +00001702 entry->interceptKeyResult = KeyEntry::InterceptKeyResult::UNKNOWN;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001703 entry->interceptKeyWakeupTime = 0;
1704 }
1705
1706 // Give the policy a chance to intercept the key.
Michael Wright5caf55a2022-11-24 22:31:42 +00001707 if (entry->interceptKeyResult == KeyEntry::InterceptKeyResult::UNKNOWN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001708 if (entry->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07001709 sp<IBinder> focusedWindowToken =
Vishnu Nairc519ff72021-01-21 08:23:08 -08001710 mFocusResolver.getFocusedWindowToken(getTargetDisplayId(*entry));
Prabir Pradhancef936d2021-07-21 16:17:52 +00001711
1712 auto command = [this, focusedWindowToken, entry]() REQUIRES(mLock) {
1713 doInterceptKeyBeforeDispatchingCommand(focusedWindowToken, *entry);
1714 };
1715 postCommandLocked(std::move(command));
Josep del Riob3981622023-04-18 15:49:45 +00001716 // Poke user activity for keys not passed to user
1717 pokeUserActivityLocked(*entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001718 return false; // wait for the command to run
1719 } else {
Michael Wright5caf55a2022-11-24 22:31:42 +00001720 entry->interceptKeyResult = KeyEntry::InterceptKeyResult::CONTINUE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001721 }
Michael Wright5caf55a2022-11-24 22:31:42 +00001722 } else if (entry->interceptKeyResult == KeyEntry::InterceptKeyResult::SKIP) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001723 if (*dropReason == DropReason::NOT_DROPPED) {
1724 *dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001725 }
1726 }
1727
1728 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001729 if (*dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001730 setInjectionResult(*entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001731 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
1732 : InputEventInjectionResult::FAILED);
Garfield Tan6a5a14e2020-01-28 13:24:04 -08001733 mReporter->reportDroppedKey(entry->id);
Josep del Riob3981622023-04-18 15:49:45 +00001734 // Poke user activity for undispatched keys
1735 pokeUserActivityLocked(*entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001736 return true;
1737 }
1738
1739 // Identify targets.
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001740 InputEventInjectionResult injectionResult;
1741 sp<WindowInfoHandle> focusedWindow =
1742 findFocusedWindowTargetLocked(currentTime, *entry, nextWakeupTime,
1743 /*byref*/ injectionResult);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001744 if (injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001745 return false;
1746 }
1747
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001748 setInjectionResult(*entry, injectionResult);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001749 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001750 return true;
1751 }
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001752 LOG_ALWAYS_FATAL_IF(focusedWindow == nullptr);
1753
1754 std::vector<InputTarget> inputTargets;
1755 addWindowTargetLocked(focusedWindow,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08001756 InputTarget::Flags::FOREGROUND | InputTarget::Flags::DISPATCH_AS_IS,
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08001757 /*pointerIds=*/{}, getDownTime(*entry), inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001758
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001759 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001760 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001761
1762 // Dispatch the key.
1763 dispatchEventLocked(currentTime, entry, inputTargets);
1764 return true;
1765}
1766
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001767void InputDispatcher::logOutboundKeyDetails(const char* prefix, const KeyEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001768 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1769 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32 ", "
1770 "policyFlags=0x%x, action=0x%x, flags=0x%x, keyCode=0x%x, scanCode=0x%x, "
1771 "metaState=0x%x, repeatCount=%d, downTime=%" PRId64,
1772 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId,
1773 entry.policyFlags, entry.action, entry.flags, entry.keyCode, entry.scanCode,
1774 entry.metaState, entry.repeatCount, entry.downTime);
1775 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001776}
1777
Prabir Pradhancef936d2021-07-21 16:17:52 +00001778void InputDispatcher::dispatchSensorLocked(nsecs_t currentTime,
1779 const std::shared_ptr<SensorEntry>& entry,
Chris Yef59a2f42020-10-16 12:55:26 -07001780 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001781 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1782 ALOGD("notifySensorEvent eventTime=%" PRId64 ", hwTimestamp=%" PRId64 ", deviceId=%d, "
1783 "source=0x%x, sensorType=%s",
1784 entry->eventTime, entry->hwTimestamp, entry->deviceId, entry->source,
Dominik Laskowski75788452021-02-09 18:51:25 -08001785 ftl::enum_string(entry->sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001786 }
Prabir Pradhancef936d2021-07-21 16:17:52 +00001787 auto command = [this, entry]() REQUIRES(mLock) {
1788 scoped_unlock unlock(mLock);
1789
1790 if (entry->accuracyChanged) {
Prabir Pradhana41d2442023-04-20 21:30:40 +00001791 mPolicy.notifySensorAccuracy(entry->deviceId, entry->sensorType, entry->accuracy);
Prabir Pradhancef936d2021-07-21 16:17:52 +00001792 }
Prabir Pradhana41d2442023-04-20 21:30:40 +00001793 mPolicy.notifySensorEvent(entry->deviceId, entry->sensorType, entry->accuracy,
1794 entry->hwTimestamp, entry->values);
Prabir Pradhancef936d2021-07-21 16:17:52 +00001795 };
1796 postCommandLocked(std::move(command));
Chris Yef59a2f42020-10-16 12:55:26 -07001797}
1798
1799bool InputDispatcher::flushSensor(int deviceId, InputDeviceSensorType sensorType) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001800 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1801 ALOGD("flushSensor deviceId=%d, sensorType=%s", deviceId,
Dominik Laskowski75788452021-02-09 18:51:25 -08001802 ftl::enum_string(sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001803 }
Chris Yef59a2f42020-10-16 12:55:26 -07001804 { // acquire lock
1805 std::scoped_lock _l(mLock);
1806
1807 for (auto it = mInboundQueue.begin(); it != mInboundQueue.end(); it++) {
1808 std::shared_ptr<EventEntry> entry = *it;
1809 if (entry->type == EventEntry::Type::SENSOR) {
1810 it = mInboundQueue.erase(it);
1811 releaseInboundEventLocked(entry);
1812 }
1813 }
1814 }
1815 return true;
1816}
1817
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001818bool InputDispatcher::dispatchMotionLocked(nsecs_t currentTime, std::shared_ptr<MotionEntry> entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001819 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001820 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001821 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001822 if (!entry->dispatchInProgress) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001823 entry->dispatchInProgress = true;
1824
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001825 logOutboundMotionDetails("dispatchMotion - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001826 }
1827
1828 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001829 if (*dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001830 setInjectionResult(*entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001831 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
1832 : InputEventInjectionResult::FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001833 return true;
1834 }
1835
Prabir Pradhanaa561d12021-09-24 06:57:33 -07001836 const bool isPointerEvent = isFromSource(entry->source, AINPUT_SOURCE_CLASS_POINTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001837
1838 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001839 std::vector<InputTarget> inputTargets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001840
1841 bool conflictingPointerActions = false;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001842 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001843 if (isPointerEvent) {
1844 // Pointer event. (eg. touchscreen)
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00001845
1846 if (mDragState &&
1847 (entry->action & AMOTION_EVENT_ACTION_MASK) == AMOTION_EVENT_ACTION_POINTER_DOWN) {
1848 // If drag and drop ongoing and pointer down occur: pilfer drag window pointers
1849 pilferPointersLocked(mDragState->dragWindow->getToken());
1850 }
1851
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08001852 inputTargets =
Siarhei Vishniakou4fe57392022-10-25 13:44:30 -07001853 findTouchedWindowTargetsLocked(currentTime, *entry, &conflictingPointerActions,
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001854 /*byref*/ injectionResult);
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08001855 LOG_ALWAYS_FATAL_IF(injectionResult != InputEventInjectionResult::SUCCEEDED &&
1856 !inputTargets.empty());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001857 } else {
1858 // Non touch event. (eg. trackball)
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001859 sp<WindowInfoHandle> focusedWindow =
1860 findFocusedWindowTargetLocked(currentTime, *entry, nextWakeupTime, injectionResult);
1861 if (injectionResult == InputEventInjectionResult::SUCCEEDED) {
1862 LOG_ALWAYS_FATAL_IF(focusedWindow == nullptr);
1863 addWindowTargetLocked(focusedWindow,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08001864 InputTarget::Flags::FOREGROUND |
1865 InputTarget::Flags::DISPATCH_AS_IS,
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08001866 /*pointerIds=*/{}, getDownTime(*entry), inputTargets);
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001867 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001868 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001869 if (injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001870 return false;
1871 }
1872
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001873 setInjectionResult(*entry, injectionResult);
Prabir Pradhan5735a322022-04-11 17:23:34 +00001874 if (injectionResult == InputEventInjectionResult::TARGET_MISMATCH) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001875 return true;
1876 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001877 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001878 CancelationOptions::Mode mode(
1879 isPointerEvent ? CancelationOptions::Mode::CANCEL_POINTER_EVENTS
1880 : CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS);
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001881 CancelationOptions options(mode, "input event injection failed");
1882 synthesizeCancelationEventsForMonitorsLocked(options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001883 return true;
1884 }
1885
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001886 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001887 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001888
1889 // Dispatch the motion.
1890 if (conflictingPointerActions) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001891 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001892 "conflicting pointer actions");
Michael Wrightd02c5b62014-02-10 15:10:22 -08001893 synthesizeCancelationEventsForAllConnectionsLocked(options);
1894 }
1895 dispatchEventLocked(currentTime, entry, inputTargets);
1896 return true;
1897}
1898
chaviw98318de2021-05-19 16:45:23 -05001899void InputDispatcher::enqueueDragEventLocked(const sp<WindowInfoHandle>& windowHandle,
Arthur Hung54745652022-04-20 07:17:41 +00001900 bool isExiting, const int32_t rawX,
1901 const int32_t rawY) {
1902 const vec2 xy = windowHandle->getInfo()->transform.transform(vec2(rawX, rawY));
arthurhungb89ccb02020-12-30 16:19:01 +08001903 std::unique_ptr<DragEntry> dragEntry =
Arthur Hung54745652022-04-20 07:17:41 +00001904 std::make_unique<DragEntry>(mIdGenerator.nextId(), now(), windowHandle->getToken(),
1905 isExiting, xy.x, xy.y);
arthurhungb89ccb02020-12-30 16:19:01 +08001906
1907 enqueueInboundEventLocked(std::move(dragEntry));
1908}
1909
1910void InputDispatcher::dispatchDragLocked(nsecs_t currentTime, std::shared_ptr<DragEntry> entry) {
1911 std::shared_ptr<InputChannel> channel = getInputChannelLocked(entry->connectionToken);
1912 if (channel == nullptr) {
1913 return; // Window has gone away
1914 }
1915 InputTarget target;
1916 target.inputChannel = channel;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08001917 target.flags = InputTarget::Flags::DISPATCH_AS_IS;
arthurhungb89ccb02020-12-30 16:19:01 +08001918 entry->dispatchInProgress = true;
1919 dispatchEventLocked(currentTime, entry, {target});
1920}
1921
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001922void InputDispatcher::logOutboundMotionDetails(const char* prefix, const MotionEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001923 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -08001924 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=%s, displayId=%" PRId32
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001925 ", policyFlags=0x%x, "
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001926 "action=%s, actionButton=0x%x, flags=0x%x, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001927 "metaState=0x%x, buttonState=0x%x,"
1928 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%" PRId64,
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -08001929 prefix, entry.eventTime, entry.deviceId,
1930 inputEventSourceToString(entry.source).c_str(), entry.displayId, entry.policyFlags,
1931 MotionEvent::actionToString(entry.action).c_str(), entry.actionButton, entry.flags,
1932 entry.metaState, entry.buttonState, entry.edgeFlags, entry.xPrecision,
1933 entry.yPrecision, entry.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001934
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001935 for (uint32_t i = 0; i < entry.pointerCount; i++) {
Siarhei Vishniakou09a8fe42022-07-21 17:27:03 -07001936 ALOGD(" Pointer %d: id=%d, toolType=%s, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001937 "x=%f, y=%f, pressure=%f, size=%f, "
1938 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
1939 "orientation=%f",
Siarhei Vishniakou09a8fe42022-07-21 17:27:03 -07001940 i, entry.pointerProperties[i].id,
1941 ftl::enum_string(entry.pointerProperties[i].toolType).c_str(),
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001942 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
1943 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
1944 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
1945 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
1946 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
1947 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
1948 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
1949 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
1950 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
1951 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001952 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001953}
1954
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001955void InputDispatcher::dispatchEventLocked(nsecs_t currentTime,
1956 std::shared_ptr<EventEntry> eventEntry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001957 const std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001958 ATRACE_CALL();
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001959 if (DEBUG_DISPATCH_CYCLE) {
1960 ALOGD("dispatchEventToCurrentInputTargets");
1961 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001962
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00001963 processInteractionsLocked(*eventEntry, inputTargets);
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00001964
Michael Wrightd02c5b62014-02-10 15:10:22 -08001965 ALOG_ASSERT(eventEntry->dispatchInProgress); // should already have been set to true
1966
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001967 pokeUserActivityLocked(*eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001968
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001969 for (const InputTarget& inputTarget : inputTargets) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07001970 std::shared_ptr<Connection> connection =
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07001971 getConnectionLocked(inputTarget.inputChannel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07001972 if (connection != nullptr) {
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08001973 prepareDispatchCycleLocked(currentTime, connection, eventEntry, inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001974 } else {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001975 if (DEBUG_FOCUS) {
1976 ALOGD("Dropping event delivery to target with channel '%s' because it "
1977 "is no longer registered with the input dispatcher.",
1978 inputTarget.inputChannel->getName().c_str());
1979 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001980 }
1981 }
1982}
1983
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07001984void InputDispatcher::cancelEventsForAnrLocked(const std::shared_ptr<Connection>& connection) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001985 // We will not be breaking any connections here, even if the policy wants us to abort dispatch.
1986 // If the policy decides to close the app, we will get a channel removal event via
1987 // unregisterInputChannel, and will clean up the connection that way. We are already not
1988 // sending new pointers to the connection when it blocked, but focused events will continue to
1989 // pile up.
1990 ALOGW("Canceling events for %s because it is unresponsive",
1991 connection->inputChannel->getName().c_str());
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08001992 if (connection->status == Connection::Status::NORMAL) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001993 CancelationOptions options(CancelationOptions::Mode::CANCEL_ALL_EVENTS,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001994 "application not responding");
1995 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001996 }
1997}
1998
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001999void InputDispatcher::resetNoFocusedWindowTimeoutLocked() {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002000 if (DEBUG_FOCUS) {
2001 ALOGD("Resetting ANR timeouts.");
2002 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002003
2004 // Reset input target wait timeout.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002005 mNoFocusedWindowTimeoutTime = std::nullopt;
Chris Yea209fde2020-07-22 13:54:51 -07002006 mAwaitedFocusedApplication.reset();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002007}
2008
Tiger Huang721e26f2018-07-24 22:26:19 +08002009/**
2010 * Get the display id that the given event should go to. If this event specifies a valid display id,
2011 * then it should be dispatched to that display. Otherwise, the event goes to the focused display.
2012 * Focused display is the display that the user most recently interacted with.
2013 */
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002014int32_t InputDispatcher::getTargetDisplayId(const EventEntry& entry) {
Tiger Huang721e26f2018-07-24 22:26:19 +08002015 int32_t displayId;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002016 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002017 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002018 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
2019 displayId = keyEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002020 break;
2021 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002022 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002023 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
2024 displayId = motionEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002025 break;
2026 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00002027 case EventEntry::Type::TOUCH_MODE_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08002028 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002029 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002030 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07002031 case EventEntry::Type::DEVICE_RESET:
arthurhungb89ccb02020-12-30 16:19:01 +08002032 case EventEntry::Type::SENSOR:
2033 case EventEntry::Type::DRAG: {
Dominik Laskowski75788452021-02-09 18:51:25 -08002034 ALOGE("%s events do not have a target display", ftl::enum_string(entry.type).c_str());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002035 return ADISPLAY_ID_NONE;
2036 }
Tiger Huang721e26f2018-07-24 22:26:19 +08002037 }
2038 return displayId == ADISPLAY_ID_NONE ? mFocusedDisplayId : displayId;
2039}
2040
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002041bool InputDispatcher::shouldWaitToSendKeyLocked(nsecs_t currentTime,
2042 const char* focusedWindowName) {
2043 if (mAnrTracker.empty()) {
2044 // already processed all events that we waited for
2045 mKeyIsWaitingForEventsTimeout = std::nullopt;
2046 return false;
2047 }
2048
2049 if (!mKeyIsWaitingForEventsTimeout.has_value()) {
2050 // Start the timer
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00002051 // Wait to send key because there are unprocessed events that may cause focus to change
Siarhei Vishniakou70622952020-07-30 11:17:23 -05002052 mKeyIsWaitingForEventsTimeout = currentTime +
2053 std::chrono::duration_cast<std::chrono::nanoseconds>(KEY_WAITING_FOR_EVENTS_TIMEOUT)
2054 .count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002055 return true;
2056 }
2057
2058 // We still have pending events, and already started the timer
2059 if (currentTime < *mKeyIsWaitingForEventsTimeout) {
2060 return true; // Still waiting
2061 }
2062
2063 // Waited too long, and some connection still hasn't processed all motions
2064 // Just send the key to the focused window
2065 ALOGW("Dispatching key to %s even though there are other unprocessed events",
2066 focusedWindowName);
2067 mKeyIsWaitingForEventsTimeout = std::nullopt;
2068 return false;
2069}
2070
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002071sp<WindowInfoHandle> InputDispatcher::findFocusedWindowTargetLocked(
2072 nsecs_t currentTime, const EventEntry& entry, nsecs_t* nextWakeupTime,
2073 InputEventInjectionResult& outInjectionResult) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002074 std::string reason;
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002075 outInjectionResult = InputEventInjectionResult::FAILED; // Default result
Michael Wrightd02c5b62014-02-10 15:10:22 -08002076
Tiger Huang721e26f2018-07-24 22:26:19 +08002077 int32_t displayId = getTargetDisplayId(entry);
chaviw98318de2021-05-19 16:45:23 -05002078 sp<WindowInfoHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Chris Yea209fde2020-07-22 13:54:51 -07002079 std::shared_ptr<InputApplicationHandle> focusedApplicationHandle =
Tiger Huang721e26f2018-07-24 22:26:19 +08002080 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
2081
Michael Wrightd02c5b62014-02-10 15:10:22 -08002082 // If there is no currently focused window and no focused application
2083 // then drop the event.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002084 if (focusedWindowHandle == nullptr && focusedApplicationHandle == nullptr) {
2085 ALOGI("Dropping %s event because there is no focused window or focused application in "
2086 "display %" PRId32 ".",
Dominik Laskowski75788452021-02-09 18:51:25 -08002087 ftl::enum_string(entry.type).c_str(), displayId);
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002088 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002089 }
2090
Vishnu Nair062a8672021-09-03 16:07:44 -07002091 // Drop key events if requested by input feature
2092 if (focusedWindowHandle != nullptr && shouldDropInput(entry, focusedWindowHandle)) {
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002093 return nullptr;
Vishnu Nair062a8672021-09-03 16:07:44 -07002094 }
2095
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002096 // Compatibility behavior: raise ANR if there is a focused application, but no focused window.
2097 // Only start counting when we have a focused event to dispatch. The ANR is canceled if we
2098 // start interacting with another application via touch (app switch). This code can be removed
2099 // if the "no focused window ANR" is moved to the policy. Input doesn't know whether
2100 // an app is expected to have a focused window.
2101 if (focusedWindowHandle == nullptr && focusedApplicationHandle != nullptr) {
2102 if (!mNoFocusedWindowTimeoutTime.has_value()) {
2103 // We just discovered that there's no focused window. Start the ANR timer
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05002104 std::chrono::nanoseconds timeout = focusedApplicationHandle->getDispatchingTimeout(
2105 DEFAULT_INPUT_DISPATCHING_TIMEOUT);
2106 mNoFocusedWindowTimeoutTime = currentTime + timeout.count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002107 mAwaitedFocusedApplication = focusedApplicationHandle;
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05002108 mAwaitedApplicationDisplayId = displayId;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002109 ALOGW("Waiting because no window has focus but %s may eventually add a "
2110 "window when it finishes starting up. Will wait for %" PRId64 "ms",
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05002111 mAwaitedFocusedApplication->getName().c_str(), millis(timeout));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002112 *nextWakeupTime = *mNoFocusedWindowTimeoutTime;
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002113 outInjectionResult = InputEventInjectionResult::PENDING;
2114 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002115 } else if (currentTime > *mNoFocusedWindowTimeoutTime) {
2116 // Already raised ANR. Drop the event
2117 ALOGE("Dropping %s event because there is no focused window",
Dominik Laskowski75788452021-02-09 18:51:25 -08002118 ftl::enum_string(entry.type).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002119 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002120 } else {
2121 // Still waiting for the focused window
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002122 outInjectionResult = InputEventInjectionResult::PENDING;
2123 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002124 }
2125 }
2126
2127 // we have a valid, non-null focused window
2128 resetNoFocusedWindowTimeoutLocked();
2129
Prabir Pradhan5735a322022-04-11 17:23:34 +00002130 // Verify targeted injection.
2131 if (const auto err = verifyTargetedInjection(focusedWindowHandle, entry); err) {
2132 ALOGW("Dropping injected event: %s", (*err).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002133 outInjectionResult = InputEventInjectionResult::TARGET_MISMATCH;
2134 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002135 }
2136
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002137 if (focusedWindowHandle->getInfo()->inputConfig.test(
2138 WindowInfo::InputConfig::PAUSE_DISPATCHING)) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002139 ALOGI("Waiting because %s is paused", focusedWindowHandle->getName().c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002140 outInjectionResult = InputEventInjectionResult::PENDING;
2141 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002142 }
2143
2144 // If the event is a key event, then we must wait for all previous events to
2145 // complete before delivering it because previous events may have the
2146 // side-effect of transferring focus to a different window and we want to
2147 // ensure that the following keys are sent to the new window.
2148 //
2149 // Suppose the user touches a button in a window then immediately presses "A".
2150 // If the button causes a pop-up window to appear then we want to ensure that
2151 // the "A" key is delivered to the new pop-up window. This is because users
2152 // often anticipate pending UI changes when typing on a keyboard.
2153 // To obtain this behavior, we must serialize key events with respect to all
2154 // prior input events.
2155 if (entry.type == EventEntry::Type::KEY) {
2156 if (shouldWaitToSendKeyLocked(currentTime, focusedWindowHandle->getName().c_str())) {
2157 *nextWakeupTime = *mKeyIsWaitingForEventsTimeout;
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002158 outInjectionResult = InputEventInjectionResult::PENDING;
2159 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002160 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002161 }
2162
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002163 outInjectionResult = InputEventInjectionResult::SUCCEEDED;
2164 return focusedWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002165}
2166
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002167/**
2168 * Given a list of monitors, remove the ones we cannot find a connection for, and the ones
2169 * that are currently unresponsive.
2170 */
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002171std::vector<Monitor> InputDispatcher::selectResponsiveMonitorsLocked(
2172 const std::vector<Monitor>& monitors) const {
2173 std::vector<Monitor> responsiveMonitors;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002174 std::copy_if(monitors.begin(), monitors.end(), std::back_inserter(responsiveMonitors),
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002175 [this](const Monitor& monitor) REQUIRES(mLock) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07002176 std::shared_ptr<Connection> connection =
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002177 getConnectionLocked(monitor.inputChannel->getConnectionToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002178 if (connection == nullptr) {
2179 ALOGE("Could not find connection for monitor %s",
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002180 monitor.inputChannel->getName().c_str());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002181 return false;
2182 }
2183 if (!connection->responsive) {
2184 ALOGW("Unresponsive monitor %s will not get the new gesture",
2185 connection->inputChannel->getName().c_str());
2186 return false;
2187 }
2188 return true;
2189 });
2190 return responsiveMonitors;
2191}
2192
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07002193/**
2194 * In general, touch should be always split between windows. Some exceptions:
2195 * 1. Don't split touch is if we have an active pointer down, and a new pointer is going down that's
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002196 * from the same device, *and* the window that's receiving the current pointer does not support
2197 * split touch.
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07002198 * 2. Don't split mouse events
2199 */
2200bool InputDispatcher::shouldSplitTouch(const TouchState& touchState,
2201 const MotionEntry& entry) const {
2202 if (isFromSource(entry.source, AINPUT_SOURCE_MOUSE)) {
2203 // We should never split mouse events
2204 return false;
2205 }
2206 for (const TouchedWindow& touchedWindow : touchState.windows) {
2207 if (touchedWindow.windowHandle->getInfo()->isSpy()) {
2208 // Spy windows should not affect whether or not touch is split.
2209 continue;
2210 }
2211 if (touchedWindow.windowHandle->getInfo()->supportsSplitTouch()) {
2212 continue;
2213 }
Arthur Hungc539dbb2022-12-08 07:45:36 +00002214 if (touchedWindow.windowHandle->getInfo()->inputConfig.test(
2215 gui::WindowInfo::InputConfig::IS_WALLPAPER)) {
2216 // Wallpaper window should not affect whether or not touch is split
2217 continue;
2218 }
2219
Siarhei Vishniakou45504fe2023-05-05 16:05:10 -07002220 if (touchedWindow.hasTouchingPointers(entry.deviceId)) {
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07002221 return false;
2222 }
2223 }
2224 return true;
2225}
2226
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002227std::vector<InputTarget> InputDispatcher::findTouchedWindowTargetsLocked(
Siarhei Vishniakou4fe57392022-10-25 13:44:30 -07002228 nsecs_t currentTime, const MotionEntry& entry, bool* outConflictingPointerActions,
2229 InputEventInjectionResult& outInjectionResult) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002230 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002231
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002232 std::vector<InputTarget> targets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002233 // For security reasons, we defer updating the touch state until we are sure that
2234 // event injection will be allowed.
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002235 const int32_t displayId = entry.displayId;
2236 const int32_t action = entry.action;
Siarhei Vishniakoubf880522023-05-01 11:03:22 -07002237 const int32_t maskedAction = MotionEvent::getActionMasked(action);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002238
2239 // Update the touch state as needed based on the properties of the touch event.
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002240 outInjectionResult = InputEventInjectionResult::PENDING;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002241
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002242 // Copy current touch state into tempTouchState.
2243 // This state will be used to update mTouchStatesByDisplay at the end of this function.
2244 // If no state for the specified display exists, then our initial state will be empty.
Yi Kong9b14ac62018-07-17 13:48:38 -07002245 const TouchState* oldState = nullptr;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002246 TouchState tempTouchState;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002247 if (const auto it = mTouchStatesByDisplay.find(displayId); it != mTouchStatesByDisplay.end()) {
2248 oldState = &(it->second);
Prabir Pradhane680f9b2022-02-04 04:24:00 -08002249 tempTouchState = *oldState;
Jeff Brownf086ddb2014-02-11 14:28:48 -08002250 }
2251
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07002252 bool isSplit = shouldSplitTouch(tempTouchState, entry);
Siarhei Vishniakou45504fe2023-05-05 16:05:10 -07002253 bool switchedDevice = false;
2254 if (oldState != nullptr) {
2255 std::set<int32_t> oldActiveDevices = oldState->getActiveDeviceIds();
2256 const bool anotherDeviceIsActive =
2257 oldActiveDevices.count(entry.deviceId) == 0 && !oldActiveDevices.empty();
2258 switchedDevice |= anotherDeviceIsActive;
Siarhei Vishniakou45504fe2023-05-05 16:05:10 -07002259 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002260
2261 const bool isHoverAction = (maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE ||
2262 maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2263 maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT);
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002264 // A DOWN could be generated from POINTER_DOWN if the initial pointers did not land into any
2265 // touchable windows.
2266 const bool wasDown = oldState != nullptr && oldState->isDown();
2267 const bool isDown = (maskedAction == AMOTION_EVENT_ACTION_DOWN) ||
2268 (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN && !wasDown);
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07002269 const bool newGesture = isDown || maskedAction == AMOTION_EVENT_ACTION_SCROLL ||
2270 maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2271 maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE;
Prabir Pradhanaa561d12021-09-24 06:57:33 -07002272 const bool isFromMouse = isFromSource(entry.source, AINPUT_SOURCE_MOUSE);
Siarhei Vishniakou5cee1e32022-11-29 12:35:39 -08002273
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002274 // If pointers are already down, let's finish the current gesture and ignore the new events
2275 // from another device. However, if the new event is a down event, let's cancel the current
2276 // touch and let the new one take over.
2277 if (switchedDevice && wasDown && !isDown) {
Siarhei Vishniakou45504fe2023-05-05 16:05:10 -07002278 LOG(INFO) << "Dropping event because a pointer for another device "
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002279 << " is already down in display " << displayId << ": " << entry.getDescription();
2280 // TODO(b/211379801): test multiple simultaneous input streams.
2281 outInjectionResult = InputEventInjectionResult::FAILED;
2282 return {}; // wrong device
2283 }
2284
Michael Wrightd02c5b62014-02-10 15:10:22 -08002285 if (newGesture) {
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002286 // If a new gesture is starting, clear the touch state completely.
2287 tempTouchState.reset();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002288 isSplit = false;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04002289 } else if (switchedDevice && maskedAction == AMOTION_EVENT_ACTION_MOVE) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07002290 ALOGI("Dropping move event because a pointer for a different device is already active "
2291 "in display %" PRId32,
2292 displayId);
Siarhei Vishniakou16e4fa02023-02-16 17:48:56 -08002293 // TODO(b/211379801): test multiple simultaneous input streams.
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002294 outInjectionResult = InputEventInjectionResult::FAILED;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002295 return {}; // wrong device
Michael Wrightd02c5b62014-02-10 15:10:22 -08002296 }
2297
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002298 if (isHoverAction) {
2299 // For hover actions, we will treat 'tempTouchState' as a new state, so let's erase
2300 // all of the existing hovering pointers and recompute.
2301 tempTouchState.clearHoveringPointers();
2302 }
2303
Michael Wrightd02c5b62014-02-10 15:10:22 -08002304 if (newGesture || (isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN)) {
2305 /* Case 1: New splittable pointer going down, or need target for hover or scroll. */
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07002306 const auto [x, y] = resolveTouchedPosition(entry);
Siarhei Vishniakou5b9766d2023-07-18 14:06:29 -07002307 const int32_t pointerIndex = MotionEvent::getActionIndex(action);
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002308 // Outside targets should be added upon first dispatched DOWN event. That means, this should
2309 // be a pointer that would generate ACTION_DOWN, *and* touch should not already be down.
Prabir Pradhand65552b2021-10-07 11:23:50 -07002310 const bool isStylus = isPointerFromStylus(entry, pointerIndex);
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002311 auto [newTouchedWindowHandle, outsideTargets] =
2312 findTouchedWindowAtLocked(displayId, x, y, isStylus);
Michael Wright3dd60e22019-03-27 22:06:44 +00002313
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002314 if (isDown) {
2315 targets += outsideTargets;
2316 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002317 // Handle the case where we did not find a window.
Yi Kong9b14ac62018-07-17 13:48:38 -07002318 if (newTouchedWindowHandle == nullptr) {
Prabir Pradhan82e081e2022-12-06 09:50:09 +00002319 ALOGD("No new touched window at (%.1f, %.1f) in display %" PRId32, x, y, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002320 // Try to assign the pointer to the first foreground window we find, if there is one.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002321 newTouchedWindowHandle = tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002322 }
2323
Prabir Pradhan5735a322022-04-11 17:23:34 +00002324 // Verify targeted injection.
2325 if (const auto err = verifyTargetedInjection(newTouchedWindowHandle, entry); err) {
2326 ALOGW("Dropping injected touch event: %s", (*err).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002327 outInjectionResult = os::InputEventInjectionResult::TARGET_MISMATCH;
Prabir Pradhan5735a322022-04-11 17:23:34 +00002328 newTouchedWindowHandle = nullptr;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002329 return {};
Prabir Pradhan5735a322022-04-11 17:23:34 +00002330 }
2331
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002332 // Figure out whether splitting will be allowed for this window.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002333 if (newTouchedWindowHandle != nullptr) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002334 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
2335 // New window supports splitting, but we should never split mouse events.
2336 isSplit = !isFromMouse;
2337 } else if (isSplit) {
2338 // New window does not support splitting but we have already split events.
2339 // Ignore the new window.
Siarhei Vishniakou25537f82023-07-18 14:35:47 -07002340 LOG(INFO) << "Skipping " << newTouchedWindowHandle->getName()
2341 << " because it doesn't support split touch";
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002342 newTouchedWindowHandle = nullptr;
2343 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002344 } else {
2345 // No window is touched, so set split to true. This will allow the next pointer down to
Prabir Pradhan713bb3e2021-12-20 02:07:40 -08002346 // be delivered to a new window which supports split touch. Pointers from a mouse device
2347 // should never be split.
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07002348 isSplit = !isFromMouse;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002349 }
2350
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002351 std::vector<sp<WindowInfoHandle>> newTouchedWindows =
Prabir Pradhand65552b2021-10-07 11:23:50 -07002352 findTouchedSpyWindowsAtLocked(displayId, x, y, isStylus);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002353 if (newTouchedWindowHandle != nullptr) {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002354 // Process the foreground window first so that it is the first to receive the event.
2355 newTouchedWindows.insert(newTouchedWindows.begin(), newTouchedWindowHandle);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002356 }
2357
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002358 if (newTouchedWindows.empty()) {
Prabir Pradhan82e081e2022-12-06 09:50:09 +00002359 ALOGI("Dropping event because there is no touchable window at (%.1f, %.1f) on display "
2360 "%d.",
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002361 x, y, displayId);
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002362 outInjectionResult = InputEventInjectionResult::FAILED;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002363 return {};
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002364 }
2365
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002366 for (const sp<WindowInfoHandle>& windowHandle : newTouchedWindows) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07002367 if (!canWindowReceiveMotionLocked(windowHandle, entry)) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002368 continue;
2369 }
2370
Siarhei Vishniakoub681c202023-05-01 11:22:33 -07002371 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2372 maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE) {
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002373 const int32_t pointerId = entry.pointerProperties[0].id;
Siarhei Vishniakoub681c202023-05-01 11:22:33 -07002374 // The "windowHandle" is the target of this hovering pointer.
2375 tempTouchState.addHoveringPointerToWindow(windowHandle, entry.deviceId, pointerId);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002376 }
2377
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002378 // Set target flags.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002379 ftl::Flags<InputTarget::Flags> targetFlags = InputTarget::Flags::DISPATCH_AS_IS;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002380
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002381 if (canReceiveForegroundTouches(*windowHandle->getInfo())) {
2382 // There should only be one touched window that can be "foreground" for the pointer.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002383 targetFlags |= InputTarget::Flags::FOREGROUND;
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002384 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002385
2386 if (isSplit) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002387 targetFlags |= InputTarget::Flags::SPLIT;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002388 }
2389 if (isWindowObscuredAtPointLocked(windowHandle, x, y)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002390 targetFlags |= InputTarget::Flags::WINDOW_IS_OBSCURED;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002391 } else if (isWindowObscuredLocked(windowHandle)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002392 targetFlags |= InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002393 }
Michael Wright3dd60e22019-03-27 22:06:44 +00002394
2395 // Update the temporary touch state.
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08002396 std::bitset<MAX_POINTER_ID + 1> pointerIds;
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002397 if (!isHoverAction) {
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08002398 pointerIds.set(entry.pointerProperties[pointerIndex].id);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002399 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002400
Siarhei Vishniakoue0431e42023-01-28 17:01:39 -08002401 const bool isDownOrPointerDown = maskedAction == AMOTION_EVENT_ACTION_DOWN ||
2402 maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN;
2403
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002404 // TODO(b/211379801): Currently, even if pointerIds are empty (hover case), we would
2405 // still add a window to the touch state. We should avoid doing that, but some of the
2406 // later checks ("at least one foreground window") rely on this in order to dispatch
2407 // the event properly, so that needs to be updated, possibly by looking at InputTargets.
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002408 tempTouchState.addOrUpdateWindow(windowHandle, targetFlags, entry.deviceId, pointerIds,
Siarhei Vishniakoue0431e42023-01-28 17:01:39 -08002409 isDownOrPointerDown
2410 ? std::make_optional(entry.eventTime)
2411 : std::nullopt);
Arthur Hungc539dbb2022-12-08 07:45:36 +00002412
2413 // If this is the pointer going down and the touched window has a wallpaper
2414 // then also add the touched wallpaper windows so they are locked in for the duration
2415 // of the touch gesture.
2416 // We do not collect wallpapers during HOVER_MOVE or SCROLL because the wallpaper
2417 // engine only supports touch events. We would need to add a mechanism similar
2418 // to View.onGenericMotionEvent to enable wallpapers to handle these events.
Siarhei Vishniakoue0431e42023-01-28 17:01:39 -08002419 if (isDownOrPointerDown) {
Arthur Hungc539dbb2022-12-08 07:45:36 +00002420 if (targetFlags.test(InputTarget::Flags::FOREGROUND) &&
2421 windowHandle->getInfo()->inputConfig.test(
2422 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER)) {
2423 sp<WindowInfoHandle> wallpaper = findWallpaperWindowBelow(windowHandle);
2424 if (wallpaper != nullptr) {
2425 ftl::Flags<InputTarget::Flags> wallpaperFlags =
2426 InputTarget::Flags::WINDOW_IS_OBSCURED |
2427 InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED |
2428 InputTarget::Flags::DISPATCH_AS_IS;
2429 if (isSplit) {
2430 wallpaperFlags |= InputTarget::Flags::SPLIT;
2431 }
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002432 tempTouchState.addOrUpdateWindow(wallpaper, wallpaperFlags, entry.deviceId,
2433 pointerIds, entry.eventTime);
Arthur Hungc539dbb2022-12-08 07:45:36 +00002434 }
2435 }
2436 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002437 }
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00002438
Siarhei Vishniakou060f82b2023-01-27 06:39:14 -08002439 // If a window is already pilfering some pointers, give it this new pointer as well and
2440 // make it pilfering. This will prevent other non-spy windows from getting this pointer,
2441 // which is a specific behaviour that we want.
2442 const int32_t pointerId = entry.pointerProperties[pointerIndex].id;
2443 for (TouchedWindow& touchedWindow : tempTouchState.windows) {
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002444 if (touchedWindow.hasTouchingPointer(entry.deviceId, pointerId) &&
2445 touchedWindow.hasPilferingPointers(entry.deviceId)) {
Siarhei Vishniakou060f82b2023-01-27 06:39:14 -08002446 // This window is already pilfering some pointers, and this new pointer is also
2447 // going to it. Therefore, take over this pointer and don't give it to anyone
2448 // else.
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002449 touchedWindow.addPilferingPointer(entry.deviceId, pointerId);
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00002450 }
2451 }
Siarhei Vishniakou060f82b2023-01-27 06:39:14 -08002452
2453 // Restrict all pilfered pointers to the pilfering windows.
2454 tempTouchState.cancelPointersForNonPilferingWindows();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002455 } else {
2456 /* Case 2: Pointer move, up, cancel or non-splittable pointer down. */
2457
2458 // If the pointer is not currently down, then ignore the event.
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07002459 if (!tempTouchState.isDown() && maskedAction != AMOTION_EVENT_ACTION_HOVER_EXIT) {
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002460 LOG(INFO) << "Dropping event because the pointer is not down or we previously "
2461 "dropped the pointer down event in display "
2462 << displayId << ": " << entry.getDescription();
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002463 outInjectionResult = InputEventInjectionResult::FAILED;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002464 return {};
Michael Wrightd02c5b62014-02-10 15:10:22 -08002465 }
2466
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07002467 // If the pointer is not currently hovering, then ignore the event.
2468 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT) {
2469 const int32_t pointerId = entry.pointerProperties[0].id;
2470 if (oldState == nullptr ||
2471 oldState->getWindowsWithHoveringPointer(entry.deviceId, pointerId).empty()) {
2472 LOG(INFO) << "Dropping event because the hovering pointer is not in any windows in "
2473 "display "
2474 << displayId << ": " << entry.getDescription();
2475 outInjectionResult = InputEventInjectionResult::FAILED;
2476 return {};
2477 }
2478 tempTouchState.removeHoveringPointer(entry.deviceId, pointerId);
2479 }
2480
arthurhung6d4bed92021-03-17 11:59:33 +08002481 addDragEventLocked(entry);
arthurhungb89ccb02020-12-30 16:19:01 +08002482
Michael Wrightd02c5b62014-02-10 15:10:22 -08002483 // Check whether touches should slip outside of the current foreground window.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002484 if (maskedAction == AMOTION_EVENT_ACTION_MOVE && entry.pointerCount == 1 &&
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002485 tempTouchState.isSlippery()) {
Siarhei Vishniakou9306c382022-09-30 15:30:31 -07002486 const auto [x, y] = resolveTouchedPosition(entry);
Harry Cutts33476232023-01-30 19:57:29 +00002487 const bool isStylus = isPointerFromStylus(entry, /*pointerIndex=*/0);
chaviw98318de2021-05-19 16:45:23 -05002488 sp<WindowInfoHandle> oldTouchedWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002489 tempTouchState.getFirstForegroundWindowHandle();
Siarhei Vishniakou0f6558d2023-04-21 12:05:13 -07002490 LOG_ALWAYS_FATAL_IF(oldTouchedWindowHandle == nullptr);
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002491 auto [newTouchedWindowHandle, _] = findTouchedWindowAtLocked(displayId, x, y, isStylus);
Vishnu Nair062a8672021-09-03 16:07:44 -07002492
Prabir Pradhan5735a322022-04-11 17:23:34 +00002493 // Verify targeted injection.
2494 if (const auto err = verifyTargetedInjection(newTouchedWindowHandle, entry); err) {
2495 ALOGW("Dropping injected event: %s", (*err).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002496 outInjectionResult = os::InputEventInjectionResult::TARGET_MISMATCH;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002497 return {};
Prabir Pradhan5735a322022-04-11 17:23:34 +00002498 }
2499
Vishnu Nair062a8672021-09-03 16:07:44 -07002500 // Drop touch events if requested by input feature
2501 if (newTouchedWindowHandle != nullptr &&
2502 shouldDropInput(entry, newTouchedWindowHandle)) {
2503 newTouchedWindowHandle = nullptr;
2504 }
2505
Siarhei Vishniakouafa08cc2023-05-08 22:35:50 -07002506 if (newTouchedWindowHandle != nullptr &&
2507 !haveSameToken(oldTouchedWindowHandle, newTouchedWindowHandle)) {
Siarhei Vishniakou0f6558d2023-04-21 12:05:13 -07002508 ALOGD("Touch is slipping out of window %s into window %s in display %" PRId32,
2509 oldTouchedWindowHandle->getName().c_str(),
2510 newTouchedWindowHandle->getName().c_str(), displayId);
2511
Michael Wrightd02c5b62014-02-10 15:10:22 -08002512 // Make a slippery exit from the old window.
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08002513 std::bitset<MAX_POINTER_ID + 1> pointerIds;
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002514 const int32_t pointerId = entry.pointerProperties[0].id;
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08002515 pointerIds.set(pointerId);
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002516
2517 const TouchedWindow& touchedWindow =
2518 tempTouchState.getTouchedWindow(oldTouchedWindowHandle);
2519 addWindowTargetLocked(oldTouchedWindowHandle,
2520 InputTarget::Flags::DISPATCH_AS_SLIPPERY_EXIT, pointerIds,
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002521 touchedWindow.getDownTimeInTarget(entry.deviceId), targets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002522
2523 // Make a slippery entrance into the new window.
2524 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
Prabir Pradhan713bb3e2021-12-20 02:07:40 -08002525 isSplit = !isFromMouse;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002526 }
2527
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002528 ftl::Flags<InputTarget::Flags> targetFlags =
2529 InputTarget::Flags::DISPATCH_AS_SLIPPERY_ENTER;
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002530 if (canReceiveForegroundTouches(*newTouchedWindowHandle->getInfo())) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002531 targetFlags |= InputTarget::Flags::FOREGROUND;
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002532 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002533 if (isSplit) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002534 targetFlags |= InputTarget::Flags::SPLIT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002535 }
2536 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002537 targetFlags |= InputTarget::Flags::WINDOW_IS_OBSCURED;
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002538 } else if (isWindowObscuredLocked(newTouchedWindowHandle)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002539 targetFlags |= InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002540 }
2541
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002542 tempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags,
2543 entry.deviceId, pointerIds, entry.eventTime);
Arthur Hungc539dbb2022-12-08 07:45:36 +00002544
2545 // Check if the wallpaper window should deliver the corresponding event.
2546 slipWallpaperTouch(targetFlags, oldTouchedWindowHandle, newTouchedWindowHandle,
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002547 tempTouchState, entry.deviceId, pointerId, targets);
2548 tempTouchState.removeTouchingPointerFromWindow(entry.deviceId, pointerId,
2549 oldTouchedWindowHandle);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002550 }
2551 }
Arthur Hung96483742022-11-15 03:30:48 +00002552
2553 // Update the pointerIds for non-splittable when it received pointer down.
2554 if (!isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN) {
2555 // If no split, we suppose all touched windows should receive pointer down.
Siarhei Vishniakou5b9766d2023-07-18 14:06:29 -07002556 const int32_t pointerIndex = MotionEvent::getActionIndex(action);
Arthur Hung96483742022-11-15 03:30:48 +00002557 for (size_t i = 0; i < tempTouchState.windows.size(); i++) {
2558 TouchedWindow& touchedWindow = tempTouchState.windows[i];
2559 // Ignore drag window for it should just track one pointer.
2560 if (mDragState && mDragState->dragWindow == touchedWindow.windowHandle) {
2561 continue;
2562 }
Siarhei Vishniakou5b9766d2023-07-18 14:06:29 -07002563 std::bitset<MAX_POINTER_ID + 1> touchingPointers;
2564 touchingPointers.set(entry.pointerProperties[pointerIndex].id);
2565 touchedWindow.addTouchingPointers(entry.deviceId, touchingPointers);
Arthur Hung96483742022-11-15 03:30:48 +00002566 }
2567 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002568 }
2569
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002570 // Update dispatching for hover enter and exit.
Sam Dubeyf886dec2023-01-27 13:28:19 +00002571 {
2572 std::vector<TouchedWindow> hoveringWindows =
2573 getHoveringWindowsLocked(oldState, tempTouchState, entry);
2574 for (const TouchedWindow& touchedWindow : hoveringWindows) {
Siarhei Vishniakoud5876ba2023-05-15 17:58:34 -07002575 std::optional<InputTarget> target =
2576 createInputTargetLocked(touchedWindow.windowHandle, touchedWindow.targetFlags,
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002577 touchedWindow.getDownTimeInTarget(entry.deviceId));
Siarhei Vishniakoud5876ba2023-05-15 17:58:34 -07002578 if (!target) {
2579 continue;
2580 }
2581 // Hardcode to single hovering pointer for now.
2582 std::bitset<MAX_POINTER_ID + 1> pointerIds;
2583 pointerIds.set(entry.pointerProperties[0].id);
2584 target->addPointers(pointerIds, touchedWindow.windowHandle->getInfo()->transform);
2585 targets.push_back(*target);
Sam Dubeyf886dec2023-01-27 13:28:19 +00002586 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002587 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002588
Prabir Pradhan5735a322022-04-11 17:23:34 +00002589 // Ensure that all touched windows are valid for injection.
2590 if (entry.injectionState != nullptr) {
2591 std::string errs;
2592 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Prabir Pradhan5735a322022-04-11 17:23:34 +00002593 const auto err = verifyTargetedInjection(touchedWindow.windowHandle, entry);
2594 if (err) errs += "\n - " + *err;
2595 }
2596 if (!errs.empty()) {
2597 ALOGW("Dropping targeted injection: At least one touched window is not owned by uid "
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00002598 "%s:%s",
2599 entry.injectionState->targetUid->toString().c_str(), errs.c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002600 outInjectionResult = InputEventInjectionResult::TARGET_MISMATCH;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002601 return {};
Prabir Pradhan5735a322022-04-11 17:23:34 +00002602 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002603 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002604
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002605 // Check whether windows listening for outside touches are owned by the same UID. If the owner
2606 // has a different UID, then we will not reveal coordinate information to this window.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002607 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
chaviw98318de2021-05-19 16:45:23 -05002608 sp<WindowInfoHandle> foregroundWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002609 tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002610 if (foregroundWindowHandle) {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00002611 const auto foregroundWindowUid = foregroundWindowHandle->getInfo()->ownerUid;
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002612 for (InputTarget& target : targets) {
2613 if (target.flags.test(InputTarget::Flags::DISPATCH_AS_OUTSIDE)) {
2614 sp<WindowInfoHandle> targetWindow =
2615 getWindowHandleLocked(target.inputChannel->getConnectionToken());
2616 if (targetWindow->getInfo()->ownerUid != foregroundWindowUid) {
2617 target.flags |= InputTarget::Flags::ZERO_COORDS;
Michael Wright3dd60e22019-03-27 22:06:44 +00002618 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002619 }
2620 }
2621 }
2622 }
2623
Harry Cuttsb166c002023-05-09 13:06:05 +00002624 // If this is a touchpad navigation gesture, it needs to only be sent to trusted targets, as we
2625 // only want the system UI to handle these gestures.
2626 const bool isTouchpadNavGesture = isFromSource(entry.source, AINPUT_SOURCE_MOUSE) &&
2627 entry.classification == MotionClassification::MULTI_FINGER_SWIPE;
2628 if (isTouchpadNavGesture) {
2629 filterUntrustedTargets(/* byref */ tempTouchState, /* byref */ targets);
2630 }
2631
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07002632 // Output targets from the touch state.
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002633 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002634 if (!touchedWindow.hasTouchingPointers(entry.deviceId) &&
2635 !touchedWindow.hasHoveringPointers(entry.deviceId)) {
Siarhei Vishniakoue0431e42023-01-28 17:01:39 -08002636 // Windows with hovering pointers are getting persisted inside TouchState.
2637 // Do not send this event to those windows.
2638 continue;
2639 }
Harry Cuttsb166c002023-05-09 13:06:05 +00002640
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002641 addWindowTargetLocked(touchedWindow.windowHandle, touchedWindow.targetFlags,
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002642 touchedWindow.getTouchingPointers(entry.deviceId),
2643 touchedWindow.getDownTimeInTarget(entry.deviceId), targets);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002644 }
Sam Dubey39d37cf2022-12-07 18:05:35 +00002645
Siarhei Vishniakou580fb3a2023-05-05 15:02:20 -07002646 // During targeted injection, only allow owned targets to receive events
2647 std::erase_if(targets, [&](const InputTarget& target) {
2648 LOG_ALWAYS_FATAL_IF(target.windowHandle == nullptr);
2649 const auto err = verifyTargetedInjection(target.windowHandle, entry);
2650 if (err) {
2651 LOG(WARNING) << "Dropping injected event from " << target.windowHandle->getName()
2652 << ": " << (*err);
2653 return true;
2654 }
2655 return false;
2656 });
2657
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07002658 if (targets.empty()) {
2659 LOG(INFO) << "Dropping event because no targets were found: " << entry.getDescription();
2660 outInjectionResult = InputEventInjectionResult::FAILED;
2661 return {};
2662 }
2663
2664 // If we only have windows getting ACTION_OUTSIDE, then drop the event, because there is no
2665 // window that is actually receiving the entire gesture.
2666 if (std::all_of(targets.begin(), targets.end(), [](const InputTarget& target) {
2667 return target.flags.test(InputTarget::Flags::DISPATCH_AS_OUTSIDE);
2668 })) {
2669 LOG(INFO) << "Dropping event because all windows would just receive ACTION_OUTSIDE: "
2670 << entry.getDescription();
2671 outInjectionResult = InputEventInjectionResult::FAILED;
2672 return {};
2673 }
2674
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002675 outInjectionResult = InputEventInjectionResult::SUCCEEDED;
Sam Dubeyf886dec2023-01-27 13:28:19 +00002676 // Drop the outside or hover touch windows since we will not care about them
2677 // in the next iteration.
2678 tempTouchState.filterNonAsIsTouchWindows();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002679
Michael Wrightd02c5b62014-02-10 15:10:22 -08002680 // Update final pieces of touch state if the injector had permission.
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002681 if (switchedDevice) {
2682 if (DEBUG_FOCUS) {
2683 ALOGD("Conflicting pointer actions: Switched to a different device.");
2684 }
2685 *outConflictingPointerActions = true;
2686 }
2687
2688 if (isHoverAction) {
2689 // Started hovering, therefore no longer down.
Siarhei Vishniakou3ad385b2022-11-04 10:09:53 -07002690 if (oldState && oldState->isDown()) {
Siarhei Vishniakou6e1e9872022-11-08 17:51:35 -08002691 ALOGD_IF(DEBUG_FOCUS,
2692 "Conflicting pointer actions: Hover received while pointer was down.");
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002693 *outConflictingPointerActions = true;
2694 }
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002695 } else if (maskedAction == AMOTION_EVENT_ACTION_UP) {
2696 // Pointer went up.
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002697 tempTouchState.removeTouchingPointer(entry.deviceId, entry.pointerProperties[0].id);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002698 } else if (maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002699 // All pointers up or canceled.
2700 tempTouchState.reset();
2701 } else if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
2702 // First pointer went down.
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002703 if (oldState && (oldState->isDown() || oldState->hasHoveringPointers())) {
2704 ALOGD("Conflicting pointer actions: Down received while already down or hovering.");
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002705 *outConflictingPointerActions = true;
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002706 }
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002707 } else if (maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
2708 // One pointer went up.
Siarhei Vishniakou5b9766d2023-07-18 14:06:29 -07002709 const int32_t pointerIndex = MotionEvent::getActionIndex(action);
2710 const uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
2711 tempTouchState.removeTouchingPointer(entry.deviceId, pointerId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002712 }
2713
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002714 // Save changes unless the action was scroll in which case the temporary touch
2715 // state was only valid for this one action.
2716 if (maskedAction != AMOTION_EVENT_ACTION_SCROLL) {
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07002717 if (displayId >= 0) {
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002718 tempTouchState.clearWindowsWithoutPointers();
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002719 mTouchStatesByDisplay[displayId] = tempTouchState;
2720 } else {
2721 mTouchStatesByDisplay.erase(displayId);
2722 }
2723 }
2724
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -08002725 if (tempTouchState.windows.empty()) {
2726 mTouchStatesByDisplay.erase(displayId);
2727 }
2728
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002729 return targets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002730}
2731
arthurhung6d4bed92021-03-17 11:59:33 +08002732void InputDispatcher::finishDragAndDrop(int32_t displayId, float x, float y) {
Prabir Pradhand65552b2021-10-07 11:23:50 -07002733 // Prevent stylus interceptor windows from affecting drag and drop behavior for now, until we
2734 // have an explicit reason to support it.
2735 constexpr bool isStylus = false;
2736
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002737 auto [dropWindow, _] =
Harry Cutts33476232023-01-30 19:57:29 +00002738 findTouchedWindowAtLocked(displayId, x, y, isStylus, /*ignoreDragWindow=*/true);
arthurhung6d4bed92021-03-17 11:59:33 +08002739 if (dropWindow) {
2740 vec2 local = dropWindow->getInfo()->transform.transform(x, y);
Prabir Pradhancef936d2021-07-21 16:17:52 +00002741 sendDropWindowCommandLocked(dropWindow->getToken(), local.x, local.y);
Arthur Hung6d0571e2021-04-09 20:18:16 +08002742 } else {
Arthur Hung54745652022-04-20 07:17:41 +00002743 ALOGW("No window found when drop.");
Prabir Pradhancef936d2021-07-21 16:17:52 +00002744 sendDropWindowCommandLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08002745 }
2746 mDragState.reset();
2747}
2748
2749void InputDispatcher::addDragEventLocked(const MotionEntry& entry) {
Arthur Hung3915c1f2022-05-31 07:17:17 +00002750 if (!mDragState || mDragState->dragWindow->getInfo()->displayId != entry.displayId) {
arthurhungb89ccb02020-12-30 16:19:01 +08002751 return;
2752 }
2753
arthurhung6d4bed92021-03-17 11:59:33 +08002754 if (!mDragState->isStartDrag) {
2755 mDragState->isStartDrag = true;
2756 mDragState->isStylusButtonDownAtStart =
2757 (entry.buttonState & AMOTION_EVENT_BUTTON_STYLUS_PRIMARY) != 0;
2758 }
2759
Arthur Hung54745652022-04-20 07:17:41 +00002760 // Find the pointer index by id.
2761 int32_t pointerIndex = 0;
2762 for (; static_cast<uint32_t>(pointerIndex) < entry.pointerCount; pointerIndex++) {
2763 const PointerProperties& pointerProperties = entry.pointerProperties[pointerIndex];
2764 if (pointerProperties.id == mDragState->pointerId) {
2765 break;
arthurhung6d4bed92021-03-17 11:59:33 +08002766 }
Arthur Hung54745652022-04-20 07:17:41 +00002767 }
arthurhung6d4bed92021-03-17 11:59:33 +08002768
Arthur Hung54745652022-04-20 07:17:41 +00002769 if (uint32_t(pointerIndex) == entry.pointerCount) {
2770 LOG_ALWAYS_FATAL("Should find a valid pointer index by id %d", mDragState->pointerId);
Arthur Hung54745652022-04-20 07:17:41 +00002771 }
2772
2773 const int32_t maskedAction = entry.action & AMOTION_EVENT_ACTION_MASK;
2774 const int32_t x = entry.pointerCoords[pointerIndex].getX();
2775 const int32_t y = entry.pointerCoords[pointerIndex].getY();
2776
2777 switch (maskedAction) {
2778 case AMOTION_EVENT_ACTION_MOVE: {
2779 // Handle the special case : stylus button no longer pressed.
2780 bool isStylusButtonDown =
2781 (entry.buttonState & AMOTION_EVENT_BUTTON_STYLUS_PRIMARY) != 0;
2782 if (mDragState->isStylusButtonDownAtStart && !isStylusButtonDown) {
2783 finishDragAndDrop(entry.displayId, x, y);
2784 return;
2785 }
2786
2787 // Prevent stylus interceptor windows from affecting drag and drop behavior for now,
2788 // until we have an explicit reason to support it.
2789 constexpr bool isStylus = false;
2790
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002791 auto [hoverWindowHandle, _] = findTouchedWindowAtLocked(entry.displayId, x, y, isStylus,
Harry Cutts33476232023-01-30 19:57:29 +00002792 /*ignoreDragWindow=*/true);
Arthur Hung54745652022-04-20 07:17:41 +00002793 // enqueue drag exit if needed.
2794 if (hoverWindowHandle != mDragState->dragHoverWindowHandle &&
2795 !haveSameToken(hoverWindowHandle, mDragState->dragHoverWindowHandle)) {
2796 if (mDragState->dragHoverWindowHandle != nullptr) {
Harry Cutts33476232023-01-30 19:57:29 +00002797 enqueueDragEventLocked(mDragState->dragHoverWindowHandle, /*isExiting=*/true, x,
Arthur Hung54745652022-04-20 07:17:41 +00002798 y);
2799 }
2800 mDragState->dragHoverWindowHandle = hoverWindowHandle;
2801 }
2802 // enqueue drag location if needed.
2803 if (hoverWindowHandle != nullptr) {
Harry Cutts33476232023-01-30 19:57:29 +00002804 enqueueDragEventLocked(hoverWindowHandle, /*isExiting=*/false, x, y);
Arthur Hung54745652022-04-20 07:17:41 +00002805 }
2806 break;
2807 }
2808
2809 case AMOTION_EVENT_ACTION_POINTER_UP:
Siarhei Vishniakou5b9766d2023-07-18 14:06:29 -07002810 if (MotionEvent::getActionIndex(entry.action) != pointerIndex) {
Arthur Hung54745652022-04-20 07:17:41 +00002811 break;
2812 }
2813 // The drag pointer is up.
2814 [[fallthrough]];
2815 case AMOTION_EVENT_ACTION_UP:
2816 finishDragAndDrop(entry.displayId, x, y);
2817 break;
2818 case AMOTION_EVENT_ACTION_CANCEL: {
2819 ALOGD("Receiving cancel when drag and drop.");
2820 sendDropWindowCommandLocked(nullptr, 0, 0);
2821 mDragState.reset();
2822 break;
2823 }
arthurhungb89ccb02020-12-30 16:19:01 +08002824 }
2825}
2826
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002827std::optional<InputTarget> InputDispatcher::createInputTargetLocked(
2828 const sp<android::gui::WindowInfoHandle>& windowHandle,
2829 ftl::Flags<InputTarget::Flags> targetFlags,
2830 std::optional<nsecs_t> firstDownTimeInTarget) const {
2831 std::shared_ptr<InputChannel> inputChannel = getInputChannelLocked(windowHandle->getToken());
2832 if (inputChannel == nullptr) {
2833 ALOGW("Not creating InputTarget for %s, no input channel", windowHandle->getName().c_str());
2834 return {};
2835 }
2836 InputTarget inputTarget;
2837 inputTarget.inputChannel = inputChannel;
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00002838 inputTarget.windowHandle = windowHandle;
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002839 inputTarget.flags = targetFlags;
2840 inputTarget.globalScaleFactor = windowHandle->getInfo()->globalScaleFactor;
2841 inputTarget.firstDownTimeInTarget = firstDownTimeInTarget;
2842 const auto& displayInfoIt = mDisplayInfos.find(windowHandle->getInfo()->displayId);
2843 if (displayInfoIt != mDisplayInfos.end()) {
2844 inputTarget.displayTransform = displayInfoIt->second.transform;
2845 } else {
Siarhei Vishniakou580fb3a2023-05-05 15:02:20 -07002846 // DisplayInfo not found for this window on display windowHandle->getInfo()->displayId.
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002847 // TODO(b/198444055): Make this an error message after 'setInputWindows' API is removed.
2848 }
2849 return inputTarget;
2850}
2851
chaviw98318de2021-05-19 16:45:23 -05002852void InputDispatcher::addWindowTargetLocked(const sp<WindowInfoHandle>& windowHandle,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002853 ftl::Flags<InputTarget::Flags> targetFlags,
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08002854 std::bitset<MAX_POINTER_ID + 1> pointerIds,
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002855 std::optional<nsecs_t> firstDownTimeInTarget,
Siarhei Vishniakouf75cddb2022-10-25 10:42:16 -07002856 std::vector<InputTarget>& inputTargets) const {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002857 std::vector<InputTarget>::iterator it =
2858 std::find_if(inputTargets.begin(), inputTargets.end(),
2859 [&windowHandle](const InputTarget& inputTarget) {
2860 return inputTarget.inputChannel->getConnectionToken() ==
2861 windowHandle->getToken();
2862 });
Chavi Weingarten97b8eec2020-01-09 18:09:08 +00002863
chaviw98318de2021-05-19 16:45:23 -05002864 const WindowInfo* windowInfo = windowHandle->getInfo();
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002865
2866 if (it == inputTargets.end()) {
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002867 std::optional<InputTarget> target =
2868 createInputTargetLocked(windowHandle, targetFlags, firstDownTimeInTarget);
2869 if (!target) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002870 return;
2871 }
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002872 inputTargets.push_back(*target);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002873 it = inputTargets.end() - 1;
2874 }
2875
2876 ALOG_ASSERT(it->flags == targetFlags);
2877 ALOG_ASSERT(it->globalScaleFactor == windowInfo->globalScaleFactor);
2878
chaviw1ff3d1e2020-07-01 15:53:47 -07002879 it->addPointers(pointerIds, windowInfo->transform);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002880}
2881
Michael Wright3dd60e22019-03-27 22:06:44 +00002882void InputDispatcher::addGlobalMonitoringTargetsLocked(std::vector<InputTarget>& inputTargets,
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002883 int32_t displayId) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002884 auto monitorsIt = mGlobalMonitorsByDisplay.find(displayId);
2885 if (monitorsIt == mGlobalMonitorsByDisplay.end()) return;
Michael Wright3dd60e22019-03-27 22:06:44 +00002886
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002887 for (const Monitor& monitor : selectResponsiveMonitorsLocked(monitorsIt->second)) {
2888 InputTarget target;
2889 target.inputChannel = monitor.inputChannel;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002890 target.flags = InputTarget::Flags::DISPATCH_AS_IS;
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002891 // target.firstDownTimeInTarget is not set for global monitors. It is only required in split
2892 // touch and global monitoring works as intended even without setting firstDownTimeInTarget
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002893 if (const auto& it = mDisplayInfos.find(displayId); it != mDisplayInfos.end()) {
2894 target.displayTransform = it->second.transform;
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002895 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002896 target.setDefaultPointerTransform(target.displayTransform);
2897 inputTargets.push_back(target);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002898 }
2899}
2900
Robert Carrc9bf1d32020-04-13 17:21:08 -07002901/**
2902 * Indicate whether one window handle should be considered as obscuring
2903 * another window handle. We only check a few preconditions. Actually
2904 * checking the bounds is left to the caller.
2905 */
chaviw98318de2021-05-19 16:45:23 -05002906static bool canBeObscuredBy(const sp<WindowInfoHandle>& windowHandle,
2907 const sp<WindowInfoHandle>& otherHandle) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002908 // Compare by token so cloned layers aren't counted
2909 if (haveSameToken(windowHandle, otherHandle)) {
2910 return false;
2911 }
2912 auto info = windowHandle->getInfo();
2913 auto otherInfo = otherHandle->getInfo();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002914 if (otherInfo->inputConfig.test(WindowInfo::InputConfig::NOT_VISIBLE)) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002915 return false;
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002916 } else if (otherInfo->alpha == 0 &&
2917 otherInfo->inputConfig.test(WindowInfo::InputConfig::NOT_TOUCHABLE)) {
Bernardo Rufino653d2e02020-10-20 17:32:40 +00002918 // Those act as if they were invisible, so we don't need to flag them.
2919 // We do want to potentially flag touchable windows even if they have 0
2920 // opacity, since they can consume touches and alter the effects of the
2921 // user interaction (eg. apps that rely on
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002922 // Flags::WINDOW_IS_PARTIALLY_OBSCURED should still be told about those
Bernardo Rufino653d2e02020-10-20 17:32:40 +00002923 // windows), hence we also check for FLAG_NOT_TOUCHABLE.
2924 return false;
Bernardo Rufino8007daf2020-09-22 09:40:01 +00002925 } else if (info->ownerUid == otherInfo->ownerUid) {
2926 // If ownerUid is the same we don't generate occlusion events as there
2927 // is no security boundary within an uid.
Robert Carrc9bf1d32020-04-13 17:21:08 -07002928 return false;
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002929 } else if (otherInfo->inputConfig.test(gui::WindowInfo::InputConfig::TRUSTED_OVERLAY)) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002930 return false;
2931 } else if (otherInfo->displayId != info->displayId) {
2932 return false;
2933 }
2934 return true;
2935}
2936
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002937/**
2938 * Returns touch occlusion information in the form of TouchOcclusionInfo. To check if the touch is
2939 * untrusted, one should check:
2940 *
2941 * 1. If result.hasBlockingOcclusion is true.
2942 * If it's, it means the touch should be blocked due to a window with occlusion mode of
2943 * BLOCK_UNTRUSTED.
2944 *
2945 * 2. If result.obscuringOpacity > mMaximumObscuringOpacityForTouch.
2946 * If it is (and 1 is false), then the touch should be blocked because a stack of windows
2947 * (possibly only one) with occlusion mode of USE_OPACITY from one UID resulted in a composed
2948 * obscuring opacity above the threshold. Note that if there was no window of occlusion mode
2949 * USE_OPACITY, result.obscuringOpacity would've been 0 and since
2950 * mMaximumObscuringOpacityForTouch >= 0, the condition above would never be true.
2951 *
2952 * If neither of those is true, then it means the touch can be allowed.
2953 */
2954InputDispatcher::TouchOcclusionInfo InputDispatcher::computeTouchOcclusionInfoLocked(
chaviw98318de2021-05-19 16:45:23 -05002955 const sp<WindowInfoHandle>& windowHandle, int32_t x, int32_t y) const {
2956 const WindowInfo* windowInfo = windowHandle->getInfo();
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002957 int32_t displayId = windowInfo->displayId;
chaviw98318de2021-05-19 16:45:23 -05002958 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002959 TouchOcclusionInfo info;
2960 info.hasBlockingOcclusion = false;
2961 info.obscuringOpacity = 0;
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00002962 info.obscuringUid = gui::Uid::INVALID;
2963 std::map<gui::Uid, float> opacityByUid;
chaviw98318de2021-05-19 16:45:23 -05002964 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002965 if (windowHandle == otherHandle) {
2966 break; // All future windows are below us. Exit early.
2967 }
chaviw98318de2021-05-19 16:45:23 -05002968 const WindowInfo* otherInfo = otherHandle->getInfo();
Bernardo Rufino1ff9d592021-01-18 16:58:57 +00002969 if (canBeObscuredBy(windowHandle, otherHandle) && otherInfo->frameContainsPoint(x, y) &&
2970 !haveSameApplicationToken(windowInfo, otherInfo)) {
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002971 if (DEBUG_TOUCH_OCCLUSION) {
2972 info.debugInfo.push_back(
Harry Cutts101ee9b2023-07-06 18:04:14 +00002973 dumpWindowForTouchOcclusion(otherInfo, /*isTouchedWindow=*/false));
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002974 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002975 // canBeObscuredBy() has returned true above, which means this window is untrusted, so
2976 // we perform the checks below to see if the touch can be propagated or not based on the
2977 // window's touch occlusion mode
2978 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::BLOCK_UNTRUSTED) {
2979 info.hasBlockingOcclusion = true;
2980 info.obscuringUid = otherInfo->ownerUid;
2981 info.obscuringPackage = otherInfo->packageName;
2982 break;
2983 }
2984 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::USE_OPACITY) {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00002985 const auto uid = otherInfo->ownerUid;
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002986 float opacity =
2987 (opacityByUid.find(uid) == opacityByUid.end()) ? 0 : opacityByUid[uid];
2988 // Given windows A and B:
2989 // opacity(A, B) = 1 - [1 - opacity(A)] * [1 - opacity(B)]
2990 opacity = 1 - (1 - opacity) * (1 - otherInfo->alpha);
2991 opacityByUid[uid] = opacity;
2992 if (opacity > info.obscuringOpacity) {
2993 info.obscuringOpacity = opacity;
2994 info.obscuringUid = uid;
2995 info.obscuringPackage = otherInfo->packageName;
2996 }
2997 }
2998 }
2999 }
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00003000 if (DEBUG_TOUCH_OCCLUSION) {
Harry Cutts101ee9b2023-07-06 18:04:14 +00003001 info.debugInfo.push_back(dumpWindowForTouchOcclusion(windowInfo, /*isTouchedWindow=*/true));
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00003002 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003003 return info;
3004}
3005
chaviw98318de2021-05-19 16:45:23 -05003006std::string InputDispatcher::dumpWindowForTouchOcclusion(const WindowInfo* info,
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00003007 bool isTouchedWindow) const {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003008 return StringPrintf(INDENT2 "* %spackage=%s/%s, id=%" PRId32 ", mode=%s, alpha=%.2f, "
Prabir Pradhan51e7db02022-02-07 06:02:57 -08003009 "frame=[%" PRId32 ",%" PRId32 "][%" PRId32 ",%" PRId32
3010 "], touchableRegion=%s, window={%s}, inputConfig={%s}, "
3011 "hasToken=%s, applicationInfo.name=%s, applicationInfo.token=%s\n",
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08003012 isTouchedWindow ? "[TOUCHED] " : "", info->packageName.c_str(),
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003013 info->ownerUid.toString().c_str(), info->id,
3014 toString(info->touchOcclusionMode).c_str(), info->alpha, info->frameLeft,
3015 info->frameTop, info->frameRight, info->frameBottom,
3016 dumpRegion(info->touchableRegion).c_str(), info->name.c_str(),
3017 info->inputConfig.string().c_str(), toString(info->token != nullptr),
3018 info->applicationInfo.name.c_str(),
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07003019 binderToString(info->applicationInfo.token).c_str());
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00003020}
3021
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003022bool InputDispatcher::isTouchTrustedLocked(const TouchOcclusionInfo& occlusionInfo) const {
3023 if (occlusionInfo.hasBlockingOcclusion) {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003024 ALOGW("Untrusted touch due to occlusion by %s/%s", occlusionInfo.obscuringPackage.c_str(),
3025 occlusionInfo.obscuringUid.toString().c_str());
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003026 return false;
3027 }
3028 if (occlusionInfo.obscuringOpacity > mMaximumObscuringOpacityForTouch) {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003029 ALOGW("Untrusted touch due to occlusion by %s/%s (obscuring opacity = "
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003030 "%.2f, maximum allowed = %.2f)",
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003031 occlusionInfo.obscuringPackage.c_str(), occlusionInfo.obscuringUid.toString().c_str(),
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003032 occlusionInfo.obscuringOpacity, mMaximumObscuringOpacityForTouch);
3033 return false;
3034 }
3035 return true;
3036}
3037
chaviw98318de2021-05-19 16:45:23 -05003038bool InputDispatcher::isWindowObscuredAtPointLocked(const sp<WindowInfoHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003039 int32_t x, int32_t y) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003040 int32_t displayId = windowHandle->getInfo()->displayId;
chaviw98318de2021-05-19 16:45:23 -05003041 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
3042 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07003043 if (windowHandle == otherHandle) {
3044 break; // All future windows are below us. Exit early.
Michael Wrightd02c5b62014-02-10 15:10:22 -08003045 }
chaviw98318de2021-05-19 16:45:23 -05003046 const WindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07003047 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08003048 otherInfo->frameContainsPoint(x, y)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003049 return true;
3050 }
3051 }
3052 return false;
3053}
3054
chaviw98318de2021-05-19 16:45:23 -05003055bool InputDispatcher::isWindowObscuredLocked(const sp<WindowInfoHandle>& windowHandle) const {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07003056 int32_t displayId = windowHandle->getInfo()->displayId;
chaviw98318de2021-05-19 16:45:23 -05003057 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
3058 const WindowInfo* windowInfo = windowHandle->getInfo();
3059 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07003060 if (windowHandle == otherHandle) {
3061 break; // All future windows are below us. Exit early.
Michael Wrightcdcd8f22016-03-22 16:52:13 -07003062 }
chaviw98318de2021-05-19 16:45:23 -05003063 const WindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07003064 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08003065 otherInfo->overlaps(windowInfo)) {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07003066 return true;
3067 }
3068 }
3069 return false;
3070}
3071
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08003072std::string InputDispatcher::getApplicationWindowLabel(
chaviw98318de2021-05-19 16:45:23 -05003073 const InputApplicationHandle* applicationHandle, const sp<WindowInfoHandle>& windowHandle) {
Yi Kong9b14ac62018-07-17 13:48:38 -07003074 if (applicationHandle != nullptr) {
3075 if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07003076 return applicationHandle->getName() + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003077 } else {
3078 return applicationHandle->getName();
3079 }
Yi Kong9b14ac62018-07-17 13:48:38 -07003080 } else if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07003081 return windowHandle->getInfo()->applicationInfo.name + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003082 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003083 return "<unknown application or window>";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003084 }
3085}
3086
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003087void InputDispatcher::pokeUserActivityLocked(const EventEntry& eventEntry) {
Antonio Kantekf16f2832021-09-28 04:39:20 +00003088 if (!isUserActivityEvent(eventEntry)) {
3089 // Not poking user activity if the event type does not represent a user activity
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003090 return;
3091 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003092 int32_t displayId = getTargetDisplayId(eventEntry);
chaviw98318de2021-05-19 16:45:23 -05003093 sp<WindowInfoHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Josep del Riob3981622023-04-18 15:49:45 +00003094 const WindowInfo* windowDisablingUserActivityInfo = nullptr;
Tiger Huang721e26f2018-07-24 22:26:19 +08003095 if (focusedWindowHandle != nullptr) {
chaviw98318de2021-05-19 16:45:23 -05003096 const WindowInfo* info = focusedWindowHandle->getInfo();
Prabir Pradhan51e7db02022-02-07 06:02:57 -08003097 if (info->inputConfig.test(WindowInfo::InputConfig::DISABLE_USER_ACTIVITY)) {
Josep del Riob3981622023-04-18 15:49:45 +00003098 windowDisablingUserActivityInfo = info;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003099 }
3100 }
3101
3102 int32_t eventType = USER_ACTIVITY_EVENT_OTHER;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003103 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003104 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003105 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
3106 if (motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003107 return;
3108 }
Josep del Riob3981622023-04-18 15:49:45 +00003109 if (windowDisablingUserActivityInfo != nullptr) {
3110 if (DEBUG_DISPATCH_CYCLE) {
3111 ALOGD("Not poking user activity: disabled by window '%s'.",
3112 windowDisablingUserActivityInfo->name.c_str());
3113 }
3114 return;
3115 }
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003116 if (MotionEvent::isTouchEvent(motionEntry.source, motionEntry.action)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003117 eventType = USER_ACTIVITY_EVENT_TOUCH;
3118 }
3119 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003120 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003121 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003122 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
3123 if (keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003124 return;
3125 }
Josep del Riob3981622023-04-18 15:49:45 +00003126 // If the key code is unknown, we don't consider it user activity
3127 if (keyEntry.keyCode == AKEYCODE_UNKNOWN) {
3128 return;
3129 }
3130 // Don't inhibit events that were intercepted or are not passed to
3131 // the apps, like system shortcuts
3132 if (windowDisablingUserActivityInfo != nullptr &&
3133 keyEntry.interceptKeyResult != KeyEntry::InterceptKeyResult::SKIP &&
3134 keyEntry.policyFlags & POLICY_FLAG_PASS_TO_USER) {
3135 if (DEBUG_DISPATCH_CYCLE) {
3136 ALOGD("Not poking user activity: disabled by window '%s'.",
3137 windowDisablingUserActivityInfo->name.c_str());
3138 }
3139 return;
3140 }
3141
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003142 eventType = USER_ACTIVITY_EVENT_BUTTON;
3143 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003144 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00003145 default: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003146 LOG_ALWAYS_FATAL("%s events are not user activity",
Dominik Laskowski75788452021-02-09 18:51:25 -08003147 ftl::enum_string(eventEntry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003148 break;
3149 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003150 }
3151
Prabir Pradhancef936d2021-07-21 16:17:52 +00003152 auto command = [this, eventTime = eventEntry.eventTime, eventType, displayId]()
3153 REQUIRES(mLock) {
3154 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00003155 mPolicy.pokeUserActivity(eventTime, eventType, displayId);
Prabir Pradhancef936d2021-07-21 16:17:52 +00003156 };
3157 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003158}
3159
3160void InputDispatcher::prepareDispatchCycleLocked(nsecs_t currentTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003161 const std::shared_ptr<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003162 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003163 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003164 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003165 std::string message =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003166 StringPrintf("prepareDispatchCycleLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003167 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00003168 ATRACE_NAME(message.c_str());
3169 }
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003170 if (DEBUG_DISPATCH_CYCLE) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003171 ALOGD("channel '%s' ~ prepareDispatchCycle - flags=%s, "
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08003172 "globalScaleFactor=%f, pointerIds=%s %s",
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003173 connection->getInputChannelName().c_str(), inputTarget.flags.string().c_str(),
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08003174 inputTarget.globalScaleFactor, bitsetToString(inputTarget.pointerIds).c_str(),
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003175 inputTarget.getPointerInfoString().c_str());
3176 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003177
3178 // Skip this event if the connection status is not normal.
3179 // We don't want to enqueue additional outbound events if the connection is broken.
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003180 if (connection->status != Connection::Status::NORMAL) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003181 if (DEBUG_DISPATCH_CYCLE) {
3182 ALOGD("channel '%s' ~ Dropping event because the channel status is %s",
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003183 connection->getInputChannelName().c_str(),
3184 ftl::enum_string(connection->status).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003185 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003186 return;
3187 }
3188
3189 // Split a motion event if needed.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003190 if (inputTarget.flags.test(InputTarget::Flags::SPLIT)) {
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003191 LOG_ALWAYS_FATAL_IF(eventEntry->type != EventEntry::Type::MOTION,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003192 "Entry type %s should not have Flags::SPLIT",
Dominik Laskowski75788452021-02-09 18:51:25 -08003193 ftl::enum_string(eventEntry->type).c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003194
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003195 const MotionEntry& originalMotionEntry = static_cast<const MotionEntry&>(*eventEntry);
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003196 if (inputTarget.pointerIds.count() != originalMotionEntry.pointerCount) {
Siarhei Vishniakou16e4fa02023-02-16 17:48:56 -08003197 if (!inputTarget.firstDownTimeInTarget.has_value()) {
3198 logDispatchStateLocked();
3199 LOG(FATAL) << "Splitting motion events requires a down time to be set for the "
3200 "target on connection "
3201 << connection->getInputChannelName() << " for "
3202 << originalMotionEntry.getDescription();
3203 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003204 std::unique_ptr<MotionEntry> splitMotionEntry =
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00003205 splitMotionEvent(originalMotionEntry, inputTarget.pointerIds,
3206 inputTarget.firstDownTimeInTarget.value());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003207 if (!splitMotionEntry) {
3208 return; // split event was dropped
3209 }
Arthur Hungb3307ee2021-10-14 10:57:37 +00003210 if (splitMotionEntry->action == AMOTION_EVENT_ACTION_CANCEL) {
3211 std::string reason = std::string("reason=pointer cancel on split window");
3212 android_log_event_list(LOGTAG_INPUT_CANCEL)
3213 << connection->getInputChannelName().c_str() << reason << LOG_ID_EVENTS;
3214 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003215 if (DEBUG_FOCUS) {
3216 ALOGD("channel '%s' ~ Split motion event.",
3217 connection->getInputChannelName().c_str());
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003218 logOutboundMotionDetails(" ", *splitMotionEntry);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003219 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003220 enqueueDispatchEntriesLocked(currentTime, connection, std::move(splitMotionEntry),
3221 inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003222 return;
3223 }
3224 }
3225
3226 // Not splitting. Enqueue dispatch entries for the event as is.
3227 enqueueDispatchEntriesLocked(currentTime, connection, eventEntry, inputTarget);
3228}
3229
3230void InputDispatcher::enqueueDispatchEntriesLocked(nsecs_t currentTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003231 const std::shared_ptr<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003232 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003233 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003234 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003235 std::string message =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003236 StringPrintf("enqueueDispatchEntriesLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003237 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00003238 ATRACE_NAME(message.c_str());
3239 }
Siarhei Vishniakou5cee1e32022-11-29 12:35:39 -08003240 LOG_ALWAYS_FATAL_IF(!inputTarget.flags.any(InputTarget::DISPATCH_MASK),
3241 "No dispatch flags are set for %s", eventEntry->getDescription().c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00003242
hongzuo liu95785e22022-09-06 02:51:35 +00003243 const bool wasEmpty = connection->outboundQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003244
3245 // Enqueue dispatch entries for the requested modes.
chaviw8c9cf542019-03-25 13:02:48 -07003246 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003247 InputTarget::Flags::DISPATCH_AS_HOVER_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07003248 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003249 InputTarget::Flags::DISPATCH_AS_OUTSIDE);
chaviw8c9cf542019-03-25 13:02:48 -07003250 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003251 InputTarget::Flags::DISPATCH_AS_HOVER_ENTER);
chaviw8c9cf542019-03-25 13:02:48 -07003252 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003253 InputTarget::Flags::DISPATCH_AS_IS);
chaviw8c9cf542019-03-25 13:02:48 -07003254 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003255 InputTarget::Flags::DISPATCH_AS_SLIPPERY_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07003256 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003257 InputTarget::Flags::DISPATCH_AS_SLIPPERY_ENTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003258
3259 // If the outbound queue was previously empty, start the dispatch cycle going.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003260 if (wasEmpty && !connection->outboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003261 startDispatchCycleLocked(currentTime, connection);
3262 }
3263}
3264
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003265void InputDispatcher::enqueueDispatchEntryLocked(const std::shared_ptr<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003266 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003267 const InputTarget& inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003268 ftl::Flags<InputTarget::Flags> dispatchMode) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003269 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003270 std::string message = StringPrintf("enqueueDispatchEntry(inputChannel=%s, dispatchMode=%s)",
3271 connection->getInputChannelName().c_str(),
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003272 dispatchMode.string().c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00003273 ATRACE_NAME(message.c_str());
3274 }
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003275 ftl::Flags<InputTarget::Flags> inputTargetFlags = inputTarget.flags;
3276 if (!inputTargetFlags.any(dispatchMode)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003277 return;
3278 }
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003279
3280 inputTargetFlags.clear(InputTarget::DISPATCH_MASK);
3281 inputTargetFlags |= dispatchMode;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003282
3283 // This is a new event.
3284 // Enqueue a new dispatch entry onto the outbound queue for this connection.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003285 std::unique_ptr<DispatchEntry> dispatchEntry =
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003286 createDispatchEntry(inputTarget, eventEntry, inputTargetFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003287
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003288 // Use the eventEntry from dispatchEntry since the entry may have changed and can now be a
3289 // different EventEntry than what was passed in.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003290 EventEntry& newEntry = *(dispatchEntry->eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003291 // Apply target flags and update the connection's input state.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003292 switch (newEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003293 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003294 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(newEntry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003295 if (!connection->inputState.trackKey(keyEntry, dispatchEntry->resolvedAction,
3296 dispatchEntry->resolvedFlags)) {
Siarhei Vishniakouc94dafe2023-05-26 10:24:19 -07003297 LOG(WARNING) << "channel " << connection->getInputChannelName()
3298 << "~ dropping inconsistent event: " << *dispatchEntry;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003299 return; // skip the inconsistent event
3300 }
3301 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003302 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003303
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003304 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003305 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003306 // Assign a default value to dispatchEntry that will never be generated by InputReader,
3307 // and assign a InputDispatcher value if it doesn't change in the if-else chain below.
3308 constexpr int32_t DEFAULT_RESOLVED_EVENT_ID =
3309 static_cast<int32_t>(IdGenerator::Source::OTHER);
3310 dispatchEntry->resolvedEventId = DEFAULT_RESOLVED_EVENT_ID;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003311 if (dispatchMode.test(InputTarget::Flags::DISPATCH_AS_OUTSIDE)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003312 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_OUTSIDE;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003313 } else if (dispatchMode.test(InputTarget::Flags::DISPATCH_AS_HOVER_EXIT)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003314 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_EXIT;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003315 } else if (dispatchMode.test(InputTarget::Flags::DISPATCH_AS_HOVER_ENTER)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003316 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003317 } else if (dispatchMode.test(InputTarget::Flags::DISPATCH_AS_SLIPPERY_EXIT)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003318 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_CANCEL;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003319 } else if (dispatchMode.test(InputTarget::Flags::DISPATCH_AS_SLIPPERY_ENTER)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003320 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_DOWN;
3321 } else {
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003322 dispatchEntry->resolvedEventId = motionEntry.id;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003323 }
3324 if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_HOVER_MOVE &&
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003325 !connection->inputState.isHovering(motionEntry.deviceId, motionEntry.source,
3326 motionEntry.displayId)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003327 if (DEBUG_DISPATCH_CYCLE) {
3328 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: filling in missing hover "
3329 "enter event",
3330 connection->getInputChannelName().c_str());
3331 }
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00003332 // We keep the 'resolvedEventId' here equal to the original 'motionEntry.id' because
3333 // this is a one-to-one event conversion.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003334 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
3335 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003336
Siarhei Vishniakou1ae72f12023-01-29 12:55:30 -08003337 if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_CANCEL) {
3338 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_CANCELED;
3339 }
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003340 if (dispatchEntry->targetFlags.test(InputTarget::Flags::WINDOW_IS_OBSCURED)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003341 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED;
3342 }
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003343 if (dispatchEntry->targetFlags.test(InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003344 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
3345 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003346
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003347 if (!connection->inputState.trackMotion(motionEntry, dispatchEntry->resolvedAction,
3348 dispatchEntry->resolvedFlags)) {
Siarhei Vishniakouc94dafe2023-05-26 10:24:19 -07003349 LOG(WARNING) << "channel " << connection->getInputChannelName()
3350 << "~ dropping inconsistent event: " << *dispatchEntry;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003351 return; // skip the inconsistent event
3352 }
3353
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003354 dispatchEntry->resolvedEventId =
3355 dispatchEntry->resolvedEventId == DEFAULT_RESOLVED_EVENT_ID
3356 ? mIdGenerator.nextId()
3357 : motionEntry.id;
3358 if (ATRACE_ENABLED() && dispatchEntry->resolvedEventId != motionEntry.id) {
3359 std::string message = StringPrintf("Transmute MotionEvent(id=0x%" PRIx32
3360 ") to MotionEvent(id=0x%" PRIx32 ").",
3361 motionEntry.id, dispatchEntry->resolvedEventId);
3362 ATRACE_NAME(message.c_str());
3363 }
3364
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08003365 if ((motionEntry.flags & AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE) &&
3366 (motionEntry.policyFlags & POLICY_FLAG_TRUSTED)) {
3367 // Skip reporting pointer down outside focus to the policy.
3368 break;
3369 }
3370
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003371 dispatchPointerDownOutsideFocus(motionEntry.source, dispatchEntry->resolvedAction,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003372 inputTarget.inputChannel->getConnectionToken());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003373
3374 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003375 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003376 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003377 case EventEntry::Type::TOUCH_MODE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08003378 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
3379 case EventEntry::Type::DRAG: {
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003380 break;
3381 }
Chris Yef59a2f42020-10-16 12:55:26 -07003382 case EventEntry::Type::SENSOR: {
3383 LOG_ALWAYS_FATAL("SENSOR events should not go to apps via input channel");
3384 break;
3385 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003386 case EventEntry::Type::CONFIGURATION_CHANGED:
3387 case EventEntry::Type::DEVICE_RESET: {
3388 LOG_ALWAYS_FATAL("%s events should not go to apps",
Dominik Laskowski75788452021-02-09 18:51:25 -08003389 ftl::enum_string(newEntry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003390 break;
3391 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003392 }
3393
3394 // Remember that we are waiting for this dispatch to complete.
3395 if (dispatchEntry->hasForegroundTarget()) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003396 incrementPendingForegroundDispatches(newEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003397 }
3398
3399 // Enqueue the dispatch entry.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003400 connection->outboundQueue.push_back(dispatchEntry.release());
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003401 traceOutboundQueueLength(*connection);
chaviw8c9cf542019-03-25 13:02:48 -07003402}
3403
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003404/**
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003405 * This function is for debugging and metrics collection. It has two roles.
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003406 *
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003407 * The first role is to log input interaction with windows, which helps determine what the user was
3408 * interacting with. For example, if user is touching launcher, we will see an input_interaction log
3409 * that user started interacting with launcher window, as well as any other window that received
3410 * that gesture, such as the wallpaper or other spy windows. A new input_interaction is only logged
3411 * when the set of tokens that received the event changes. It is not logged again as long as the
3412 * user is interacting with the same windows.
3413 *
3414 * The second role is to track input device activity for metrics collection. For each input event,
3415 * we report the set of UIDs that the input device interacted with to the policy. Unlike for the
3416 * input_interaction logs, the device interaction is reported even when the set of interaction
3417 * tokens do not change.
3418 *
3419 * For these purposes, we do not count ACTION_OUTSIDE, ACTION_UP and ACTION_CANCEL actions as
3420 * interaction. This includes up and cancel events for both keys and motions.
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003421 */
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003422void InputDispatcher::processInteractionsLocked(const EventEntry& entry,
3423 const std::vector<InputTarget>& targets) {
3424 int32_t deviceId;
3425 nsecs_t eventTime;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003426 // Skip ACTION_UP events, and all events other than keys and motions
3427 if (entry.type == EventEntry::Type::KEY) {
3428 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
3429 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
3430 return;
3431 }
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003432 deviceId = keyEntry.deviceId;
3433 eventTime = keyEntry.eventTime;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003434 } else if (entry.type == EventEntry::Type::MOTION) {
3435 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
3436 if (motionEntry.action == AMOTION_EVENT_ACTION_UP ||
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003437 motionEntry.action == AMOTION_EVENT_ACTION_CANCEL ||
3438 MotionEvent::getActionMasked(motionEntry.action) == AMOTION_EVENT_ACTION_POINTER_UP) {
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003439 return;
3440 }
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003441 deviceId = motionEntry.deviceId;
3442 eventTime = motionEntry.eventTime;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003443 } else {
3444 return; // Not a key or a motion
3445 }
3446
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003447 std::set<gui::Uid> interactionUids;
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07003448 std::unordered_set<sp<IBinder>, StrongPointerHash<IBinder>> newConnectionTokens;
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003449 std::vector<std::shared_ptr<Connection>> newConnections;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003450 for (const InputTarget& target : targets) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003451 if (target.flags.test(InputTarget::Flags::DISPATCH_AS_OUTSIDE)) {
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003452 continue; // Skip windows that receive ACTION_OUTSIDE
3453 }
3454
3455 sp<IBinder> token = target.inputChannel->getConnectionToken();
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003456 std::shared_ptr<Connection> connection = getConnectionLocked(token);
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003457 if (connection == nullptr) {
3458 continue;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003459 }
3460 newConnectionTokens.insert(std::move(token));
3461 newConnections.emplace_back(connection);
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003462 if (target.windowHandle) {
3463 interactionUids.emplace(target.windowHandle->getInfo()->ownerUid);
3464 }
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003465 }
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003466
3467 auto command = [this, deviceId, eventTime, uids = std::move(interactionUids)]()
3468 REQUIRES(mLock) {
3469 scoped_unlock unlock(mLock);
3470 mPolicy.notifyDeviceInteraction(deviceId, eventTime, uids);
3471 };
3472 postCommandLocked(std::move(command));
3473
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003474 if (newConnectionTokens == mInteractionConnectionTokens) {
3475 return; // no change
3476 }
3477 mInteractionConnectionTokens = newConnectionTokens;
3478
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003479 std::string targetList;
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003480 for (const std::shared_ptr<Connection>& connection : newConnections) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003481 targetList += connection->getWindowName() + ", ";
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003482 }
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003483 std::string message = "Interaction with: " + targetList;
3484 if (targetList.empty()) {
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003485 message += "<none>";
3486 }
3487 android_log_event_list(LOGTAG_INPUT_INTERACTION) << message << LOG_ID_EVENTS;
3488}
3489
chaviwfd6d3512019-03-25 13:23:49 -07003490void InputDispatcher::dispatchPointerDownOutsideFocus(uint32_t source, int32_t action,
Vishnu Nairad321cd2020-08-20 16:40:21 -07003491 const sp<IBinder>& token) {
chaviw8c9cf542019-03-25 13:02:48 -07003492 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
chaviwfd6d3512019-03-25 13:23:49 -07003493 uint32_t maskedSource = source & AINPUT_SOURCE_CLASS_MASK;
3494 if (maskedSource != AINPUT_SOURCE_CLASS_POINTER || maskedAction != AMOTION_EVENT_ACTION_DOWN) {
chaviw8c9cf542019-03-25 13:02:48 -07003495 return;
3496 }
3497
Vishnu Nairc519ff72021-01-21 08:23:08 -08003498 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07003499 if (focusedToken == token) {
3500 // ignore since token is focused
chaviw8c9cf542019-03-25 13:02:48 -07003501 return;
3502 }
3503
Prabir Pradhancef936d2021-07-21 16:17:52 +00003504 auto command = [this, token]() REQUIRES(mLock) {
3505 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00003506 mPolicy.onPointerDownOutsideFocus(token);
Prabir Pradhancef936d2021-07-21 16:17:52 +00003507 };
3508 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003509}
3510
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003511status_t InputDispatcher::publishMotionEvent(Connection& connection,
3512 DispatchEntry& dispatchEntry) const {
3513 const EventEntry& eventEntry = *(dispatchEntry.eventEntry);
3514 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
3515
3516 PointerCoords scaledCoords[MAX_POINTERS];
3517 const PointerCoords* usingCoords = motionEntry.pointerCoords;
3518
3519 // Set the X and Y offset and X and Y scale depending on the input source.
3520 if ((motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) &&
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003521 !(dispatchEntry.targetFlags.test(InputTarget::Flags::ZERO_COORDS))) {
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003522 float globalScaleFactor = dispatchEntry.globalScaleFactor;
3523 if (globalScaleFactor != 1.0f) {
3524 for (uint32_t i = 0; i < motionEntry.pointerCount; i++) {
3525 scaledCoords[i] = motionEntry.pointerCoords[i];
3526 // Don't apply window scale here since we don't want scale to affect raw
3527 // coordinates. The scale will be sent back to the client and applied
3528 // later when requesting relative coordinates.
Harry Cutts33476232023-01-30 19:57:29 +00003529 scaledCoords[i].scale(globalScaleFactor, /*windowXScale=*/1, /*windowYScale=*/1);
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003530 }
3531 usingCoords = scaledCoords;
3532 }
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003533 } else if (dispatchEntry.targetFlags.test(InputTarget::Flags::ZERO_COORDS)) {
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003534 // We don't want the dispatch target to know the coordinates
3535 for (uint32_t i = 0; i < motionEntry.pointerCount; i++) {
3536 scaledCoords[i].clear();
3537 }
3538 usingCoords = scaledCoords;
3539 }
3540
3541 std::array<uint8_t, 32> hmac = getSignature(motionEntry, dispatchEntry);
3542
3543 // Publish the motion event.
3544 return connection.inputPublisher
3545 .publishMotionEvent(dispatchEntry.seq, dispatchEntry.resolvedEventId,
3546 motionEntry.deviceId, motionEntry.source, motionEntry.displayId,
3547 std::move(hmac), dispatchEntry.resolvedAction,
3548 motionEntry.actionButton, dispatchEntry.resolvedFlags,
3549 motionEntry.edgeFlags, motionEntry.metaState,
3550 motionEntry.buttonState, motionEntry.classification,
3551 dispatchEntry.transform, motionEntry.xPrecision,
3552 motionEntry.yPrecision, motionEntry.xCursorPosition,
3553 motionEntry.yCursorPosition, dispatchEntry.rawTransform,
3554 motionEntry.downTime, motionEntry.eventTime,
3555 motionEntry.pointerCount, motionEntry.pointerProperties,
3556 usingCoords);
3557}
3558
Michael Wrightd02c5b62014-02-10 15:10:22 -08003559void InputDispatcher::startDispatchCycleLocked(nsecs_t currentTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003560 const std::shared_ptr<Connection>& connection) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003561 if (ATRACE_ENABLED()) {
3562 std::string message = StringPrintf("startDispatchCycleLocked(inputChannel=%s)",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003563 connection->getInputChannelName().c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00003564 ATRACE_NAME(message.c_str());
3565 }
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003566 if (DEBUG_DISPATCH_CYCLE) {
3567 ALOGD("channel '%s' ~ startDispatchCycle", connection->getInputChannelName().c_str());
3568 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003569
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003570 while (connection->status == Connection::Status::NORMAL && !connection->outboundQueue.empty()) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003571 DispatchEntry* dispatchEntry = connection->outboundQueue.front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003572 dispatchEntry->deliveryTime = currentTime;
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003573 const std::chrono::nanoseconds timeout = getDispatchingTimeoutLocked(connection);
Siarhei Vishniakou70622952020-07-30 11:17:23 -05003574 dispatchEntry->timeoutTime = currentTime + timeout.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003575
3576 // Publish the event.
3577 status_t status;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003578 const EventEntry& eventEntry = *(dispatchEntry->eventEntry);
3579 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003580 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003581 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
3582 std::array<uint8_t, 32> hmac = getSignature(keyEntry, *dispatchEntry);
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08003583 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
3584 LOG(DEBUG) << "Publishing " << *dispatchEntry << " to "
3585 << connection->getInputChannelName();
3586 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003587
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003588 // Publish the key event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003589 status = connection->inputPublisher
3590 .publishKeyEvent(dispatchEntry->seq,
3591 dispatchEntry->resolvedEventId, keyEntry.deviceId,
3592 keyEntry.source, keyEntry.displayId,
3593 std::move(hmac), dispatchEntry->resolvedAction,
3594 dispatchEntry->resolvedFlags, keyEntry.keyCode,
3595 keyEntry.scanCode, keyEntry.metaState,
3596 keyEntry.repeatCount, keyEntry.downTime,
3597 keyEntry.eventTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003598 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003599 }
3600
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003601 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08003602 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
3603 LOG(DEBUG) << "Publishing " << *dispatchEntry << " to "
3604 << connection->getInputChannelName();
3605 }
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003606 status = publishMotionEvent(*connection, *dispatchEntry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003607 break;
3608 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003609
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003610 case EventEntry::Type::FOCUS: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003611 const FocusEntry& focusEntry = static_cast<const FocusEntry&>(eventEntry);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003612 status = connection->inputPublisher.publishFocusEvent(dispatchEntry->seq,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003613 focusEntry.id,
Antonio Kantek3cfec7b2021-11-05 18:26:17 -07003614 focusEntry.hasFocus);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003615 break;
3616 }
3617
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003618 case EventEntry::Type::TOUCH_MODE_CHANGED: {
3619 const TouchModeEntry& touchModeEntry =
3620 static_cast<const TouchModeEntry&>(eventEntry);
3621 status = connection->inputPublisher
3622 .publishTouchModeEvent(dispatchEntry->seq, touchModeEntry.id,
3623 touchModeEntry.inTouchMode);
3624
3625 break;
3626 }
3627
Prabir Pradhan99987712020-11-10 18:43:05 -08003628 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
3629 const auto& captureEntry =
3630 static_cast<const PointerCaptureChangedEntry&>(eventEntry);
3631 status = connection->inputPublisher
3632 .publishCaptureEvent(dispatchEntry->seq, captureEntry.id,
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00003633 captureEntry.pointerCaptureRequest.enable);
Prabir Pradhan99987712020-11-10 18:43:05 -08003634 break;
3635 }
3636
arthurhungb89ccb02020-12-30 16:19:01 +08003637 case EventEntry::Type::DRAG: {
3638 const DragEntry& dragEntry = static_cast<const DragEntry&>(eventEntry);
3639 status = connection->inputPublisher.publishDragEvent(dispatchEntry->seq,
3640 dragEntry.id, dragEntry.x,
3641 dragEntry.y,
3642 dragEntry.isExiting);
3643 break;
3644 }
3645
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003646 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07003647 case EventEntry::Type::DEVICE_RESET:
3648 case EventEntry::Type::SENSOR: {
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003649 LOG_ALWAYS_FATAL("Should never start dispatch cycles for %s events",
Dominik Laskowski75788452021-02-09 18:51:25 -08003650 ftl::enum_string(eventEntry.type).c_str());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003651 return;
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003652 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003653 }
3654
3655 // Check the result.
3656 if (status) {
3657 if (status == WOULD_BLOCK) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003658 if (connection->waitQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003659 ALOGE("channel '%s' ~ Could not publish event because the pipe is full. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003660 "This is unexpected because the wait queue is empty, so the pipe "
3661 "should be empty and we shouldn't have any problems writing an "
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +00003662 "event to it, status=%s(%d)",
3663 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3664 status);
Harry Cutts33476232023-01-30 19:57:29 +00003665 abortBrokenDispatchCycleLocked(currentTime, connection, /*notify=*/true);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003666 } else {
3667 // Pipe is full and we are waiting for the app to finish process some events
3668 // before sending more events to it.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003669 if (DEBUG_DISPATCH_CYCLE) {
3670 ALOGD("channel '%s' ~ Could not publish event because the pipe is full, "
3671 "waiting for the application to catch up",
3672 connection->getInputChannelName().c_str());
3673 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003674 }
3675 } else {
3676 ALOGE("channel '%s' ~ Could not publish event due to an unexpected error, "
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +00003677 "status=%s(%d)",
3678 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3679 status);
Harry Cutts33476232023-01-30 19:57:29 +00003680 abortBrokenDispatchCycleLocked(currentTime, connection, /*notify=*/true);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003681 }
3682 return;
3683 }
3684
3685 // Re-enqueue the event on the wait queue.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003686 connection->outboundQueue.erase(std::remove(connection->outboundQueue.begin(),
3687 connection->outboundQueue.end(),
3688 dispatchEntry));
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003689 traceOutboundQueueLength(*connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003690 connection->waitQueue.push_back(dispatchEntry);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003691 if (connection->responsive) {
3692 mAnrTracker.insert(dispatchEntry->timeoutTime,
3693 connection->inputChannel->getConnectionToken());
3694 }
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003695 traceWaitQueueLength(*connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003696 }
3697}
3698
chaviw09c8d2d2020-08-24 15:48:26 -07003699std::array<uint8_t, 32> InputDispatcher::sign(const VerifiedInputEvent& event) const {
3700 size_t size;
3701 switch (event.type) {
3702 case VerifiedInputEvent::Type::KEY: {
3703 size = sizeof(VerifiedKeyEvent);
3704 break;
3705 }
3706 case VerifiedInputEvent::Type::MOTION: {
3707 size = sizeof(VerifiedMotionEvent);
3708 break;
3709 }
3710 }
3711 const uint8_t* start = reinterpret_cast<const uint8_t*>(&event);
3712 return mHmacKeyManager.sign(start, size);
3713}
3714
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003715const std::array<uint8_t, 32> InputDispatcher::getSignature(
3716 const MotionEntry& motionEntry, const DispatchEntry& dispatchEntry) const {
Siarhei Vishniakoubf880522023-05-01 11:03:22 -07003717 const int32_t actionMasked = MotionEvent::getActionMasked(dispatchEntry.resolvedAction);
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003718 if (actionMasked != AMOTION_EVENT_ACTION_UP && actionMasked != AMOTION_EVENT_ACTION_DOWN) {
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003719 // Only sign events up and down events as the purely move events
3720 // are tied to their up/down counterparts so signing would be redundant.
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003721 return INVALID_HMAC;
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003722 }
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003723
3724 VerifiedMotionEvent verifiedEvent =
3725 verifiedMotionEventFromMotionEntry(motionEntry, dispatchEntry.rawTransform);
3726 verifiedEvent.actionMasked = actionMasked;
3727 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_MOTION_EVENT_FLAGS;
3728 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003729}
3730
3731const std::array<uint8_t, 32> InputDispatcher::getSignature(
3732 const KeyEntry& keyEntry, const DispatchEntry& dispatchEntry) const {
3733 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEntry(keyEntry);
3734 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_KEY_EVENT_FLAGS;
3735 verifiedEvent.action = dispatchEntry.resolvedAction;
chaviw09c8d2d2020-08-24 15:48:26 -07003736 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003737}
3738
Michael Wrightd02c5b62014-02-10 15:10:22 -08003739void InputDispatcher::finishDispatchCycleLocked(nsecs_t currentTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003740 const std::shared_ptr<Connection>& connection,
3741 uint32_t seq, bool handled, nsecs_t consumeTime) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003742 if (DEBUG_DISPATCH_CYCLE) {
3743 ALOGD("channel '%s' ~ finishDispatchCycle - seq=%u, handled=%s",
3744 connection->getInputChannelName().c_str(), seq, toString(handled));
3745 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003746
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003747 if (connection->status == Connection::Status::BROKEN ||
3748 connection->status == Connection::Status::ZOMBIE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003749 return;
3750 }
3751
3752 // Notify other system components and prepare to start the next dispatch cycle.
Prabir Pradhancef936d2021-07-21 16:17:52 +00003753 auto command = [this, currentTime, connection, seq, handled, consumeTime]() REQUIRES(mLock) {
3754 doDispatchCycleFinishedCommand(currentTime, connection, seq, handled, consumeTime);
3755 };
3756 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003757}
3758
3759void InputDispatcher::abortBrokenDispatchCycleLocked(nsecs_t currentTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003760 const std::shared_ptr<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003761 bool notify) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003762 if (DEBUG_DISPATCH_CYCLE) {
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07003763 LOG(DEBUG) << "channel '" << connection->getInputChannelName() << "'~ " << __func__
3764 << " - notify=" << toString(notify);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003765 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003766
3767 // Clear the dispatch queues.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003768 drainDispatchQueue(connection->outboundQueue);
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003769 traceOutboundQueueLength(*connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003770 drainDispatchQueue(connection->waitQueue);
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003771 traceWaitQueueLength(*connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003772
3773 // The connection appears to be unrecoverably broken.
3774 // Ignore already broken or zombie connections.
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003775 if (connection->status == Connection::Status::NORMAL) {
3776 connection->status = Connection::Status::BROKEN;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003777
3778 if (notify) {
3779 // Notify other system components.
Prabir Pradhancef936d2021-07-21 16:17:52 +00003780 ALOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
3781 connection->getInputChannelName().c_str());
3782
3783 auto command = [this, connection]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00003784 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00003785 mPolicy.notifyInputChannelBroken(connection->inputChannel->getConnectionToken());
Prabir Pradhancef936d2021-07-21 16:17:52 +00003786 };
3787 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003788 }
3789 }
3790}
3791
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003792void InputDispatcher::drainDispatchQueue(std::deque<DispatchEntry*>& queue) {
3793 while (!queue.empty()) {
3794 DispatchEntry* dispatchEntry = queue.front();
3795 queue.pop_front();
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003796 releaseDispatchEntry(dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003797 }
3798}
3799
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003800void InputDispatcher::releaseDispatchEntry(DispatchEntry* dispatchEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003801 if (dispatchEntry->hasForegroundTarget()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003802 decrementPendingForegroundDispatches(*(dispatchEntry->eventEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003803 }
3804 delete dispatchEntry;
3805}
3806
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003807int InputDispatcher::handleReceiveCallback(int events, sp<IBinder> connectionToken) {
3808 std::scoped_lock _l(mLock);
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003809 std::shared_ptr<Connection> connection = getConnectionLocked(connectionToken);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003810 if (connection == nullptr) {
3811 ALOGW("Received looper callback for unknown input channel token %p. events=0x%x",
3812 connectionToken.get(), events);
3813 return 0; // remove the callback
3814 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003815
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003816 bool notify;
3817 if (!(events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP))) {
3818 if (!(events & ALOOPER_EVENT_INPUT)) {
3819 ALOGW("channel '%s' ~ Received spurious callback for unhandled poll event. "
3820 "events=0x%x",
3821 connection->getInputChannelName().c_str(), events);
3822 return 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003823 }
3824
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003825 nsecs_t currentTime = now();
3826 bool gotOne = false;
3827 status_t status = OK;
3828 for (;;) {
3829 Result<InputPublisher::ConsumerResponse> result =
3830 connection->inputPublisher.receiveConsumerResponse();
3831 if (!result.ok()) {
3832 status = result.error().code();
3833 break;
3834 }
3835
3836 if (std::holds_alternative<InputPublisher::Finished>(*result)) {
3837 const InputPublisher::Finished& finish =
3838 std::get<InputPublisher::Finished>(*result);
3839 finishDispatchCycleLocked(currentTime, connection, finish.seq, finish.handled,
3840 finish.consumeTime);
3841 } else if (std::holds_alternative<InputPublisher::Timeline>(*result)) {
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00003842 if (shouldReportMetricsForConnection(*connection)) {
3843 const InputPublisher::Timeline& timeline =
3844 std::get<InputPublisher::Timeline>(*result);
3845 mLatencyTracker
3846 .trackGraphicsLatency(timeline.inputEventId,
3847 connection->inputChannel->getConnectionToken(),
3848 std::move(timeline.graphicsTimeline));
3849 }
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003850 }
3851 gotOne = true;
3852 }
3853 if (gotOne) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00003854 runCommandsLockedInterruptable();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003855 if (status == WOULD_BLOCK) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003856 return 1;
3857 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003858 }
3859
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003860 notify = status != DEAD_OBJECT || !connection->monitor;
3861 if (notify) {
3862 ALOGE("channel '%s' ~ Failed to receive finished signal. status=%s(%d)",
3863 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3864 status);
3865 }
3866 } else {
3867 // Monitor channels are never explicitly unregistered.
3868 // We do it automatically when the remote endpoint is closed so don't warn about them.
3869 const bool stillHaveWindowHandle =
3870 getWindowHandleLocked(connection->inputChannel->getConnectionToken()) != nullptr;
3871 notify = !connection->monitor && stillHaveWindowHandle;
3872 if (notify) {
3873 ALOGW("channel '%s' ~ Consumer closed input channel or an error occurred. events=0x%x",
3874 connection->getInputChannelName().c_str(), events);
3875 }
3876 }
3877
3878 // Remove the channel.
3879 removeInputChannelLocked(connection->inputChannel->getConnectionToken(), notify);
3880 return 0; // remove the callback
Michael Wrightd02c5b62014-02-10 15:10:22 -08003881}
3882
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003883void InputDispatcher::synthesizeCancelationEventsForAllConnectionsLocked(
Michael Wrightd02c5b62014-02-10 15:10:22 -08003884 const CancelationOptions& options) {
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003885 for (const auto& [token, connection] : mConnectionsByToken) {
Siarhei Vishniakou2e2ea992020-12-15 02:57:19 +00003886 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003887 }
3888}
3889
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003890void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
Michael Wrightfa13dcf2015-06-12 13:25:11 +01003891 const CancelationOptions& options) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08003892 for (const auto& [_, monitors] : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003893 for (const Monitor& monitor : monitors) {
3894 synthesizeCancelationEventsForInputChannelLocked(monitor.inputChannel, options);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003895 }
Michael Wrightfa13dcf2015-06-12 13:25:11 +01003896 }
3897}
3898
Michael Wrightd02c5b62014-02-10 15:10:22 -08003899void InputDispatcher::synthesizeCancelationEventsForInputChannelLocked(
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05003900 const std::shared_ptr<InputChannel>& channel, const CancelationOptions& options) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003901 std::shared_ptr<Connection> connection = getConnectionLocked(channel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003902 if (connection == nullptr) {
3903 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003904 }
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003905
3906 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003907}
3908
3909void InputDispatcher::synthesizeCancelationEventsForConnectionLocked(
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003910 const std::shared_ptr<Connection>& connection, const CancelationOptions& options) {
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003911 if (connection->status == Connection::Status::BROKEN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003912 return;
3913 }
3914
3915 nsecs_t currentTime = now();
3916
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003917 std::vector<std::unique_ptr<EventEntry>> cancelationEvents =
Siarhei Vishniakou00fca7c2019-10-29 13:05:57 -07003918 connection->inputState.synthesizeCancelationEvents(currentTime, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003919
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003920 if (cancelationEvents.empty()) {
3921 return;
3922 }
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003923 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
3924 ALOGD("channel '%s' ~ Synthesized %zu cancelation events to bring channel back in sync "
Siarhei Vishniakou2e3e4432023-02-09 18:34:11 -08003925 "with reality: %s, mode=%s.",
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003926 connection->getInputChannelName().c_str(), cancelationEvents.size(), options.reason,
Siarhei Vishniakou2e3e4432023-02-09 18:34:11 -08003927 ftl::enum_string(options.mode).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003928 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08003929
Arthur Hungb3307ee2021-10-14 10:57:37 +00003930 std::string reason = std::string("reason=").append(options.reason);
3931 android_log_event_list(LOGTAG_INPUT_CANCEL)
3932 << connection->getInputChannelName().c_str() << reason << LOG_ID_EVENTS;
3933
Svet Ganov5d3bc372020-01-26 23:11:07 -08003934 InputTarget target;
chaviw98318de2021-05-19 16:45:23 -05003935 sp<WindowInfoHandle> windowHandle =
Svet Ganov5d3bc372020-01-26 23:11:07 -08003936 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
3937 if (windowHandle != nullptr) {
chaviw98318de2021-05-19 16:45:23 -05003938 const WindowInfo* windowInfo = windowHandle->getInfo();
chaviw1ff3d1e2020-07-01 15:53:47 -07003939 target.setDefaultPointerTransform(windowInfo->transform);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003940 target.globalScaleFactor = windowInfo->globalScaleFactor;
3941 }
3942 target.inputChannel = connection->inputChannel;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003943 target.flags = InputTarget::Flags::DISPATCH_AS_IS;
Svet Ganov5d3bc372020-01-26 23:11:07 -08003944
hongzuo liu95785e22022-09-06 02:51:35 +00003945 const bool wasEmpty = connection->outboundQueue.empty();
3946
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003947 for (size_t i = 0; i < cancelationEvents.size(); i++) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003948 std::unique_ptr<EventEntry> cancelationEventEntry = std::move(cancelationEvents[i]);
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003949 switch (cancelationEventEntry->type) {
3950 case EventEntry::Type::KEY: {
3951 logOutboundKeyDetails("cancel - ",
3952 static_cast<const KeyEntry&>(*cancelationEventEntry));
3953 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003954 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003955 case EventEntry::Type::MOTION: {
3956 logOutboundMotionDetails("cancel - ",
3957 static_cast<const MotionEntry&>(*cancelationEventEntry));
3958 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003959 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003960 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003961 case EventEntry::Type::TOUCH_MODE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08003962 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
3963 case EventEntry::Type::DRAG: {
Prabir Pradhan99987712020-11-10 18:43:05 -08003964 LOG_ALWAYS_FATAL("Canceling %s events is not supported",
Dominik Laskowski75788452021-02-09 18:51:25 -08003965 ftl::enum_string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003966 break;
3967 }
3968 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07003969 case EventEntry::Type::DEVICE_RESET:
3970 case EventEntry::Type::SENSOR: {
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003971 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Dominik Laskowski75788452021-02-09 18:51:25 -08003972 ftl::enum_string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003973 break;
3974 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003975 }
3976
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003977 enqueueDispatchEntryLocked(connection, std::move(cancelationEventEntry), target,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003978 InputTarget::Flags::DISPATCH_AS_IS);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003979 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003980
hongzuo liu95785e22022-09-06 02:51:35 +00003981 // If the outbound queue was previously empty, start the dispatch cycle going.
3982 if (wasEmpty && !connection->outboundQueue.empty()) {
3983 startDispatchCycleLocked(currentTime, connection);
3984 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003985}
3986
Svet Ganov5d3bc372020-01-26 23:11:07 -08003987void InputDispatcher::synthesizePointerDownEventsForConnectionLocked(
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003988 const nsecs_t downTime, const std::shared_ptr<Connection>& connection,
Arthur Hungc539dbb2022-12-08 07:45:36 +00003989 ftl::Flags<InputTarget::Flags> targetFlags) {
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003990 if (connection->status == Connection::Status::BROKEN) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003991 return;
3992 }
3993
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003994 std::vector<std::unique_ptr<EventEntry>> downEvents =
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00003995 connection->inputState.synthesizePointerDownEvents(downTime);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003996
3997 if (downEvents.empty()) {
3998 return;
3999 }
4000
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004001 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08004002 ALOGD("channel '%s' ~ Synthesized %zu down events to ensure consistent event stream.",
4003 connection->getInputChannelName().c_str(), downEvents.size());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004004 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08004005
4006 InputTarget target;
chaviw98318de2021-05-19 16:45:23 -05004007 sp<WindowInfoHandle> windowHandle =
Svet Ganov5d3bc372020-01-26 23:11:07 -08004008 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
4009 if (windowHandle != nullptr) {
chaviw98318de2021-05-19 16:45:23 -05004010 const WindowInfo* windowInfo = windowHandle->getInfo();
chaviw1ff3d1e2020-07-01 15:53:47 -07004011 target.setDefaultPointerTransform(windowInfo->transform);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004012 target.globalScaleFactor = windowInfo->globalScaleFactor;
4013 }
4014 target.inputChannel = connection->inputChannel;
Arthur Hungc539dbb2022-12-08 07:45:36 +00004015 target.flags = targetFlags;
Svet Ganov5d3bc372020-01-26 23:11:07 -08004016
hongzuo liu95785e22022-09-06 02:51:35 +00004017 const bool wasEmpty = connection->outboundQueue.empty();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004018 for (std::unique_ptr<EventEntry>& downEventEntry : downEvents) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08004019 switch (downEventEntry->type) {
4020 case EventEntry::Type::MOTION: {
4021 logOutboundMotionDetails("down - ",
4022 static_cast<const MotionEntry&>(*downEventEntry));
4023 break;
4024 }
4025
4026 case EventEntry::Type::KEY:
4027 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07004028 case EventEntry::Type::TOUCH_MODE_CHANGED:
Svet Ganov5d3bc372020-01-26 23:11:07 -08004029 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08004030 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07004031 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08004032 case EventEntry::Type::SENSOR:
4033 case EventEntry::Type::DRAG: {
Svet Ganov5d3bc372020-01-26 23:11:07 -08004034 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Dominik Laskowski75788452021-02-09 18:51:25 -08004035 ftl::enum_string(downEventEntry->type).c_str());
Svet Ganov5d3bc372020-01-26 23:11:07 -08004036 break;
4037 }
4038 }
4039
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004040 enqueueDispatchEntryLocked(connection, std::move(downEventEntry), target,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08004041 InputTarget::Flags::DISPATCH_AS_IS);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004042 }
4043
hongzuo liu95785e22022-09-06 02:51:35 +00004044 // If the outbound queue was previously empty, start the dispatch cycle going.
4045 if (wasEmpty && !connection->outboundQueue.empty()) {
4046 startDispatchCycleLocked(downTime, connection);
4047 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08004048}
4049
Arthur Hungc539dbb2022-12-08 07:45:36 +00004050void InputDispatcher::synthesizeCancelationEventsForWindowLocked(
4051 const sp<WindowInfoHandle>& windowHandle, const CancelationOptions& options) {
4052 if (windowHandle != nullptr) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07004053 std::shared_ptr<Connection> wallpaperConnection =
4054 getConnectionLocked(windowHandle->getToken());
Arthur Hungc539dbb2022-12-08 07:45:36 +00004055 if (wallpaperConnection != nullptr) {
4056 synthesizeCancelationEventsForConnectionLocked(wallpaperConnection, options);
4057 }
4058 }
4059}
4060
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004061std::unique_ptr<MotionEntry> InputDispatcher::splitMotionEvent(
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08004062 const MotionEntry& originalMotionEntry, std::bitset<MAX_POINTER_ID + 1> pointerIds,
4063 nsecs_t splitDownTime) {
4064 ALOG_ASSERT(pointerIds.any());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004065
4066 uint32_t splitPointerIndexMap[MAX_POINTERS];
4067 PointerProperties splitPointerProperties[MAX_POINTERS];
4068 PointerCoords splitPointerCoords[MAX_POINTERS];
4069
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07004070 uint32_t originalPointerCount = originalMotionEntry.pointerCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004071 uint32_t splitPointerCount = 0;
4072
4073 for (uint32_t originalPointerIndex = 0; originalPointerIndex < originalPointerCount;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004074 originalPointerIndex++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004075 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07004076 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08004077 uint32_t pointerId = uint32_t(pointerProperties.id);
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08004078 if (pointerIds.test(pointerId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004079 splitPointerIndexMap[splitPointerCount] = originalPointerIndex;
Siarhei Vishniakou73e6d372023-07-06 18:07:21 -07004080 splitPointerProperties[splitPointerCount] = pointerProperties;
4081 splitPointerCoords[splitPointerCount] =
4082 originalMotionEntry.pointerCoords[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08004083 splitPointerCount += 1;
4084 }
4085 }
4086
4087 if (splitPointerCount != pointerIds.count()) {
4088 // This is bad. We are missing some of the pointers that we expected to deliver.
4089 // Most likely this indicates that we received an ACTION_MOVE events that has
4090 // different pointer ids than we expected based on the previous ACTION_DOWN
4091 // or ACTION_POINTER_DOWN events that caused us to decide to split the pointers
4092 // in this way.
4093 ALOGW("Dropping split motion event because the pointer count is %d but "
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08004094 "we expected there to be %zu pointers. This probably means we received "
Siarhei Vishniakou16e4fa02023-02-16 17:48:56 -08004095 "a broken sequence of pointer ids from the input device: %s",
4096 splitPointerCount, pointerIds.count(), originalMotionEntry.getDescription().c_str());
Yi Kong9b14ac62018-07-17 13:48:38 -07004097 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004098 }
4099
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07004100 int32_t action = originalMotionEntry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004101 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004102 if (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN ||
4103 maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
Siarhei Vishniakou5b9766d2023-07-18 14:06:29 -07004104 int32_t originalPointerIndex = MotionEvent::getActionIndex(action);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004105 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07004106 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08004107 uint32_t pointerId = uint32_t(pointerProperties.id);
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08004108 if (pointerIds.test(pointerId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004109 if (pointerIds.count() == 1) {
4110 // The first/last pointer went down/up.
4111 action = maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004112 ? AMOTION_EVENT_ACTION_DOWN
arthurhungea3f4fc2020-12-21 23:18:53 +08004113 : (originalMotionEntry.flags & AMOTION_EVENT_FLAG_CANCELED) != 0
4114 ? AMOTION_EVENT_ACTION_CANCEL
4115 : AMOTION_EVENT_ACTION_UP;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004116 } else {
4117 // A secondary pointer went down/up.
4118 uint32_t splitPointerIndex = 0;
4119 while (pointerId != uint32_t(splitPointerProperties[splitPointerIndex].id)) {
4120 splitPointerIndex += 1;
4121 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004122 action = maskedAction |
4123 (splitPointerIndex << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004124 }
4125 } else {
4126 // An unrelated pointer changed.
4127 action = AMOTION_EVENT_ACTION_MOVE;
4128 }
4129 }
4130
Siarhei Vishniakou59e302b2023-06-05 08:04:53 -07004131 if (action == AMOTION_EVENT_ACTION_DOWN && splitDownTime != originalMotionEntry.eventTime) {
4132 logDispatchStateLocked();
4133 LOG_ALWAYS_FATAL("Split motion event has mismatching downTime and eventTime for "
4134 "ACTION_DOWN, motionEntry=%s, splitDownTime=%" PRId64,
4135 originalMotionEntry.getDescription().c_str(), splitDownTime);
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00004136 }
4137
Garfield Tanff1f1bb2020-01-28 13:24:04 -08004138 int32_t newId = mIdGenerator.nextId();
4139 if (ATRACE_ENABLED()) {
4140 std::string message = StringPrintf("Split MotionEvent(id=0x%" PRIx32
4141 ") to MotionEvent(id=0x%" PRIx32 ").",
4142 originalMotionEntry.id, newId);
4143 ATRACE_NAME(message.c_str());
4144 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004145 std::unique_ptr<MotionEntry> splitMotionEntry =
4146 std::make_unique<MotionEntry>(newId, originalMotionEntry.eventTime,
4147 originalMotionEntry.deviceId, originalMotionEntry.source,
4148 originalMotionEntry.displayId,
4149 originalMotionEntry.policyFlags, action,
4150 originalMotionEntry.actionButton,
4151 originalMotionEntry.flags, originalMotionEntry.metaState,
4152 originalMotionEntry.buttonState,
4153 originalMotionEntry.classification,
4154 originalMotionEntry.edgeFlags,
4155 originalMotionEntry.xPrecision,
4156 originalMotionEntry.yPrecision,
4157 originalMotionEntry.xCursorPosition,
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00004158 originalMotionEntry.yCursorPosition, splitDownTime,
4159 splitPointerCount, splitPointerProperties,
4160 splitPointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004161
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07004162 if (originalMotionEntry.injectionState) {
4163 splitMotionEntry->injectionState = originalMotionEntry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004164 splitMotionEntry->injectionState->refCount += 1;
4165 }
4166
4167 return splitMotionEntry;
4168}
4169
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004170void InputDispatcher::notifyConfigurationChanged(const NotifyConfigurationChangedArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004171 if (debugInboundEventDetails()) {
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004172 ALOGD("notifyConfigurationChanged - eventTime=%" PRId64, args.eventTime);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004173 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004174
Antonio Kantekf16f2832021-09-28 04:39:20 +00004175 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004176 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004177 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004178
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004179 std::unique_ptr<ConfigurationChangedEntry> newEntry =
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004180 std::make_unique<ConfigurationChangedEntry>(args.id, args.eventTime);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004181 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004182 } // release lock
4183
4184 if (needWake) {
4185 mLooper->wake();
4186 }
4187}
4188
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05004189/**
4190 * If one of the meta shortcuts is detected, process them here:
Vaibhav Devmurari34cd5b02023-02-23 14:51:18 +00004191 * Meta + Backspace; Meta + Grave; Meta + Left arrow -> generate BACK
4192 * Most System shortcuts are handled in PhoneWindowManager.java except 'Back' shortcuts. Unlike
4193 * Back, other shortcuts DO NOT need to be sent to applications and are fully handled by the system.
4194 * But for Back key and Back shortcuts, we need to send KEYCODE_BACK to applications which can
4195 * potentially handle the back key presses.
4196 * Note: We don't send any Meta based KeyEvents to applications, so we need to convert to a KeyEvent
4197 * where meta modifier is off before sending. Currently only use case is 'Back'.
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05004198 */
4199void InputDispatcher::accelerateMetaShortcuts(const int32_t deviceId, const int32_t action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004200 int32_t& keyCode, int32_t& metaState) {
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05004201 if (metaState & AMETA_META_ON && action == AKEY_EVENT_ACTION_DOWN) {
4202 int32_t newKeyCode = AKEYCODE_UNKNOWN;
Vaibhav Devmurari34cd5b02023-02-23 14:51:18 +00004203 if (keyCode == AKEYCODE_DEL || keyCode == AKEYCODE_GRAVE || keyCode == AKEYCODE_DPAD_LEFT) {
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05004204 newKeyCode = AKEYCODE_BACK;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05004205 }
4206 if (newKeyCode != AKEYCODE_UNKNOWN) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004207 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05004208 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004209 mReplacedKeys[replacement] = newKeyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05004210 keyCode = newKeyCode;
4211 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
4212 }
4213 } else if (action == AKEY_EVENT_ACTION_UP) {
4214 // In order to maintain a consistent stream of up and down events, check to see if the key
4215 // going up is one we've replaced in a down event and haven't yet replaced in an up event,
4216 // even if the modifier was released between the down and the up events.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004217 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05004218 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004219 auto replacementIt = mReplacedKeys.find(replacement);
4220 if (replacementIt != mReplacedKeys.end()) {
4221 keyCode = replacementIt->second;
4222 mReplacedKeys.erase(replacementIt);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05004223 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
4224 }
4225 }
4226}
4227
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004228void InputDispatcher::notifyKey(const NotifyKeyArgs& args) {
Prabir Pradhan96282b02023-02-24 22:36:17 +00004229 ALOGD_IF(debugInboundEventDetails(),
4230 "notifyKey - id=%" PRIx32 ", eventTime=%" PRId64
4231 ", deviceId=%d, source=%s, displayId=%" PRId32
4232 "policyFlags=0x%x, action=%s, flags=0x%x, keyCode=%s, scanCode=0x%x, metaState=0x%x, "
4233 "downTime=%" PRId64,
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004234 args.id, args.eventTime, args.deviceId, inputEventSourceToString(args.source).c_str(),
4235 args.displayId, args.policyFlags, KeyEvent::actionToString(args.action), args.flags,
4236 KeyEvent::getLabel(args.keyCode), args.scanCode, args.metaState, args.downTime);
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004237 Result<void> keyCheck = validateKeyEvent(args.action);
4238 if (!keyCheck.ok()) {
4239 LOG(ERROR) << "invalid key event: " << keyCheck.error();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004240 return;
4241 }
4242
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004243 uint32_t policyFlags = args.policyFlags;
4244 int32_t flags = args.flags;
4245 int32_t metaState = args.metaState;
Siarhei Vishniakou622bd322018-10-29 18:02:27 -07004246 // InputDispatcher tracks and generates key repeats on behalf of
4247 // whatever notifies it, so repeatCount should always be set to 0
4248 constexpr int32_t repeatCount = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004249 if ((policyFlags & POLICY_FLAG_VIRTUAL) || (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY)) {
4250 policyFlags |= POLICY_FLAG_VIRTUAL;
4251 flags |= AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
4252 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004253 if (policyFlags & POLICY_FLAG_FUNCTION) {
4254 metaState |= AMETA_FUNCTION_ON;
4255 }
4256
4257 policyFlags |= POLICY_FLAG_TRUSTED;
4258
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004259 int32_t keyCode = args.keyCode;
4260 accelerateMetaShortcuts(args.deviceId, args.action, keyCode, metaState);
Michael Wright78f24442014-08-06 15:55:28 -07004261
Michael Wrightd02c5b62014-02-10 15:10:22 -08004262 KeyEvent event;
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004263 event.initialize(args.id, args.deviceId, args.source, args.displayId, INVALID_HMAC, args.action,
4264 flags, keyCode, args.scanCode, metaState, repeatCount, args.downTime,
4265 args.eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004266
Michael Wright2b3c3302018-03-02 17:19:13 +00004267 android::base::Timer t;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004268 mPolicy.interceptKeyBeforeQueueing(event, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00004269 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4270 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004271 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00004272 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004273
Antonio Kantekf16f2832021-09-28 04:39:20 +00004274 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004275 { // acquire lock
4276 mLock.lock();
4277
4278 if (shouldSendKeyToInputFilterLocked(args)) {
4279 mLock.unlock();
4280
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004281 policyFlags |= POLICY_FLAG_FILTERED;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004282 if (!mPolicy.filterInputEvent(event, policyFlags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004283 return; // event was consumed by the filter
4284 }
4285
4286 mLock.lock();
4287 }
4288
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004289 std::unique_ptr<KeyEntry> newEntry =
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004290 std::make_unique<KeyEntry>(args.id, args.eventTime, args.deviceId, args.source,
4291 args.displayId, policyFlags, args.action, flags, keyCode,
4292 args.scanCode, metaState, repeatCount, args.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004293
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004294 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004295 mLock.unlock();
4296 } // release lock
4297
4298 if (needWake) {
4299 mLooper->wake();
4300 }
4301}
4302
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004303bool InputDispatcher::shouldSendKeyToInputFilterLocked(const NotifyKeyArgs& args) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004304 return mInputFilterEnabled;
4305}
4306
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004307void InputDispatcher::notifyMotion(const NotifyMotionArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004308 if (debugInboundEventDetails()) {
Prabir Pradhan96282b02023-02-24 22:36:17 +00004309 ALOGD("notifyMotion - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=%s, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004310 "displayId=%" PRId32 ", policyFlags=0x%x, "
Siarhei Vishniakou6ebd0692022-10-20 15:05:45 -07004311 "action=%s, actionButton=0x%x, flags=0x%x, metaState=0x%x, buttonState=0x%x, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004312 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, xCursorPosition=%f, "
4313 "yCursorPosition=%f, downTime=%" PRId64,
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004314 args.id, args.eventTime, args.deviceId, inputEventSourceToString(args.source).c_str(),
4315 args.displayId, args.policyFlags, MotionEvent::actionToString(args.action).c_str(),
4316 args.actionButton, args.flags, args.metaState, args.buttonState, args.edgeFlags,
4317 args.xPrecision, args.yPrecision, args.xCursorPosition, args.yCursorPosition,
4318 args.downTime);
Siarhei Vishniakou3218fc02023-06-15 20:41:02 -07004319 for (uint32_t i = 0; i < args.getPointerCount(); i++) {
Prabir Pradhan96282b02023-02-24 22:36:17 +00004320 ALOGD(" Pointer %d: id=%d, toolType=%s, x=%f, y=%f, pressure=%f, size=%f, "
4321 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, orientation=%f",
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004322 i, args.pointerProperties[i].id,
4323 ftl::enum_string(args.pointerProperties[i].toolType).c_str(),
4324 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
4325 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
4326 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
4327 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
4328 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
4329 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
4330 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
4331 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
4332 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004333 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004334 }
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004335
Siarhei Vishniakou3218fc02023-06-15 20:41:02 -07004336 Result<void> motionCheck =
4337 validateMotionEvent(args.action, args.actionButton, args.getPointerCount(),
4338 args.pointerProperties.data());
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004339 if (!motionCheck.ok()) {
4340 LOG(FATAL) << "Invalid event: " << args.dump() << "; reason: " << motionCheck.error();
4341 return;
4342 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004343
Siarhei Vishniakou5c02a712023-05-15 15:45:02 -07004344 if (DEBUG_VERIFY_EVENTS) {
4345 auto [it, _] =
4346 mVerifiersByDisplay.try_emplace(args.displayId,
4347 StringPrintf("display %" PRId32, args.displayId));
4348 Result<void> result =
Siarhei Vishniakou3218fc02023-06-15 20:41:02 -07004349 it->second.processMovement(args.deviceId, args.action, args.getPointerCount(),
4350 args.pointerProperties.data(), args.pointerCoords.data(),
4351 args.flags);
Siarhei Vishniakou5c02a712023-05-15 15:45:02 -07004352 if (!result.ok()) {
4353 LOG(FATAL) << "Bad stream: " << result.error() << " caused by " << args.dump();
4354 }
4355 }
4356
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004357 uint32_t policyFlags = args.policyFlags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004358 policyFlags |= POLICY_FLAG_TRUSTED;
Michael Wright2b3c3302018-03-02 17:19:13 +00004359
4360 android::base::Timer t;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004361 mPolicy.interceptMotionBeforeQueueing(args.displayId, args.eventTime, policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00004362 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4363 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004364 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00004365 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004366
Antonio Kantekf16f2832021-09-28 04:39:20 +00004367 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004368 { // acquire lock
4369 mLock.lock();
Siarhei Vishniakou5bf25d92023-02-08 15:43:38 -08004370 if (!(policyFlags & POLICY_FLAG_PASS_TO_USER)) {
4371 // Set the flag anyway if we already have an ongoing gesture. That would allow us to
4372 // complete the processing of the current stroke.
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004373 const auto touchStateIt = mTouchStatesByDisplay.find(args.displayId);
Siarhei Vishniakou5bf25d92023-02-08 15:43:38 -08004374 if (touchStateIt != mTouchStatesByDisplay.end()) {
4375 const TouchState& touchState = touchStateIt->second;
Siarhei Vishniakou45504fe2023-05-05 16:05:10 -07004376 if (touchState.hasTouchingPointers(args.deviceId)) {
Siarhei Vishniakou5bf25d92023-02-08 15:43:38 -08004377 policyFlags |= POLICY_FLAG_PASS_TO_USER;
4378 }
4379 }
4380 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004381
4382 if (shouldSendMotionToInputFilterLocked(args)) {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004383 ui::Transform displayTransform;
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004384 if (const auto it = mDisplayInfos.find(args.displayId); it != mDisplayInfos.end()) {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004385 displayTransform = it->second.transform;
4386 }
4387
Michael Wrightd02c5b62014-02-10 15:10:22 -08004388 mLock.unlock();
4389
4390 MotionEvent event;
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004391 event.initialize(args.id, args.deviceId, args.source, args.displayId, INVALID_HMAC,
4392 args.action, args.actionButton, args.flags, args.edgeFlags,
4393 args.metaState, args.buttonState, args.classification,
4394 displayTransform, args.xPrecision, args.yPrecision,
4395 args.xCursorPosition, args.yCursorPosition, displayTransform,
Siarhei Vishniakou3218fc02023-06-15 20:41:02 -07004396 args.downTime, args.eventTime, args.getPointerCount(),
4397 args.pointerProperties.data(), args.pointerCoords.data());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004398
4399 policyFlags |= POLICY_FLAG_FILTERED;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004400 if (!mPolicy.filterInputEvent(event, policyFlags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004401 return; // event was consumed by the filter
4402 }
4403
4404 mLock.lock();
4405 }
4406
4407 // Just enqueue a new motion event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004408 std::unique_ptr<MotionEntry> newEntry =
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004409 std::make_unique<MotionEntry>(args.id, args.eventTime, args.deviceId, args.source,
4410 args.displayId, policyFlags, args.action,
4411 args.actionButton, args.flags, args.metaState,
4412 args.buttonState, args.classification, args.edgeFlags,
4413 args.xPrecision, args.yPrecision,
4414 args.xCursorPosition, args.yCursorPosition,
Siarhei Vishniakou3218fc02023-06-15 20:41:02 -07004415 args.downTime, args.getPointerCount(),
4416 args.pointerProperties.data(),
4417 args.pointerCoords.data());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004418
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004419 if (args.id != android::os::IInputConstants::INVALID_INPUT_EVENT_ID &&
4420 IdGenerator::getSource(args.id) == IdGenerator::Source::INPUT_READER &&
Siarhei Vishniakou363e7292021-07-09 03:22:42 +00004421 !mInputFilterEnabled) {
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004422 const bool isDown = args.action == AMOTION_EVENT_ACTION_DOWN;
4423 mLatencyTracker.trackListener(args.id, isDown, args.eventTime, args.readTime);
Siarhei Vishniakou363e7292021-07-09 03:22:42 +00004424 }
4425
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004426 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004427 mLock.unlock();
4428 } // release lock
4429
4430 if (needWake) {
4431 mLooper->wake();
4432 }
4433}
4434
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004435void InputDispatcher::notifySensor(const NotifySensorArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004436 if (debugInboundEventDetails()) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004437 ALOGD("notifySensor - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=0x%x, "
4438 " sensorType=%s",
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004439 args.id, args.eventTime, args.deviceId, args.source,
4440 ftl::enum_string(args.sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004441 }
Chris Yef59a2f42020-10-16 12:55:26 -07004442
Antonio Kantekf16f2832021-09-28 04:39:20 +00004443 bool needWake = false;
Chris Yef59a2f42020-10-16 12:55:26 -07004444 { // acquire lock
4445 mLock.lock();
4446
4447 // Just enqueue a new sensor event.
4448 std::unique_ptr<SensorEntry> newEntry =
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004449 std::make_unique<SensorEntry>(args.id, args.eventTime, args.deviceId, args.source,
4450 /* policyFlags=*/0, args.hwTimestamp, args.sensorType,
4451 args.accuracy, args.accuracyChanged, args.values);
Chris Yef59a2f42020-10-16 12:55:26 -07004452
4453 needWake = enqueueInboundEventLocked(std::move(newEntry));
4454 mLock.unlock();
4455 } // release lock
4456
4457 if (needWake) {
4458 mLooper->wake();
4459 }
4460}
4461
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004462void InputDispatcher::notifyVibratorState(const NotifyVibratorStateArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004463 if (debugInboundEventDetails()) {
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004464 ALOGD("notifyVibratorState - eventTime=%" PRId64 ", device=%d, isOn=%d", args.eventTime,
4465 args.deviceId, args.isOn);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004466 }
Prabir Pradhana41d2442023-04-20 21:30:40 +00004467 mPolicy.notifyVibratorState(args.deviceId, args.isOn);
Chris Yefb552902021-02-03 17:18:37 -08004468}
4469
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004470bool InputDispatcher::shouldSendMotionToInputFilterLocked(const NotifyMotionArgs& args) {
Jackal Guof9696682018-10-05 12:23:23 +08004471 return mInputFilterEnabled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004472}
4473
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004474void InputDispatcher::notifySwitch(const NotifySwitchArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004475 if (debugInboundEventDetails()) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004476 ALOGD("notifySwitch - eventTime=%" PRId64 ", policyFlags=0x%x, switchValues=0x%08x, "
4477 "switchMask=0x%08x",
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004478 args.eventTime, args.policyFlags, args.switchValues, args.switchMask);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004479 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004480
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004481 uint32_t policyFlags = args.policyFlags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004482 policyFlags |= POLICY_FLAG_TRUSTED;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004483 mPolicy.notifySwitch(args.eventTime, args.switchValues, args.switchMask, policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004484}
4485
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004486void InputDispatcher::notifyDeviceReset(const NotifyDeviceResetArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004487 if (debugInboundEventDetails()) {
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004488 ALOGD("notifyDeviceReset - eventTime=%" PRId64 ", deviceId=%d", args.eventTime,
4489 args.deviceId);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004490 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004491
Antonio Kantekf16f2832021-09-28 04:39:20 +00004492 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004493 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004494 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004495
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004496 std::unique_ptr<DeviceResetEntry> newEntry =
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004497 std::make_unique<DeviceResetEntry>(args.id, args.eventTime, args.deviceId);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004498 needWake = enqueueInboundEventLocked(std::move(newEntry));
Siarhei Vishniakou1160ecd2023-06-28 15:57:47 -07004499
4500 for (auto& [_, verifier] : mVerifiersByDisplay) {
4501 verifier.resetDevice(args.deviceId);
4502 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004503 } // release lock
4504
4505 if (needWake) {
4506 mLooper->wake();
4507 }
4508}
4509
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004510void InputDispatcher::notifyPointerCaptureChanged(const NotifyPointerCaptureChangedArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004511 if (debugInboundEventDetails()) {
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004512 ALOGD("notifyPointerCaptureChanged - eventTime=%" PRId64 ", enabled=%s", args.eventTime,
4513 args.request.enable ? "true" : "false");
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004514 }
Prabir Pradhan7e186182020-11-10 13:56:45 -08004515
Antonio Kantekf16f2832021-09-28 04:39:20 +00004516 bool needWake = false;
Prabir Pradhan99987712020-11-10 18:43:05 -08004517 { // acquire lock
4518 std::scoped_lock _l(mLock);
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004519 auto entry =
4520 std::make_unique<PointerCaptureChangedEntry>(args.id, args.eventTime, args.request);
Prabir Pradhan99987712020-11-10 18:43:05 -08004521 needWake = enqueueInboundEventLocked(std::move(entry));
4522 } // release lock
4523
4524 if (needWake) {
4525 mLooper->wake();
4526 }
Prabir Pradhan7e186182020-11-10 13:56:45 -08004527}
4528
Prabir Pradhan5735a322022-04-11 17:23:34 +00004529InputEventInjectionResult InputDispatcher::injectInputEvent(const InputEvent* event,
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00004530 std::optional<gui::Uid> targetUid,
Prabir Pradhan5735a322022-04-11 17:23:34 +00004531 InputEventInjectionSync syncMode,
4532 std::chrono::milliseconds timeout,
4533 uint32_t policyFlags) {
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004534 Result<void> eventValidation = validateInputEvent(*event);
4535 if (!eventValidation.ok()) {
4536 LOG(INFO) << "Injection failed: invalid event: " << eventValidation.error();
4537 return InputEventInjectionResult::FAILED;
4538 }
4539
Prabir Pradhan65613802023-02-22 23:36:58 +00004540 if (debugInboundEventDetails()) {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00004541 LOG(DEBUG) << __func__ << ": targetUid=" << toString(targetUid, &uidString)
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004542 << ", syncMode=" << ftl::enum_string(syncMode) << ", timeout=" << timeout.count()
4543 << "ms, policyFlags=0x" << std::hex << policyFlags << std::dec
4544 << ", event=" << *event;
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004545 }
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07004546 nsecs_t endTime = now() + std::chrono::duration_cast<std::chrono::nanoseconds>(timeout).count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004547
Prabir Pradhan5735a322022-04-11 17:23:34 +00004548 policyFlags |= POLICY_FLAG_INJECTED | POLICY_FLAG_TRUSTED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004549
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004550 // For all injected events, set device id = VIRTUAL_KEYBOARD_ID. The only exception is events
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004551 // that have gone through the InputFilter. If the event passed through the InputFilter, assign
4552 // the provided device id. If the InputFilter is accessibility, and it modifies or synthesizes
4553 // the injected event, it is responsible for setting POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY.
4554 // For those events, we will set FLAG_IS_ACCESSIBILITY_EVENT to allow apps to distinguish them
4555 // from events that originate from actual hardware.
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004556 int32_t resolvedDeviceId = VIRTUAL_KEYBOARD_ID;
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004557 if (policyFlags & POLICY_FLAG_FILTERED) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004558 resolvedDeviceId = event->getDeviceId();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004559 }
4560
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004561 std::queue<std::unique_ptr<EventEntry>> injectedEntries;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004562 switch (event->getType()) {
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004563 case InputEventType::KEY: {
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004564 const KeyEvent& incomingKey = static_cast<const KeyEvent&>(*event);
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004565 const int32_t action = incomingKey.getAction();
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004566 int32_t flags = incomingKey.getFlags();
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004567 if (policyFlags & POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY) {
4568 flags |= AKEY_EVENT_FLAG_IS_ACCESSIBILITY_EVENT;
4569 }
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004570 int32_t keyCode = incomingKey.getKeyCode();
4571 int32_t metaState = incomingKey.getMetaState();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004572 accelerateMetaShortcuts(resolvedDeviceId, action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004573 /*byref*/ keyCode, /*byref*/ metaState);
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004574 KeyEvent keyEvent;
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004575 keyEvent.initialize(incomingKey.getId(), resolvedDeviceId, incomingKey.getSource(),
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004576 incomingKey.getDisplayId(), INVALID_HMAC, action, flags, keyCode,
4577 incomingKey.getScanCode(), metaState, incomingKey.getRepeatCount(),
4578 incomingKey.getDownTime(), incomingKey.getEventTime());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004579
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004580 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
4581 policyFlags |= POLICY_FLAG_VIRTUAL;
Michael Wright2b3c3302018-03-02 17:19:13 +00004582 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004583
4584 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
4585 android::base::Timer t;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004586 mPolicy.interceptKeyBeforeQueueing(keyEvent, /*byref*/ policyFlags);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004587 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4588 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
4589 std::to_string(t.duration().count()).c_str());
4590 }
4591 }
4592
4593 mLock.lock();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004594 std::unique_ptr<KeyEntry> injectedEntry =
4595 std::make_unique<KeyEntry>(incomingKey.getId(), incomingKey.getEventTime(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004596 resolvedDeviceId, incomingKey.getSource(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004597 incomingKey.getDisplayId(), policyFlags, action,
4598 flags, keyCode, incomingKey.getScanCode(), metaState,
4599 incomingKey.getRepeatCount(),
4600 incomingKey.getDownTime());
4601 injectedEntries.push(std::move(injectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004602 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004603 }
4604
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004605 case InputEventType::MOTION: {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004606 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(*event);
Prabir Pradhanaa561d12021-09-24 06:57:33 -07004607 const bool isPointerEvent =
4608 isFromSource(event->getSource(), AINPUT_SOURCE_CLASS_POINTER);
4609 // If a pointer event has no displayId specified, inject it to the default display.
4610 const uint32_t displayId = isPointerEvent && (event->getDisplayId() == ADISPLAY_ID_NONE)
4611 ? ADISPLAY_ID_DEFAULT
4612 : event->getDisplayId();
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004613 int32_t flags = motionEvent.getFlags();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004614
4615 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004616 nsecs_t eventTime = motionEvent.getEventTime();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004617 android::base::Timer t;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004618 mPolicy.interceptMotionBeforeQueueing(displayId, eventTime, /*byref*/ policyFlags);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004619 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4620 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
4621 std::to_string(t.duration().count()).c_str());
4622 }
4623 }
4624
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004625 if (policyFlags & POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY) {
4626 flags |= AMOTION_EVENT_FLAG_IS_ACCESSIBILITY_EVENT;
4627 }
4628
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004629 mLock.lock();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004630 const nsecs_t* sampleEventTimes = motionEvent.getSampleEventTimes();
4631 const PointerCoords* samplePointerCoords = motionEvent.getSamplePointerCoords();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004632 std::unique_ptr<MotionEntry> injectedEntry =
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004633 std::make_unique<MotionEntry>(motionEvent.getId(), *sampleEventTimes,
4634 resolvedDeviceId, motionEvent.getSource(),
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004635 displayId, policyFlags, motionEvent.getAction(),
4636 motionEvent.getActionButton(), flags,
4637 motionEvent.getMetaState(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004638 motionEvent.getButtonState(),
4639 motionEvent.getClassification(),
4640 motionEvent.getEdgeFlags(),
4641 motionEvent.getXPrecision(),
4642 motionEvent.getYPrecision(),
4643 motionEvent.getRawXCursorPosition(),
4644 motionEvent.getRawYCursorPosition(),
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004645 motionEvent.getDownTime(),
4646 motionEvent.getPointerCount(),
4647 motionEvent.getPointerProperties(),
4648 samplePointerCoords);
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004649 transformMotionEntryForInjectionLocked(*injectedEntry, motionEvent.getTransform());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004650 injectedEntries.push(std::move(injectedEntry));
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004651 for (size_t i = motionEvent.getHistorySize(); i > 0; i--) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004652 sampleEventTimes += 1;
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004653 samplePointerCoords += motionEvent.getPointerCount();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004654 std::unique_ptr<MotionEntry> nextInjectedEntry =
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004655 std::make_unique<MotionEntry>(motionEvent.getId(), *sampleEventTimes,
4656 resolvedDeviceId, motionEvent.getSource(),
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004657 displayId, policyFlags,
4658 motionEvent.getAction(),
4659 motionEvent.getActionButton(), flags,
4660 motionEvent.getMetaState(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004661 motionEvent.getButtonState(),
4662 motionEvent.getClassification(),
4663 motionEvent.getEdgeFlags(),
4664 motionEvent.getXPrecision(),
4665 motionEvent.getYPrecision(),
4666 motionEvent.getRawXCursorPosition(),
4667 motionEvent.getRawYCursorPosition(),
4668 motionEvent.getDownTime(),
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004669 motionEvent.getPointerCount(),
4670 motionEvent.getPointerProperties(),
Prabir Pradhan5beda762021-12-10 09:30:08 +00004671 samplePointerCoords);
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004672 transformMotionEntryForInjectionLocked(*nextInjectedEntry,
4673 motionEvent.getTransform());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004674 injectedEntries.push(std::move(nextInjectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004675 }
4676 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004677 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004678
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004679 default:
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004680 LOG(WARNING) << "Cannot inject " << ftl::enum_string(event->getType()) << " events";
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004681 return InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004682 }
4683
Prabir Pradhan5735a322022-04-11 17:23:34 +00004684 InjectionState* injectionState = new InjectionState(targetUid);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004685 if (syncMode == InputEventInjectionSync::NONE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004686 injectionState->injectionIsAsync = true;
4687 }
4688
4689 injectionState->refCount += 1;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004690 injectedEntries.back()->injectionState = injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004691
4692 bool needWake = false;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004693 while (!injectedEntries.empty()) {
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08004694 if (DEBUG_INJECTION) {
4695 LOG(DEBUG) << "Injecting " << injectedEntries.front()->getDescription();
4696 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004697 needWake |= enqueueInboundEventLocked(std::move(injectedEntries.front()));
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004698 injectedEntries.pop();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004699 }
4700
4701 mLock.unlock();
4702
4703 if (needWake) {
4704 mLooper->wake();
4705 }
4706
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004707 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004708 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004709 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004710
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004711 if (syncMode == InputEventInjectionSync::NONE) {
4712 injectionResult = InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004713 } else {
4714 for (;;) {
4715 injectionResult = injectionState->injectionResult;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004716 if (injectionResult != InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004717 break;
4718 }
4719
4720 nsecs_t remainingTimeout = endTime - now();
4721 if (remainingTimeout <= 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004722 if (DEBUG_INJECTION) {
4723 ALOGD("injectInputEvent - Timed out waiting for injection result "
4724 "to become available.");
4725 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004726 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004727 break;
4728 }
4729
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004730 mInjectionResultAvailable.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004731 }
4732
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004733 if (injectionResult == InputEventInjectionResult::SUCCEEDED &&
4734 syncMode == InputEventInjectionSync::WAIT_FOR_FINISHED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004735 while (injectionState->pendingForegroundDispatches != 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004736 if (DEBUG_INJECTION) {
4737 ALOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
4738 injectionState->pendingForegroundDispatches);
4739 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004740 nsecs_t remainingTimeout = endTime - now();
4741 if (remainingTimeout <= 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004742 if (DEBUG_INJECTION) {
4743 ALOGD("injectInputEvent - Timed out waiting for pending foreground "
4744 "dispatches to finish.");
4745 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004746 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004747 break;
4748 }
4749
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004750 mInjectionSyncFinished.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004751 }
4752 }
4753 }
4754
4755 injectionState->release();
4756 } // release lock
4757
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004758 if (DEBUG_INJECTION) {
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08004759 LOG(DEBUG) << "injectInputEvent - Finished with result "
4760 << ftl::enum_string(injectionResult);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004761 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004762
4763 return injectionResult;
4764}
4765
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004766std::unique_ptr<VerifiedInputEvent> InputDispatcher::verifyInputEvent(const InputEvent& event) {
Gang Wange9087892020-01-07 12:17:14 -05004767 std::array<uint8_t, 32> calculatedHmac;
4768 std::unique_ptr<VerifiedInputEvent> result;
4769 switch (event.getType()) {
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004770 case InputEventType::KEY: {
Gang Wange9087892020-01-07 12:17:14 -05004771 const KeyEvent& keyEvent = static_cast<const KeyEvent&>(event);
4772 VerifiedKeyEvent verifiedKeyEvent = verifiedKeyEventFromKeyEvent(keyEvent);
4773 result = std::make_unique<VerifiedKeyEvent>(verifiedKeyEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004774 calculatedHmac = sign(verifiedKeyEvent);
Gang Wange9087892020-01-07 12:17:14 -05004775 break;
4776 }
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004777 case InputEventType::MOTION: {
Gang Wange9087892020-01-07 12:17:14 -05004778 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(event);
4779 VerifiedMotionEvent verifiedMotionEvent =
4780 verifiedMotionEventFromMotionEvent(motionEvent);
4781 result = std::make_unique<VerifiedMotionEvent>(verifiedMotionEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004782 calculatedHmac = sign(verifiedMotionEvent);
Gang Wange9087892020-01-07 12:17:14 -05004783 break;
4784 }
4785 default: {
4786 ALOGE("Cannot verify events of type %" PRId32, event.getType());
4787 return nullptr;
4788 }
4789 }
4790 if (calculatedHmac == INVALID_HMAC) {
4791 return nullptr;
4792 }
tyiu1573a672023-02-21 22:38:32 +00004793 if (0 != CRYPTO_memcmp(calculatedHmac.data(), event.getHmac().data(), calculatedHmac.size())) {
Gang Wange9087892020-01-07 12:17:14 -05004794 return nullptr;
4795 }
4796 return result;
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004797}
4798
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004799void InputDispatcher::setInjectionResult(EventEntry& entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004800 InputEventInjectionResult injectionResult) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004801 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004802 if (injectionState) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004803 if (DEBUG_INJECTION) {
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08004804 LOG(DEBUG) << "Setting input event injection result to "
4805 << ftl::enum_string(injectionResult);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004806 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004807
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004808 if (injectionState->injectionIsAsync && !(entry.policyFlags & POLICY_FLAG_FILTERED)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004809 // Log the outcome since the injector did not wait for the injection result.
4810 switch (injectionResult) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004811 case InputEventInjectionResult::SUCCEEDED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004812 ALOGV("Asynchronous input event injection succeeded.");
4813 break;
Prabir Pradhan5735a322022-04-11 17:23:34 +00004814 case InputEventInjectionResult::TARGET_MISMATCH:
4815 ALOGV("Asynchronous input event injection target mismatch.");
4816 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004817 case InputEventInjectionResult::FAILED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004818 ALOGW("Asynchronous input event injection failed.");
4819 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004820 case InputEventInjectionResult::TIMED_OUT:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004821 ALOGW("Asynchronous input event injection timed out.");
4822 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004823 case InputEventInjectionResult::PENDING:
4824 ALOGE("Setting result to 'PENDING' for asynchronous injection");
4825 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004826 }
4827 }
4828
4829 injectionState->injectionResult = injectionResult;
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004830 mInjectionResultAvailable.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004831 }
4832}
4833
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004834void InputDispatcher::transformMotionEntryForInjectionLocked(
4835 MotionEntry& entry, const ui::Transform& injectedTransform) const {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004836 // Input injection works in the logical display coordinate space, but the input pipeline works
4837 // display space, so we need to transform the injected events accordingly.
4838 const auto it = mDisplayInfos.find(entry.displayId);
4839 if (it == mDisplayInfos.end()) return;
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004840 const auto& transformToDisplay = it->second.transform.inverse() * injectedTransform;
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004841
Prabir Pradhand9a2ebe2022-07-20 19:25:13 +00004842 if (entry.xCursorPosition != AMOTION_EVENT_INVALID_CURSOR_POSITION &&
4843 entry.yCursorPosition != AMOTION_EVENT_INVALID_CURSOR_POSITION) {
4844 const vec2 cursor =
4845 MotionEvent::calculateTransformedXY(entry.source, transformToDisplay,
4846 {entry.xCursorPosition, entry.yCursorPosition});
4847 entry.xCursorPosition = cursor.x;
4848 entry.yCursorPosition = cursor.y;
4849 }
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004850 for (uint32_t i = 0; i < entry.pointerCount; i++) {
Prabir Pradhan8e6ce222022-02-24 09:08:54 -08004851 entry.pointerCoords[i] =
4852 MotionEvent::calculateTransformedCoords(entry.source, transformToDisplay,
4853 entry.pointerCoords[i]);
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004854 }
4855}
4856
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004857void InputDispatcher::incrementPendingForegroundDispatches(EventEntry& entry) {
4858 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004859 if (injectionState) {
4860 injectionState->pendingForegroundDispatches += 1;
4861 }
4862}
4863
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004864void InputDispatcher::decrementPendingForegroundDispatches(EventEntry& entry) {
4865 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004866 if (injectionState) {
4867 injectionState->pendingForegroundDispatches -= 1;
4868
4869 if (injectionState->pendingForegroundDispatches == 0) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004870 mInjectionSyncFinished.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004871 }
4872 }
4873}
4874
chaviw98318de2021-05-19 16:45:23 -05004875const std::vector<sp<WindowInfoHandle>>& InputDispatcher::getWindowHandlesLocked(
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004876 int32_t displayId) const {
chaviw98318de2021-05-19 16:45:23 -05004877 static const std::vector<sp<WindowInfoHandle>> EMPTY_WINDOW_HANDLES;
Vishnu Nairad321cd2020-08-20 16:40:21 -07004878 auto it = mWindowHandlesByDisplay.find(displayId);
4879 return it != mWindowHandlesByDisplay.end() ? it->second : EMPTY_WINDOW_HANDLES;
Arthur Hungb92218b2018-08-14 12:00:21 +08004880}
4881
chaviw98318de2021-05-19 16:45:23 -05004882sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(
chaviwfbe5d9c2018-12-26 12:23:37 -08004883 const sp<IBinder>& windowHandleToken) const {
arthurhungbe737672020-06-24 12:29:21 +08004884 if (windowHandleToken == nullptr) {
4885 return nullptr;
4886 }
4887
Arthur Hungb92218b2018-08-14 12:00:21 +08004888 for (auto& it : mWindowHandlesByDisplay) {
chaviw98318de2021-05-19 16:45:23 -05004889 const std::vector<sp<WindowInfoHandle>>& windowHandles = it.second;
4890 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
chaviwfbe5d9c2018-12-26 12:23:37 -08004891 if (windowHandle->getToken() == windowHandleToken) {
Arthur Hungb92218b2018-08-14 12:00:21 +08004892 return windowHandle;
4893 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004894 }
4895 }
Yi Kong9b14ac62018-07-17 13:48:38 -07004896 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004897}
4898
chaviw98318de2021-05-19 16:45:23 -05004899sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(const sp<IBinder>& windowHandleToken,
4900 int displayId) const {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004901 if (windowHandleToken == nullptr) {
4902 return nullptr;
4903 }
4904
chaviw98318de2021-05-19 16:45:23 -05004905 for (const sp<WindowInfoHandle>& windowHandle : getWindowHandlesLocked(displayId)) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004906 if (windowHandle->getToken() == windowHandleToken) {
4907 return windowHandle;
4908 }
4909 }
4910 return nullptr;
4911}
4912
chaviw98318de2021-05-19 16:45:23 -05004913sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(
4914 const sp<WindowInfoHandle>& windowHandle) const {
Mady Mellor017bcd12020-06-23 19:12:00 +00004915 for (auto& it : mWindowHandlesByDisplay) {
chaviw98318de2021-05-19 16:45:23 -05004916 const std::vector<sp<WindowInfoHandle>>& windowHandles = it.second;
4917 for (const sp<WindowInfoHandle>& handle : windowHandles) {
arthurhungbe737672020-06-24 12:29:21 +08004918 if (handle->getId() == windowHandle->getId() &&
4919 handle->getToken() == windowHandle->getToken()) {
Mady Mellor017bcd12020-06-23 19:12:00 +00004920 if (windowHandle->getInfo()->displayId != it.first) {
4921 ALOGE("Found window %s in display %" PRId32
4922 ", but it should belong to display %" PRId32,
4923 windowHandle->getName().c_str(), it.first,
4924 windowHandle->getInfo()->displayId);
4925 }
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004926 return handle;
Arthur Hungb92218b2018-08-14 12:00:21 +08004927 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004928 }
4929 }
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004930 return nullptr;
4931}
4932
chaviw98318de2021-05-19 16:45:23 -05004933sp<WindowInfoHandle> InputDispatcher::getFocusedWindowHandleLocked(int displayId) const {
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004934 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(displayId);
4935 return getWindowHandleLocked(focusedToken, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004936}
4937
Prabir Pradhan33e3baa2022-12-06 20:30:22 +00004938ui::Transform InputDispatcher::getTransformLocked(int32_t displayId) const {
4939 auto displayInfoIt = mDisplayInfos.find(displayId);
4940 return displayInfoIt != mDisplayInfos.end() ? displayInfoIt->second.transform
4941 : kIdentityTransform;
4942}
4943
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004944bool InputDispatcher::canWindowReceiveMotionLocked(const sp<WindowInfoHandle>& window,
4945 const MotionEntry& motionEntry) const {
4946 const WindowInfo& info = *window->getInfo();
4947
4948 // Skip spy window targets that are not valid for targeted injection.
4949 if (const auto err = verifyTargetedInjection(window, motionEntry); err) {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004950 return false;
4951 }
4952
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004953 if (info.inputConfig.test(WindowInfo::InputConfig::PAUSE_DISPATCHING)) {
4954 ALOGI("Not sending touch event to %s because it is paused", window->getName().c_str());
4955 return false;
4956 }
4957
4958 if (info.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL)) {
4959 ALOGW("Not sending touch gesture to %s because it has config NO_INPUT_CHANNEL",
4960 window->getName().c_str());
4961 return false;
4962 }
4963
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07004964 std::shared_ptr<Connection> connection = getConnectionLocked(window->getToken());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004965 if (connection == nullptr) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004966 ALOGW("Not sending touch to %s because there's no corresponding connection",
4967 window->getName().c_str());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004968 return false;
4969 }
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004970
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004971 if (!connection->responsive) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004972 ALOGW("Not sending touch to %s because it is not responsive", window->getName().c_str());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004973 return false;
4974 }
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004975
4976 // Drop events that can't be trusted due to occlusion
4977 const auto [x, y] = resolveTouchedPosition(motionEntry);
4978 TouchOcclusionInfo occlusionInfo = computeTouchOcclusionInfoLocked(window, x, y);
4979 if (!isTouchTrustedLocked(occlusionInfo)) {
4980 if (DEBUG_TOUCH_OCCLUSION) {
Prabir Pradhan82e081e2022-12-06 09:50:09 +00004981 ALOGD("Stack of obscuring windows during untrusted touch (%.1f, %.1f):", x, y);
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004982 for (const auto& log : occlusionInfo.debugInfo) {
4983 ALOGD("%s", log.c_str());
4984 }
4985 }
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00004986 ALOGW("Dropping untrusted touch event due to %s/%s", occlusionInfo.obscuringPackage.c_str(),
4987 occlusionInfo.obscuringUid.toString().c_str());
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004988 return false;
4989 }
4990
4991 // Drop touch events if requested by input feature
4992 if (shouldDropInput(motionEntry, window)) {
4993 return false;
4994 }
4995
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004996 return true;
4997}
4998
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004999std::shared_ptr<InputChannel> InputDispatcher::getInputChannelLocked(
5000 const sp<IBinder>& token) const {
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005001 auto connectionIt = mConnectionsByToken.find(token);
5002 if (connectionIt == mConnectionsByToken.end()) {
Robert Carr5c8a0262018-10-03 16:30:44 -07005003 return nullptr;
5004 }
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005005 return connectionIt->second->inputChannel;
Robert Carr5c8a0262018-10-03 16:30:44 -07005006}
5007
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005008void InputDispatcher::updateWindowHandlesForDisplayLocked(
chaviw98318de2021-05-19 16:45:23 -05005009 const std::vector<sp<WindowInfoHandle>>& windowInfoHandles, int32_t displayId) {
5010 if (windowInfoHandles.empty()) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005011 // Remove all handles on a display if there are no windows left.
5012 mWindowHandlesByDisplay.erase(displayId);
5013 return;
5014 }
5015
5016 // Since we compare the pointer of input window handles across window updates, we need
5017 // to make sure the handle object for the same window stays unchanged across updates.
chaviw98318de2021-05-19 16:45:23 -05005018 const std::vector<sp<WindowInfoHandle>>& oldHandles = getWindowHandlesLocked(displayId);
5019 std::unordered_map<int32_t /*id*/, sp<WindowInfoHandle>> oldHandlesById;
5020 for (const sp<WindowInfoHandle>& handle : oldHandles) {
chaviwaf87b3e2019-10-01 16:59:28 -07005021 oldHandlesById[handle->getId()] = handle;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005022 }
5023
chaviw98318de2021-05-19 16:45:23 -05005024 std::vector<sp<WindowInfoHandle>> newHandles;
5025 for (const sp<WindowInfoHandle>& handle : windowInfoHandles) {
chaviw98318de2021-05-19 16:45:23 -05005026 const WindowInfo* info = handle->getInfo();
Siarhei Vishniakou64452932020-11-06 17:51:32 -06005027 if (getInputChannelLocked(handle->getToken()) == nullptr) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005028 const bool noInputChannel =
Prabir Pradhan51e7db02022-02-07 06:02:57 -08005029 info->inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005030 const bool canReceiveInput =
5031 !info->inputConfig.test(WindowInfo::InputConfig::NOT_TOUCHABLE) ||
5032 !info->inputConfig.test(WindowInfo::InputConfig::NOT_FOCUSABLE);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005033 if (canReceiveInput && !noInputChannel) {
John Recke0710582019-09-26 13:46:12 -07005034 ALOGV("Window handle %s has no registered input channel",
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005035 handle->getName().c_str());
Robert Carr2984b7a2020-04-13 17:06:45 -07005036 continue;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005037 }
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005038 }
5039
5040 if (info->displayId != displayId) {
5041 ALOGE("Window %s updated by wrong display %d, should belong to display %d",
5042 handle->getName().c_str(), displayId, info->displayId);
5043 continue;
5044 }
5045
Robert Carredd13602020-04-13 17:24:34 -07005046 if ((oldHandlesById.find(handle->getId()) != oldHandlesById.end()) &&
5047 (oldHandlesById.at(handle->getId())->getToken() == handle->getToken())) {
chaviw98318de2021-05-19 16:45:23 -05005048 const sp<WindowInfoHandle>& oldHandle = oldHandlesById.at(handle->getId());
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005049 oldHandle->updateFrom(handle);
5050 newHandles.push_back(oldHandle);
5051 } else {
5052 newHandles.push_back(handle);
5053 }
5054 }
5055
5056 // Insert or replace
5057 mWindowHandlesByDisplay[displayId] = newHandles;
5058}
5059
Arthur Hung72d8dc32020-03-28 00:48:39 +00005060void InputDispatcher::setInputWindows(
chaviw98318de2021-05-19 16:45:23 -05005061 const std::unordered_map<int32_t, std::vector<sp<WindowInfoHandle>>>& handlesPerDisplay) {
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005062 // TODO(b/198444055): Remove setInputWindows from InputDispatcher.
Arthur Hung72d8dc32020-03-28 00:48:39 +00005063 { // acquire lock
5064 std::scoped_lock _l(mLock);
Siarhei Vishniakou2508b872020-12-03 16:33:53 -10005065 for (const auto& [displayId, handles] : handlesPerDisplay) {
5066 setInputWindowsLocked(handles, displayId);
Arthur Hung72d8dc32020-03-28 00:48:39 +00005067 }
5068 }
5069 // Wake up poll loop since it may need to make new input dispatching choices.
5070 mLooper->wake();
5071}
5072
Arthur Hungb92218b2018-08-14 12:00:21 +08005073/**
5074 * Called from InputManagerService, update window handle list by displayId that can receive input.
5075 * A window handle contains information about InputChannel, Touch Region, Types, Focused,...
5076 * If set an empty list, remove all handles from the specific display.
5077 * For focused handle, check if need to change and send a cancel event to previous one.
5078 * For removed handle, check if need to send a cancel event if already in touch.
5079 */
Arthur Hung72d8dc32020-03-28 00:48:39 +00005080void InputDispatcher::setInputWindowsLocked(
chaviw98318de2021-05-19 16:45:23 -05005081 const std::vector<sp<WindowInfoHandle>>& windowInfoHandles, int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005082 if (DEBUG_FOCUS) {
5083 std::string windowList;
chaviw98318de2021-05-19 16:45:23 -05005084 for (const sp<WindowInfoHandle>& iwh : windowInfoHandles) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005085 windowList += iwh->getName() + " ";
5086 }
5087 ALOGD("setInputWindows displayId=%" PRId32 " %s", displayId, windowList.c_str());
5088 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005089
Prabir Pradhand65552b2021-10-07 11:23:50 -07005090 // Check preconditions for new input windows
chaviw98318de2021-05-19 16:45:23 -05005091 for (const sp<WindowInfoHandle>& window : windowInfoHandles) {
Prabir Pradhand65552b2021-10-07 11:23:50 -07005092 const WindowInfo& info = *window->getInfo();
5093
5094 // Ensure all tokens are null if the window has feature NO_INPUT_CHANNEL
Prabir Pradhan51e7db02022-02-07 06:02:57 -08005095 const bool noInputWindow = info.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005096 if (noInputWindow && window->getToken() != nullptr) {
5097 ALOGE("%s has feature NO_INPUT_WINDOW, but a non-null token. Clearing",
5098 window->getName().c_str());
5099 window->releaseChannel();
5100 }
Prabir Pradhand65552b2021-10-07 11:23:50 -07005101
Prabir Pradhan5c85e052021-12-22 02:27:12 -08005102 // Ensure all spy windows are trusted overlays
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005103 LOG_ALWAYS_FATAL_IF(info.isSpy() &&
5104 !info.inputConfig.test(
5105 WindowInfo::InputConfig::TRUSTED_OVERLAY),
Prabir Pradhan5c85e052021-12-22 02:27:12 -08005106 "%s has feature SPY, but is not a trusted overlay.",
5107 window->getName().c_str());
5108
Prabir Pradhand65552b2021-10-07 11:23:50 -07005109 // Ensure all stylus interceptors are trusted overlays
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005110 LOG_ALWAYS_FATAL_IF(info.interceptsStylus() &&
5111 !info.inputConfig.test(
5112 WindowInfo::InputConfig::TRUSTED_OVERLAY),
Prabir Pradhand65552b2021-10-07 11:23:50 -07005113 "%s has feature INTERCEPTS_STYLUS, but is not a trusted overlay.",
5114 window->getName().c_str());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005115 }
5116
Arthur Hung72d8dc32020-03-28 00:48:39 +00005117 // Copy old handles for release if they are no longer present.
chaviw98318de2021-05-19 16:45:23 -05005118 const std::vector<sp<WindowInfoHandle>> oldWindowHandles = getWindowHandlesLocked(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005119
chaviw98318de2021-05-19 16:45:23 -05005120 updateWindowHandlesForDisplayLocked(windowInfoHandles, displayId);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005121
chaviw98318de2021-05-19 16:45:23 -05005122 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Arthur Hung72d8dc32020-03-28 00:48:39 +00005123
Vishnu Nairc519ff72021-01-21 08:23:08 -08005124 std::optional<FocusResolver::FocusChanges> changes =
5125 mFocusResolver.setInputWindows(displayId, windowHandles);
5126 if (changes) {
5127 onFocusChangedLocked(*changes);
Arthur Hung72d8dc32020-03-28 00:48:39 +00005128 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005129
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005130 std::unordered_map<int32_t, TouchState>::iterator stateIt =
5131 mTouchStatesByDisplay.find(displayId);
5132 if (stateIt != mTouchStatesByDisplay.end()) {
5133 TouchState& state = stateIt->second;
Arthur Hung72d8dc32020-03-28 00:48:39 +00005134 for (size_t i = 0; i < state.windows.size();) {
5135 TouchedWindow& touchedWindow = state.windows[i];
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07005136 if (getWindowHandleLocked(touchedWindow.windowHandle) == nullptr) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005137 if (DEBUG_FOCUS) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00005138 ALOGD("Touched window was removed: %s in display %" PRId32,
5139 touchedWindow.windowHandle->getName().c_str(), displayId);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005140 }
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005141 std::shared_ptr<InputChannel> touchedInputChannel =
Arthur Hung72d8dc32020-03-28 00:48:39 +00005142 getInputChannelLocked(touchedWindow.windowHandle->getToken());
5143 if (touchedInputChannel != nullptr) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00005144 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
Arthur Hung72d8dc32020-03-28 00:48:39 +00005145 "touched window was removed");
5146 synthesizeCancelationEventsForInputChannelLocked(touchedInputChannel, options);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00005147 // Since we are about to drop the touch, cancel the events for the wallpaper as
5148 // well.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005149 if (touchedWindow.targetFlags.test(InputTarget::Flags::FOREGROUND) &&
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005150 touchedWindow.windowHandle->getInfo()->inputConfig.test(
5151 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER)) {
Siarhei Vishniakouca205502021-07-16 21:31:58 +00005152 sp<WindowInfoHandle> wallpaper = state.getWallpaperWindow();
Arthur Hungc539dbb2022-12-08 07:45:36 +00005153 synthesizeCancelationEventsForWindowLocked(wallpaper, options);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00005154 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005155 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00005156 state.windows.erase(state.windows.begin() + i);
5157 } else {
5158 ++i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005159 }
5160 }
arthurhungb89ccb02020-12-30 16:19:01 +08005161
arthurhung6d4bed92021-03-17 11:59:33 +08005162 // If drag window is gone, it would receive a cancel event and broadcast the DRAG_END. We
arthurhungb89ccb02020-12-30 16:19:01 +08005163 // could just clear the state here.
Arthur Hung3915c1f2022-05-31 07:17:17 +00005164 if (mDragState && mDragState->dragWindow->getInfo()->displayId == displayId &&
arthurhung6d4bed92021-03-17 11:59:33 +08005165 std::find(windowHandles.begin(), windowHandles.end(), mDragState->dragWindow) ==
arthurhungb89ccb02020-12-30 16:19:01 +08005166 windowHandles.end()) {
Arthur Hung3915c1f2022-05-31 07:17:17 +00005167 ALOGI("Drag window went away: %s", mDragState->dragWindow->getName().c_str());
5168 sendDropWindowCommandLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08005169 mDragState.reset();
arthurhungb89ccb02020-12-30 16:19:01 +08005170 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00005171 }
Arthur Hung25e2af12020-03-26 12:58:37 +00005172
Arthur Hung72d8dc32020-03-28 00:48:39 +00005173 // Release information for windows that are no longer present.
5174 // This ensures that unused input channels are released promptly.
5175 // Otherwise, they might stick around until the window handle is destroyed
5176 // which might not happen until the next GC.
chaviw98318de2021-05-19 16:45:23 -05005177 for (const sp<WindowInfoHandle>& oldWindowHandle : oldWindowHandles) {
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07005178 if (getWindowHandleLocked(oldWindowHandle) == nullptr) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00005179 if (DEBUG_FOCUS) {
5180 ALOGD("Window went away: %s", oldWindowHandle->getName().c_str());
Arthur Hung25e2af12020-03-26 12:58:37 +00005181 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00005182 oldWindowHandle->releaseChannel();
Arthur Hung25e2af12020-03-26 12:58:37 +00005183 }
chaviw291d88a2019-02-14 10:33:58 -08005184 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005185}
5186
5187void InputDispatcher::setFocusedApplication(
Chris Yea209fde2020-07-22 13:54:51 -07005188 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005189 if (DEBUG_FOCUS) {
5190 ALOGD("setFocusedApplication displayId=%" PRId32 " %s", displayId,
5191 inputApplicationHandle ? inputApplicationHandle->getName().c_str() : "<nullptr>");
5192 }
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05005193 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005194 std::scoped_lock _l(mLock);
Vishnu Nair599f1412021-06-21 10:39:58 -07005195 setFocusedApplicationLocked(displayId, inputApplicationHandle);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005196 } // release lock
5197
5198 // Wake up poll loop since it may need to make new input dispatching choices.
5199 mLooper->wake();
5200}
5201
Vishnu Nair599f1412021-06-21 10:39:58 -07005202void InputDispatcher::setFocusedApplicationLocked(
5203 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
5204 std::shared_ptr<InputApplicationHandle> oldFocusedApplicationHandle =
5205 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
5206
5207 if (sharedPointersEqual(oldFocusedApplicationHandle, inputApplicationHandle)) {
5208 return; // This application is already focused. No need to wake up or change anything.
5209 }
5210
5211 // Set the new application handle.
5212 if (inputApplicationHandle != nullptr) {
5213 mFocusedApplicationHandlesByDisplay[displayId] = inputApplicationHandle;
5214 } else {
5215 mFocusedApplicationHandlesByDisplay.erase(displayId);
5216 }
5217
5218 // No matter what the old focused application was, stop waiting on it because it is
5219 // no longer focused.
5220 resetNoFocusedWindowTimeoutLocked();
5221}
5222
Tiger Huang721e26f2018-07-24 22:26:19 +08005223/**
5224 * Sets the focused display, which is responsible for receiving focus-dispatched input events where
5225 * the display not specified.
5226 *
5227 * We track any unreleased events for each window. If a window loses the ability to receive the
5228 * released event, we will send a cancel event to it. So when the focused display is changed, we
5229 * cancel all the unreleased display-unspecified events for the focused window on the old focused
5230 * display. The display-specified events won't be affected.
5231 */
5232void InputDispatcher::setFocusedDisplay(int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005233 if (DEBUG_FOCUS) {
5234 ALOGD("setFocusedDisplay displayId=%" PRId32, displayId);
5235 }
Tiger Huang721e26f2018-07-24 22:26:19 +08005236 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005237 std::scoped_lock _l(mLock);
Tiger Huang721e26f2018-07-24 22:26:19 +08005238
5239 if (mFocusedDisplayId != displayId) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07005240 sp<IBinder> oldFocusedWindowToken =
Vishnu Nairc519ff72021-01-21 08:23:08 -08005241 mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07005242 if (oldFocusedWindowToken != nullptr) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005243 std::shared_ptr<InputChannel> inputChannel =
Vishnu Nairad321cd2020-08-20 16:40:21 -07005244 getInputChannelLocked(oldFocusedWindowToken);
Tiger Huang721e26f2018-07-24 22:26:19 +08005245 if (inputChannel != nullptr) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005246 CancelationOptions
Michael Wrightfb04fd52022-11-24 22:31:11 +00005247 options(CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005248 "The display which contains this window no longer has focus.");
Michael Wright3dd60e22019-03-27 22:06:44 +00005249 options.displayId = ADISPLAY_ID_NONE;
Tiger Huang721e26f2018-07-24 22:26:19 +08005250 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
5251 }
5252 }
5253 mFocusedDisplayId = displayId;
5254
Chris Ye3c2d6f52020-08-09 10:39:48 -07005255 // Find new focused window and validate
Vishnu Nairc519ff72021-01-21 08:23:08 -08005256 sp<IBinder> newFocusedWindowToken = mFocusResolver.getFocusedWindowToken(displayId);
Prabir Pradhancef936d2021-07-21 16:17:52 +00005257 sendFocusChangedCommandLocked(oldFocusedWindowToken, newFocusedWindowToken);
Robert Carrf759f162018-11-13 12:57:11 -08005258
Vishnu Nairad321cd2020-08-20 16:40:21 -07005259 if (newFocusedWindowToken == nullptr) {
Tiger Huang721e26f2018-07-24 22:26:19 +08005260 ALOGW("Focused display #%" PRId32 " does not have a focused window.", displayId);
Vishnu Nairc519ff72021-01-21 08:23:08 -08005261 if (mFocusResolver.hasFocusedWindowTokens()) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07005262 ALOGE("But another display has a focused window\n%s",
Vishnu Nairc519ff72021-01-21 08:23:08 -08005263 mFocusResolver.dumpFocusedWindows().c_str());
Tiger Huang721e26f2018-07-24 22:26:19 +08005264 }
5265 }
5266 }
Tiger Huang721e26f2018-07-24 22:26:19 +08005267 } // release lock
5268
5269 // Wake up poll loop since it may need to make new input dispatching choices.
5270 mLooper->wake();
5271}
5272
Michael Wrightd02c5b62014-02-10 15:10:22 -08005273void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005274 if (DEBUG_FOCUS) {
5275 ALOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
5276 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005277
5278 bool changed;
5279 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005280 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005281
5282 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
5283 if (mDispatchFrozen && !frozen) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005284 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005285 }
5286
5287 if (mDispatchEnabled && !enabled) {
5288 resetAndDropEverythingLocked("dispatcher is being disabled");
5289 }
5290
5291 mDispatchEnabled = enabled;
5292 mDispatchFrozen = frozen;
5293 changed = true;
5294 } else {
5295 changed = false;
5296 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005297 } // release lock
5298
5299 if (changed) {
5300 // Wake up poll loop since it may need to make new input dispatching choices.
5301 mLooper->wake();
5302 }
5303}
5304
5305void InputDispatcher::setInputFilterEnabled(bool enabled) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005306 if (DEBUG_FOCUS) {
5307 ALOGD("setInputFilterEnabled: enabled=%d", enabled);
5308 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005309
5310 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005311 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005312
5313 if (mInputFilterEnabled == enabled) {
5314 return;
5315 }
5316
5317 mInputFilterEnabled = enabled;
5318 resetAndDropEverythingLocked("input filter is being enabled or disabled");
5319 } // release lock
5320
5321 // Wake up poll loop since there might be work to do to drop everything.
5322 mLooper->wake();
5323}
5324
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005325bool InputDispatcher::setInTouchMode(bool inTouchMode, gui::Pid pid, gui::Uid uid,
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00005326 bool hasPermission, int32_t displayId) {
Antonio Kantekf16f2832021-09-28 04:39:20 +00005327 bool needWake = false;
5328 {
5329 std::scoped_lock lock(mLock);
Antonio Kantek15beb512022-06-13 22:35:41 +00005330 ALOGD_IF(DEBUG_TOUCH_MODE,
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005331 "Request to change touch mode to %s (calling pid=%s, uid=%s, "
Antonio Kantek15beb512022-06-13 22:35:41 +00005332 "hasPermission=%s, target displayId=%d, mTouchModePerDisplay[displayId]=%s)",
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005333 toString(inTouchMode), pid.toString().c_str(), uid.toString().c_str(),
5334 toString(hasPermission), displayId,
Antonio Kantek15beb512022-06-13 22:35:41 +00005335 mTouchModePerDisplay.count(displayId) == 0
5336 ? "not set"
5337 : std::to_string(mTouchModePerDisplay[displayId]).c_str());
5338
Antonio Kantek15beb512022-06-13 22:35:41 +00005339 auto touchModeIt = mTouchModePerDisplay.find(displayId);
5340 if (touchModeIt != mTouchModePerDisplay.end() && touchModeIt->second == inTouchMode) {
Antonio Kantekea47acb2021-12-23 12:41:25 -08005341 return false;
Antonio Kantekf16f2832021-09-28 04:39:20 +00005342 }
Antonio Kantekea47acb2021-12-23 12:41:25 -08005343 if (!hasPermission) {
Antonio Kantek48710e42022-03-24 14:19:30 -07005344 if (!focusedWindowIsOwnedByLocked(pid, uid) &&
5345 !recentWindowsAreOwnedByLocked(pid, uid)) {
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005346 ALOGD("Touch mode switch rejected, caller (pid=%s, uid=%s) doesn't own the focused "
Antonio Kantek48710e42022-03-24 14:19:30 -07005347 "window nor none of the previously interacted window",
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005348 pid.toString().c_str(), uid.toString().c_str());
Antonio Kantekea47acb2021-12-23 12:41:25 -08005349 return false;
5350 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00005351 }
Antonio Kantek15beb512022-06-13 22:35:41 +00005352 mTouchModePerDisplay[displayId] = inTouchMode;
5353 auto entry = std::make_unique<TouchModeEntry>(mIdGenerator.nextId(), now(), inTouchMode,
5354 displayId);
Antonio Kantekf16f2832021-09-28 04:39:20 +00005355 needWake = enqueueInboundEventLocked(std::move(entry));
5356 } // release lock
5357
5358 if (needWake) {
5359 mLooper->wake();
5360 }
Antonio Kantekea47acb2021-12-23 12:41:25 -08005361 return true;
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -08005362}
5363
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005364bool InputDispatcher::focusedWindowIsOwnedByLocked(gui::Pid pid, gui::Uid uid) {
Antonio Kantek48710e42022-03-24 14:19:30 -07005365 const sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
5366 if (focusedToken == nullptr) {
5367 return false;
5368 }
5369 sp<WindowInfoHandle> windowHandle = getWindowHandleLocked(focusedToken);
5370 return isWindowOwnedBy(windowHandle, pid, uid);
5371}
5372
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005373bool InputDispatcher::recentWindowsAreOwnedByLocked(gui::Pid pid, gui::Uid uid) {
Antonio Kantek48710e42022-03-24 14:19:30 -07005374 return std::find_if(mInteractionConnectionTokens.begin(), mInteractionConnectionTokens.end(),
5375 [&](const sp<IBinder>& connectionToken) REQUIRES(mLock) {
5376 const sp<WindowInfoHandle> windowHandle =
5377 getWindowHandleLocked(connectionToken);
5378 return isWindowOwnedBy(windowHandle, pid, uid);
5379 }) != mInteractionConnectionTokens.end();
5380}
5381
Bernardo Rufinoea97d182020-08-19 14:43:14 +01005382void InputDispatcher::setMaximumObscuringOpacityForTouch(float opacity) {
5383 if (opacity < 0 || opacity > 1) {
5384 LOG_ALWAYS_FATAL("Maximum obscuring opacity for touch should be >= 0 and <= 1");
5385 return;
5386 }
5387
5388 std::scoped_lock lock(mLock);
5389 mMaximumObscuringOpacityForTouch = opacity;
5390}
5391
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005392std::tuple<TouchState*, TouchedWindow*, int32_t /*displayId*/>
5393InputDispatcher::findTouchStateWindowAndDisplayLocked(const sp<IBinder>& token) {
Arthur Hungabbb9d82021-09-01 14:52:30 +00005394 for (auto& [displayId, state] : mTouchStatesByDisplay) {
5395 for (TouchedWindow& w : state.windows) {
5396 if (w.windowHandle->getToken() == token) {
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005397 return std::make_tuple(&state, &w, displayId);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005398 }
5399 }
5400 }
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005401 return std::make_tuple(nullptr, nullptr, ADISPLAY_ID_DEFAULT);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005402}
5403
arthurhungb89ccb02020-12-30 16:19:01 +08005404bool InputDispatcher::transferTouchFocus(const sp<IBinder>& fromToken, const sp<IBinder>& toToken,
5405 bool isDragDrop) {
chaviwfbe5d9c2018-12-26 12:23:37 -08005406 if (fromToken == toToken) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005407 if (DEBUG_FOCUS) {
5408 ALOGD("Trivial transfer to same window.");
5409 }
chaviwfbe5d9c2018-12-26 12:23:37 -08005410 return true;
5411 }
5412
Michael Wrightd02c5b62014-02-10 15:10:22 -08005413 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005414 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005415
Arthur Hungabbb9d82021-09-01 14:52:30 +00005416 // Find the target touch state and touched window by fromToken.
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005417 auto [state, touchedWindow, displayId] = findTouchStateWindowAndDisplayLocked(fromToken);
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005418
Arthur Hungabbb9d82021-09-01 14:52:30 +00005419 if (state == nullptr || touchedWindow == nullptr) {
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005420 ALOGD("Touch transfer failed because from window is not being touched.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005421 return false;
5422 }
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005423 std::set<int32_t> deviceIds = touchedWindow->getTouchingDeviceIds();
5424 if (deviceIds.size() != 1) {
5425 LOG(DEBUG) << "Can't transfer touch. Currently touching devices: " << dumpSet(deviceIds)
5426 << " for window: " << touchedWindow->dump();
5427 return false;
5428 }
5429 const int32_t deviceId = *deviceIds.begin();
Arthur Hungabbb9d82021-09-01 14:52:30 +00005430
Arthur Hungabbb9d82021-09-01 14:52:30 +00005431 sp<WindowInfoHandle> toWindowHandle = getWindowHandleLocked(toToken, displayId);
5432 if (toWindowHandle == nullptr) {
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005433 ALOGW("Cannot transfer touch because to window not found.");
Arthur Hungabbb9d82021-09-01 14:52:30 +00005434 return false;
5435 }
5436
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005437 if (DEBUG_FOCUS) {
5438 ALOGD("transferTouchFocus: fromWindowHandle=%s, toWindowHandle=%s",
Arthur Hungabbb9d82021-09-01 14:52:30 +00005439 touchedWindow->windowHandle->getName().c_str(),
5440 toWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005441 }
5442
Arthur Hungabbb9d82021-09-01 14:52:30 +00005443 // Erase old window.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005444 ftl::Flags<InputTarget::Flags> oldTargetFlags = touchedWindow->targetFlags;
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005445 std::bitset<MAX_POINTER_ID + 1> pointerIds = touchedWindow->getTouchingPointers(deviceId);
Arthur Hungc539dbb2022-12-08 07:45:36 +00005446 sp<WindowInfoHandle> fromWindowHandle = touchedWindow->windowHandle;
Arthur Hungabbb9d82021-09-01 14:52:30 +00005447 state->removeWindowByToken(fromToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005448
Arthur Hungabbb9d82021-09-01 14:52:30 +00005449 // Add new window.
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00005450 nsecs_t downTimeInTarget = now();
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005451 ftl::Flags<InputTarget::Flags> newTargetFlags =
5452 oldTargetFlags & (InputTarget::Flags::SPLIT | InputTarget::Flags::DISPATCH_AS_IS);
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00005453 if (canReceiveForegroundTouches(*toWindowHandle->getInfo())) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005454 newTargetFlags |= InputTarget::Flags::FOREGROUND;
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00005455 }
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005456 state->addOrUpdateWindow(toWindowHandle, newTargetFlags, deviceId, pointerIds,
5457 downTimeInTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005458
Arthur Hungabbb9d82021-09-01 14:52:30 +00005459 // Store the dragging window.
5460 if (isDragDrop) {
Arthur Hungb75c2aa2022-07-15 09:35:36 +00005461 if (pointerIds.count() != 1) {
5462 ALOGW("The drag and drop cannot be started when there is no pointer or more than 1"
5463 " pointer on the window.");
Arthur Hung54745652022-04-20 07:17:41 +00005464 return false;
5465 }
Arthur Hungb75c2aa2022-07-15 09:35:36 +00005466 // Track the pointer id for drag window and generate the drag state.
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08005467 const size_t id = firstMarkedBit(pointerIds);
Arthur Hung54745652022-04-20 07:17:41 +00005468 mDragState = std::make_unique<DragState>(toWindowHandle, id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005469 }
5470
Arthur Hungabbb9d82021-09-01 14:52:30 +00005471 // Synthesize cancel for old window and down for new window.
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07005472 std::shared_ptr<Connection> fromConnection = getConnectionLocked(fromToken);
5473 std::shared_ptr<Connection> toConnection = getConnectionLocked(toToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005474 if (fromConnection != nullptr && toConnection != nullptr) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08005475 fromConnection->inputState.mergePointerStateTo(toConnection->inputState);
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005476 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
5477 "transferring touch from this window to another window");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005478 synthesizeCancelationEventsForConnectionLocked(fromConnection, options);
Arthur Hungc539dbb2022-12-08 07:45:36 +00005479 synthesizePointerDownEventsForConnectionLocked(downTimeInTarget, toConnection,
5480 newTargetFlags);
5481
5482 // Check if the wallpaper window should deliver the corresponding event.
5483 transferWallpaperTouch(oldTargetFlags, newTargetFlags, fromWindowHandle, toWindowHandle,
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005484 *state, deviceId, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005485 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005486 } // release lock
5487
5488 // Wake up poll loop since it may need to make new input dispatching choices.
5489 mLooper->wake();
5490 return true;
5491}
5492
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005493/**
5494 * Get the touched foreground window on the given display.
5495 * Return null if there are no windows touched on that display, or if more than one foreground
5496 * window is being touched.
5497 */
5498sp<WindowInfoHandle> InputDispatcher::findTouchedForegroundWindowLocked(int32_t displayId) const {
5499 auto stateIt = mTouchStatesByDisplay.find(displayId);
5500 if (stateIt == mTouchStatesByDisplay.end()) {
5501 ALOGI("No touch state on display %" PRId32, displayId);
5502 return nullptr;
5503 }
5504
5505 const TouchState& state = stateIt->second;
5506 sp<WindowInfoHandle> touchedForegroundWindow;
5507 // If multiple foreground windows are touched, return nullptr
5508 for (const TouchedWindow& window : state.windows) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005509 if (window.targetFlags.test(InputTarget::Flags::FOREGROUND)) {
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005510 if (touchedForegroundWindow != nullptr) {
5511 ALOGI("Two or more foreground windows: %s and %s",
5512 touchedForegroundWindow->getName().c_str(),
5513 window.windowHandle->getName().c_str());
5514 return nullptr;
5515 }
5516 touchedForegroundWindow = window.windowHandle;
5517 }
5518 }
5519 return touchedForegroundWindow;
5520}
5521
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005522// Binder call
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005523bool InputDispatcher::transferTouch(const sp<IBinder>& destChannelToken, int32_t displayId) {
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005524 sp<IBinder> fromToken;
5525 { // acquire lock
5526 std::scoped_lock _l(mLock);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005527 sp<WindowInfoHandle> toWindowHandle = getWindowHandleLocked(destChannelToken, displayId);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005528 if (toWindowHandle == nullptr) {
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005529 ALOGW("Could not find window associated with token=%p on display %" PRId32,
5530 destChannelToken.get(), displayId);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005531 return false;
5532 }
5533
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005534 sp<WindowInfoHandle> from = findTouchedForegroundWindowLocked(displayId);
5535 if (from == nullptr) {
5536 ALOGE("Could not find a source window in %s for %p", __func__, destChannelToken.get());
5537 return false;
5538 }
5539
5540 fromToken = from->getToken();
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005541 } // release lock
5542
5543 return transferTouchFocus(fromToken, destChannelToken);
5544}
5545
Michael Wrightd02c5b62014-02-10 15:10:22 -08005546void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005547 if (DEBUG_FOCUS) {
5548 ALOGD("Resetting and dropping all events (%s).", reason);
5549 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005550
Michael Wrightfb04fd52022-11-24 22:31:11 +00005551 CancelationOptions options(CancelationOptions::Mode::CANCEL_ALL_EVENTS, reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005552 synthesizeCancelationEventsForAllConnectionsLocked(options);
5553
5554 resetKeyRepeatLocked();
5555 releasePendingEventLocked();
5556 drainInboundQueueLocked();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005557 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005558
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005559 mAnrTracker.clear();
Jeff Brownf086ddb2014-02-11 14:28:48 -08005560 mTouchStatesByDisplay.clear();
Michael Wright78f24442014-08-06 15:55:28 -07005561 mReplacedKeys.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005562}
5563
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005564void InputDispatcher::logDispatchStateLocked() const {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005565 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005566 dumpDispatchStateLocked(dump);
5567
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005568 std::istringstream stream(dump);
5569 std::string line;
5570
5571 while (std::getline(stream, line, '\n')) {
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07005572 ALOGI("%s", line.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005573 }
5574}
5575
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005576std::string InputDispatcher::dumpPointerCaptureStateLocked() const {
Prabir Pradhan99987712020-11-10 18:43:05 -08005577 std::string dump;
5578
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005579 dump += StringPrintf(INDENT "Pointer Capture Requested: %s\n",
5580 toString(mCurrentPointerCaptureRequest.enable));
Prabir Pradhan99987712020-11-10 18:43:05 -08005581
5582 std::string windowName = "None";
5583 if (mWindowTokenWithPointerCapture) {
chaviw98318de2021-05-19 16:45:23 -05005584 const sp<WindowInfoHandle> captureWindowHandle =
Prabir Pradhan99987712020-11-10 18:43:05 -08005585 getWindowHandleLocked(mWindowTokenWithPointerCapture);
5586 windowName = captureWindowHandle ? captureWindowHandle->getName().c_str()
5587 : "token has capture without window";
5588 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005589 dump += StringPrintf(INDENT "Current Window with Pointer Capture: %s\n", windowName.c_str());
Prabir Pradhan99987712020-11-10 18:43:05 -08005590
5591 return dump;
5592}
5593
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005594void InputDispatcher::dumpDispatchStateLocked(std::string& dump) const {
Siarhei Vishniakou043a3ec2019-05-01 11:30:46 -07005595 dump += StringPrintf(INDENT "DispatchEnabled: %s\n", toString(mDispatchEnabled));
5596 dump += StringPrintf(INDENT "DispatchFrozen: %s\n", toString(mDispatchFrozen));
5597 dump += StringPrintf(INDENT "InputFilterEnabled: %s\n", toString(mInputFilterEnabled));
Tiger Huang721e26f2018-07-24 22:26:19 +08005598 dump += StringPrintf(INDENT "FocusedDisplayId: %" PRId32 "\n", mFocusedDisplayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005599
Tiger Huang721e26f2018-07-24 22:26:19 +08005600 if (!mFocusedApplicationHandlesByDisplay.empty()) {
5601 dump += StringPrintf(INDENT "FocusedApplications:\n");
5602 for (auto& it : mFocusedApplicationHandlesByDisplay) {
5603 const int32_t displayId = it.first;
Chris Yea209fde2020-07-22 13:54:51 -07005604 const std::shared_ptr<InputApplicationHandle>& applicationHandle = it.second;
Siarhei Vishniakou70622952020-07-30 11:17:23 -05005605 const std::chrono::duration timeout =
5606 applicationHandle->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005607 dump += StringPrintf(INDENT2 "displayId=%" PRId32
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005608 ", name='%s', dispatchingTimeout=%" PRId64 "ms\n",
Siarhei Vishniakou70622952020-07-30 11:17:23 -05005609 displayId, applicationHandle->getName().c_str(), millis(timeout));
Tiger Huang721e26f2018-07-24 22:26:19 +08005610 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005611 } else {
Tiger Huang721e26f2018-07-24 22:26:19 +08005612 dump += StringPrintf(INDENT "FocusedApplications: <none>\n");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005613 }
Tiger Huang721e26f2018-07-24 22:26:19 +08005614
Vishnu Nairc519ff72021-01-21 08:23:08 -08005615 dump += mFocusResolver.dump();
Prabir Pradhan99987712020-11-10 18:43:05 -08005616 dump += dumpPointerCaptureStateLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005617
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005618 if (!mTouchStatesByDisplay.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005619 dump += StringPrintf(INDENT "TouchStatesByDisplay:\n");
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005620 for (const auto& [displayId, state] : mTouchStatesByDisplay) {
Siarhei Vishniakou6e1e9872022-11-08 17:51:35 -08005621 std::string touchStateDump = addLinePrefix(state.dump(), INDENT2);
5622 dump += INDENT2 + std::to_string(displayId) + " : " + touchStateDump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005623 }
5624 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005625 dump += INDENT "TouchStates: <no displays touched>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005626 }
5627
arthurhung6d4bed92021-03-17 11:59:33 +08005628 if (mDragState) {
5629 dump += StringPrintf(INDENT "DragState:\n");
5630 mDragState->dump(dump, INDENT2);
5631 }
5632
Arthur Hungb92218b2018-08-14 12:00:21 +08005633 if (!mWindowHandlesByDisplay.empty()) {
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005634 for (const auto& [displayId, windowHandles] : mWindowHandlesByDisplay) {
5635 dump += StringPrintf(INDENT "Display: %" PRId32 "\n", displayId);
5636 if (const auto& it = mDisplayInfos.find(displayId); it != mDisplayInfos.end()) {
5637 const auto& displayInfo = it->second;
5638 dump += StringPrintf(INDENT2 "logicalSize=%dx%d\n", displayInfo.logicalWidth,
5639 displayInfo.logicalHeight);
5640 displayInfo.transform.dump(dump, "transform", INDENT4);
5641 } else {
5642 dump += INDENT2 "No DisplayInfo found!\n";
5643 }
5644
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08005645 if (!windowHandles.empty()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08005646 dump += INDENT2 "Windows:\n";
5647 for (size_t i = 0; i < windowHandles.size(); i++) {
chaviw98318de2021-05-19 16:45:23 -05005648 const sp<WindowInfoHandle>& windowHandle = windowHandles[i];
5649 const WindowInfo* windowInfo = windowHandle->getInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005650
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00005651 dump += StringPrintf(INDENT3 "%zu: name='%s', id=%" PRId32 ", displayId=%d, "
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005652 "inputConfig=%s, alpha=%.2f, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005653 "frame=[%d,%d][%d,%d], globalScale=%f, "
Bernardo Rufino49d99e42021-01-18 15:16:59 +00005654 "applicationInfo.name=%s, "
5655 "applicationInfo.token=%s, "
chaviw1ff3d1e2020-07-01 15:53:47 -07005656 "touchableRegion=",
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00005657 i, windowInfo->name.c_str(), windowInfo->id,
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005658 windowInfo->displayId,
5659 windowInfo->inputConfig.string().c_str(),
5660 windowInfo->alpha, windowInfo->frameLeft,
5661 windowInfo->frameTop, windowInfo->frameRight,
5662 windowInfo->frameBottom, windowInfo->globalScaleFactor,
Bernardo Rufino49d99e42021-01-18 15:16:59 +00005663 windowInfo->applicationInfo.name.c_str(),
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07005664 binderToString(windowInfo->applicationInfo.token).c_str());
Bernardo Rufino53fc31e2020-11-03 11:01:07 +00005665 dump += dumpRegion(windowInfo->touchableRegion);
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005666 dump += StringPrintf(", ownerPid=%s, ownerUid=%s, dispatchingTimeout=%" PRId64
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005667 "ms, hasToken=%s, "
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005668 "touchOcclusionMode=%s\n",
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005669 windowInfo->ownerPid.toString().c_str(),
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00005670 windowInfo->ownerUid.toString().c_str(),
Bernardo Rufinoc2f1fad2020-11-04 17:30:57 +00005671 millis(windowInfo->dispatchingTimeout),
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07005672 binderToString(windowInfo->token).c_str(),
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005673 toString(windowInfo->touchOcclusionMode).c_str());
chaviw85b44202020-07-24 11:46:21 -07005674 windowInfo->transform.dump(dump, "transform", INDENT4);
Arthur Hungb92218b2018-08-14 12:00:21 +08005675 }
5676 } else {
5677 dump += INDENT2 "Windows: <none>\n";
5678 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005679 }
5680 } else {
Arthur Hungb92218b2018-08-14 12:00:21 +08005681 dump += INDENT "Displays: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005682 }
5683
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005684 if (!mGlobalMonitorsByDisplay.empty()) {
5685 for (const auto& [displayId, monitors] : mGlobalMonitorsByDisplay) {
5686 dump += StringPrintf(INDENT "Global monitors on display %d:\n", displayId);
Michael Wright3dd60e22019-03-27 22:06:44 +00005687 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005688 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005689 } else {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005690 dump += INDENT "Global Monitors: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005691 }
5692
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005693 const nsecs_t currentTime = now();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005694
5695 // Dump recently dispatched or dropped events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005696 if (!mRecentQueue.empty()) {
5697 dump += StringPrintf(INDENT "RecentQueue: length=%zu\n", mRecentQueue.size());
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005698 for (const std::shared_ptr<EventEntry>& entry : mRecentQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005699 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005700 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005701 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005702 }
5703 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005704 dump += INDENT "RecentQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005705 }
5706
5707 // Dump event currently being dispatched.
5708 if (mPendingEvent) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005709 dump += INDENT "PendingEvent:\n";
5710 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005711 dump += mPendingEvent->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005712 dump += StringPrintf(", age=%" PRId64 "ms\n",
5713 ns2ms(currentTime - mPendingEvent->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005714 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005715 dump += INDENT "PendingEvent: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005716 }
5717
5718 // Dump inbound events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005719 if (!mInboundQueue.empty()) {
5720 dump += StringPrintf(INDENT "InboundQueue: length=%zu\n", mInboundQueue.size());
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005721 for (const std::shared_ptr<EventEntry>& entry : mInboundQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005722 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005723 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005724 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005725 }
5726 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005727 dump += INDENT "InboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005728 }
5729
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005730 if (!mReplacedKeys.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005731 dump += INDENT "ReplacedKeys:\n";
Michael Wright3cec4462022-11-24 22:05:46 +00005732 for (const auto& [replacement, newKeyCode] : mReplacedKeys) {
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005733 dump += StringPrintf(INDENT2 "originalKeyCode=%d, deviceId=%d -> newKeyCode=%d\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005734 replacement.keyCode, replacement.deviceId, newKeyCode);
Michael Wright78f24442014-08-06 15:55:28 -07005735 }
5736 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005737 dump += INDENT "ReplacedKeys: <empty>\n";
Michael Wright78f24442014-08-06 15:55:28 -07005738 }
5739
Prabir Pradhancef936d2021-07-21 16:17:52 +00005740 if (!mCommandQueue.empty()) {
5741 dump += StringPrintf(INDENT "CommandQueue: size=%zu\n", mCommandQueue.size());
5742 } else {
5743 dump += INDENT "CommandQueue: <empty>\n";
5744 }
5745
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005746 if (!mConnectionsByToken.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005747 dump += INDENT "Connections:\n";
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005748 for (const auto& [token, connection] : mConnectionsByToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005749 dump += StringPrintf(INDENT2 "%i: channelName='%s', windowName='%s', "
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005750 "status=%s, monitor=%s, responsive=%s\n",
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005751 connection->inputChannel->getFd().get(),
5752 connection->getInputChannelName().c_str(),
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08005753 connection->getWindowName().c_str(),
5754 ftl::enum_string(connection->status).c_str(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005755 toString(connection->monitor), toString(connection->responsive));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005756
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005757 if (!connection->outboundQueue.empty()) {
5758 dump += StringPrintf(INDENT3 "OutboundQueue: length=%zu\n",
5759 connection->outboundQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005760 dump += dumpQueue(connection->outboundQueue, currentTime);
5761
Michael Wrightd02c5b62014-02-10 15:10:22 -08005762 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005763 dump += INDENT3 "OutboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005764 }
5765
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005766 if (!connection->waitQueue.empty()) {
5767 dump += StringPrintf(INDENT3 "WaitQueue: length=%zu\n",
5768 connection->waitQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005769 dump += dumpQueue(connection->waitQueue, currentTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005770 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005771 dump += INDENT3 "WaitQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005772 }
Siarhei Vishniakoud38a1e02023-07-18 11:55:17 -07005773 std::stringstream inputStateDump;
5774 inputStateDump << connection->inputState;
5775 if (!isEmpty(inputStateDump)) {
5776 dump += INDENT3 "InputState: ";
5777 dump += inputStateDump.str() + "\n";
5778 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005779 }
5780 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005781 dump += INDENT "Connections: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005782 }
5783
5784 if (isAppSwitchPendingLocked()) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005785 dump += StringPrintf(INDENT "AppSwitch: pending, due in %" PRId64 "ms\n",
5786 ns2ms(mAppSwitchDueTime - now()));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005787 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005788 dump += INDENT "AppSwitch: not pending\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005789 }
5790
Antonio Kantek15beb512022-06-13 22:35:41 +00005791 if (!mTouchModePerDisplay.empty()) {
5792 dump += INDENT "TouchModePerDisplay:\n";
5793 for (const auto& [displayId, touchMode] : mTouchModePerDisplay) {
5794 dump += StringPrintf(INDENT2 "Display: %" PRId32 " TouchMode: %s\n", displayId,
5795 std::to_string(touchMode).c_str());
5796 }
5797 } else {
5798 dump += INDENT "TouchModePerDisplay: <none>\n";
5799 }
5800
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005801 dump += INDENT "Configuration:\n";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005802 dump += StringPrintf(INDENT2 "KeyRepeatDelay: %" PRId64 "ms\n", ns2ms(mConfig.keyRepeatDelay));
5803 dump += StringPrintf(INDENT2 "KeyRepeatTimeout: %" PRId64 "ms\n",
5804 ns2ms(mConfig.keyRepeatTimeout));
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00005805 dump += mLatencyTracker.dump(INDENT2);
Siarhei Vishniakoua04181f2021-03-26 05:56:49 +00005806 dump += mLatencyAggregator.dump(INDENT2);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005807}
5808
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005809void InputDispatcher::dumpMonitors(std::string& dump, const std::vector<Monitor>& monitors) const {
Michael Wright3dd60e22019-03-27 22:06:44 +00005810 const size_t numMonitors = monitors.size();
5811 for (size_t i = 0; i < numMonitors; i++) {
5812 const Monitor& monitor = monitors[i];
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005813 const std::shared_ptr<InputChannel>& channel = monitor.inputChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005814 dump += StringPrintf(INDENT2 "%zu: '%s', ", i, channel->getName().c_str());
5815 dump += "\n";
5816 }
5817}
5818
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005819class LooperEventCallback : public LooperCallback {
5820public:
5821 LooperEventCallback(std::function<int(int events)> callback) : mCallback(callback) {}
5822 int handleEvent(int /*fd*/, int events, void* /*data*/) override { return mCallback(events); }
5823
5824private:
5825 std::function<int(int events)> mCallback;
5826};
5827
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005828Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputChannel(const std::string& name) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00005829 if (DEBUG_CHANNEL_CREATION) {
5830 ALOGD("channel '%s' ~ createInputChannel", name.c_str());
5831 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005832
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005833 std::unique_ptr<InputChannel> serverChannel;
Garfield Tan15601662020-09-22 15:32:38 -07005834 std::unique_ptr<InputChannel> clientChannel;
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005835 status_t result = InputChannel::openInputChannelPair(name, serverChannel, clientChannel);
Garfield Tan15601662020-09-22 15:32:38 -07005836
5837 if (result) {
5838 return base::Error(result) << "Failed to open input channel pair with name " << name;
5839 }
5840
Michael Wrightd02c5b62014-02-10 15:10:22 -08005841 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005842 std::scoped_lock _l(mLock);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005843 const sp<IBinder>& token = serverChannel->getConnectionToken();
Garfield Tan15601662020-09-22 15:32:38 -07005844 int fd = serverChannel->getFd();
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07005845 std::shared_ptr<Connection> connection =
5846 std::make_shared<Connection>(std::move(serverChannel), /*monitor=*/false,
5847 mIdGenerator);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005848
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005849 if (mConnectionsByToken.find(token) != mConnectionsByToken.end()) {
5850 ALOGE("Created a new connection, but the token %p is already known", token.get());
5851 }
5852 mConnectionsByToken.emplace(token, connection);
5853
5854 std::function<int(int events)> callback = std::bind(&InputDispatcher::handleReceiveCallback,
5855 this, std::placeholders::_1, token);
5856
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005857 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, sp<LooperEventCallback>::make(callback),
5858 nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005859 } // release lock
5860
5861 // Wake the looper because some connections have changed.
5862 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07005863 return clientChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005864}
5865
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005866Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputMonitor(int32_t displayId,
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005867 const std::string& name,
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005868 gui::Pid pid) {
Garfield Tan15601662020-09-22 15:32:38 -07005869 std::shared_ptr<InputChannel> serverChannel;
5870 std::unique_ptr<InputChannel> clientChannel;
5871 status_t result = openInputChannelPair(name, serverChannel, clientChannel);
5872 if (result) {
5873 return base::Error(result) << "Failed to open input channel pair with name " << name;
5874 }
5875
Michael Wright3dd60e22019-03-27 22:06:44 +00005876 { // acquire lock
5877 std::scoped_lock _l(mLock);
5878
5879 if (displayId < 0) {
Garfield Tan15601662020-09-22 15:32:38 -07005880 return base::Error(BAD_VALUE) << "Attempted to create input monitor with name " << name
5881 << " without a specified display.";
Michael Wright3dd60e22019-03-27 22:06:44 +00005882 }
5883
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07005884 std::shared_ptr<Connection> connection =
5885 std::make_shared<Connection>(serverChannel, /*monitor=*/true, mIdGenerator);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005886 const sp<IBinder>& token = serverChannel->getConnectionToken();
Garfield Tan15601662020-09-22 15:32:38 -07005887 const int fd = serverChannel->getFd();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005888
5889 if (mConnectionsByToken.find(token) != mConnectionsByToken.end()) {
5890 ALOGE("Created a new connection, but the token %p is already known", token.get());
5891 }
5892 mConnectionsByToken.emplace(token, connection);
5893 std::function<int(int events)> callback = std::bind(&InputDispatcher::handleReceiveCallback,
5894 this, std::placeholders::_1, token);
Michael Wright3dd60e22019-03-27 22:06:44 +00005895
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005896 mGlobalMonitorsByDisplay[displayId].emplace_back(serverChannel, pid);
Michael Wright3dd60e22019-03-27 22:06:44 +00005897
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005898 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, sp<LooperEventCallback>::make(callback),
5899 nullptr);
Michael Wright3dd60e22019-03-27 22:06:44 +00005900 }
Garfield Tan15601662020-09-22 15:32:38 -07005901
Michael Wright3dd60e22019-03-27 22:06:44 +00005902 // Wake the looper because some connections have changed.
5903 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07005904 return clientChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005905}
5906
Garfield Tan15601662020-09-22 15:32:38 -07005907status_t InputDispatcher::removeInputChannel(const sp<IBinder>& connectionToken) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005908 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005909 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005910
Harry Cutts33476232023-01-30 19:57:29 +00005911 status_t status = removeInputChannelLocked(connectionToken, /*notify=*/false);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005912 if (status) {
5913 return status;
5914 }
5915 } // release lock
5916
5917 // Wake the poll loop because removing the connection may have changed the current
5918 // synchronization state.
5919 mLooper->wake();
5920 return OK;
5921}
5922
Garfield Tan15601662020-09-22 15:32:38 -07005923status_t InputDispatcher::removeInputChannelLocked(const sp<IBinder>& connectionToken,
5924 bool notify) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07005925 std::shared_ptr<Connection> connection = getConnectionLocked(connectionToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005926 if (connection == nullptr) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005927 // Connection can be removed via socket hang up or an explicit call to 'removeInputChannel'
Michael Wrightd02c5b62014-02-10 15:10:22 -08005928 return BAD_VALUE;
5929 }
5930
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005931 removeConnectionLocked(connection);
Robert Carr5c8a0262018-10-03 16:30:44 -07005932
Michael Wrightd02c5b62014-02-10 15:10:22 -08005933 if (connection->monitor) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005934 removeMonitorChannelLocked(connectionToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005935 }
5936
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005937 mLooper->removeFd(connection->inputChannel->getFd());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005938
5939 nsecs_t currentTime = now();
5940 abortBrokenDispatchCycleLocked(currentTime, connection, notify);
5941
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08005942 connection->status = Connection::Status::ZOMBIE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005943 return OK;
5944}
5945
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005946void InputDispatcher::removeMonitorChannelLocked(const sp<IBinder>& connectionToken) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005947 for (auto it = mGlobalMonitorsByDisplay.begin(); it != mGlobalMonitorsByDisplay.end();) {
5948 auto& [displayId, monitors] = *it;
5949 std::erase_if(monitors, [connectionToken](const Monitor& monitor) {
5950 return monitor.inputChannel->getConnectionToken() == connectionToken;
5951 });
Michael Wright3dd60e22019-03-27 22:06:44 +00005952
Michael Wright3dd60e22019-03-27 22:06:44 +00005953 if (monitors.empty()) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005954 it = mGlobalMonitorsByDisplay.erase(it);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005955 } else {
5956 ++it;
5957 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005958 }
5959}
5960
Michael Wright3dd60e22019-03-27 22:06:44 +00005961status_t InputDispatcher::pilferPointers(const sp<IBinder>& token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005962 std::scoped_lock _l(mLock);
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00005963 return pilferPointersLocked(token);
5964}
Michael Wright3dd60e22019-03-27 22:06:44 +00005965
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00005966status_t InputDispatcher::pilferPointersLocked(const sp<IBinder>& token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005967 const std::shared_ptr<InputChannel> requestingChannel = getInputChannelLocked(token);
5968 if (!requestingChannel) {
5969 ALOGW("Attempted to pilfer pointers from an un-registered channel or invalid token");
5970 return BAD_VALUE;
Michael Wright3dd60e22019-03-27 22:06:44 +00005971 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005972
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005973 auto [statePtr, windowPtr, displayId] = findTouchStateWindowAndDisplayLocked(token);
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005974 if (statePtr == nullptr || windowPtr == nullptr) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005975 ALOGW("Attempted to pilfer points from a channel without any on-going pointer streams."
5976 " Ignoring.");
5977 return BAD_VALUE;
5978 }
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005979 std::set<int32_t> deviceIds = windowPtr->getTouchingDeviceIds();
5980 if (deviceIds.size() != 1) {
5981 LOG(WARNING) << "Can't pilfer. Currently touching devices: " << dumpSet(deviceIds)
5982 << " in window: " << windowPtr->dump();
5983 return BAD_VALUE;
5984 }
5985 const int32_t deviceId = *deviceIds.begin();
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005986
5987 TouchState& state = *statePtr;
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00005988 TouchedWindow& window = *windowPtr;
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005989 // Send cancel events to all the input channels we're stealing from.
Michael Wrightfb04fd52022-11-24 22:31:11 +00005990 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005991 "input channel stole pointer stream");
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005992 options.deviceId = deviceId;
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005993 options.displayId = displayId;
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005994 std::bitset<MAX_POINTER_ID + 1> pointerIds = window.getTouchingPointers(deviceId);
5995 options.pointerIds = pointerIds;
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005996 std::string canceledWindows;
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00005997 for (const TouchedWindow& w : state.windows) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005998 const std::shared_ptr<InputChannel> channel =
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00005999 getInputChannelLocked(w.windowHandle->getToken());
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006000 if (channel != nullptr && channel->getConnectionToken() != token) {
6001 synthesizeCancelationEventsForInputChannelLocked(channel, options);
6002 canceledWindows += canceledWindows.empty() ? "[" : ", ";
6003 canceledWindows += channel->getName();
6004 }
6005 }
6006 canceledWindows += canceledWindows.empty() ? "[]" : "]";
6007 ALOGI("Channel %s is stealing touch from %s", requestingChannel->getName().c_str(),
6008 canceledWindows.c_str());
6009
Prabir Pradhane680f9b2022-02-04 04:24:00 -08006010 // Prevent the gesture from being sent to any other windows.
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00006011 // This only blocks relevant pointers to be sent to other windows
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07006012 window.addPilferingPointers(deviceId, pointerIds);
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00006013
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07006014 state.cancelPointersForWindowsExcept(deviceId, pointerIds, token);
Michael Wright3dd60e22019-03-27 22:06:44 +00006015 return OK;
6016}
6017
Prabir Pradhan99987712020-11-10 18:43:05 -08006018void InputDispatcher::requestPointerCapture(const sp<IBinder>& windowToken, bool enabled) {
6019 { // acquire lock
6020 std::scoped_lock _l(mLock);
6021 if (DEBUG_FOCUS) {
chaviw98318de2021-05-19 16:45:23 -05006022 const sp<WindowInfoHandle> windowHandle = getWindowHandleLocked(windowToken);
Prabir Pradhan99987712020-11-10 18:43:05 -08006023 ALOGI("Request to %s Pointer Capture from: %s.", enabled ? "enable" : "disable",
6024 windowHandle != nullptr ? windowHandle->getName().c_str()
6025 : "token without window");
6026 }
6027
Vishnu Nairc519ff72021-01-21 08:23:08 -08006028 const sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Prabir Pradhan99987712020-11-10 18:43:05 -08006029 if (focusedToken != windowToken) {
6030 ALOGW("Ignoring request to %s Pointer Capture: window does not have focus.",
6031 enabled ? "enable" : "disable");
6032 return;
6033 }
6034
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006035 if (enabled == mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006036 ALOGW("Ignoring request to %s Pointer Capture: "
6037 "window has %s requested pointer capture.",
6038 enabled ? "enable" : "disable", enabled ? "already" : "not");
6039 return;
6040 }
6041
Christine Franksb768bb42021-11-29 12:11:31 -08006042 if (enabled) {
6043 if (std::find(mIneligibleDisplaysForPointerCapture.begin(),
6044 mIneligibleDisplaysForPointerCapture.end(),
6045 mFocusedDisplayId) != mIneligibleDisplaysForPointerCapture.end()) {
6046 ALOGW("Ignoring request to enable Pointer Capture: display is not eligible");
6047 return;
6048 }
6049 }
6050
Prabir Pradhan99987712020-11-10 18:43:05 -08006051 setPointerCaptureLocked(enabled);
6052 } // release lock
6053
6054 // Wake the thread to process command entries.
6055 mLooper->wake();
6056}
6057
Christine Franksb768bb42021-11-29 12:11:31 -08006058void InputDispatcher::setDisplayEligibilityForPointerCapture(int32_t displayId, bool isEligible) {
6059 { // acquire lock
6060 std::scoped_lock _l(mLock);
6061 std::erase(mIneligibleDisplaysForPointerCapture, displayId);
6062 if (!isEligible) {
6063 mIneligibleDisplaysForPointerCapture.push_back(displayId);
6064 }
6065 } // release lock
6066}
6067
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00006068std::optional<gui::Pid> InputDispatcher::findMonitorPidByTokenLocked(const sp<IBinder>& token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006069 for (const auto& [_, monitors] : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00006070 for (const Monitor& monitor : monitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07006071 if (monitor.inputChannel->getConnectionToken() == token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006072 return monitor.pid;
Michael Wright3dd60e22019-03-27 22:06:44 +00006073 }
6074 }
6075 }
6076 return std::nullopt;
6077}
6078
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006079std::shared_ptr<Connection> InputDispatcher::getConnectionLocked(
6080 const sp<IBinder>& inputConnectionToken) const {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07006081 if (inputConnectionToken == nullptr) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07006082 return nullptr;
Arthur Hung3b413f22018-10-26 18:05:34 +08006083 }
6084
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00006085 for (const auto& [token, connection] : mConnectionsByToken) {
6086 if (token == inputConnectionToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07006087 return connection;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006088 }
6089 }
Robert Carr4e670e52018-08-15 13:26:12 -07006090
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07006091 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006092}
6093
Siarhei Vishniakouad991402020-10-28 11:40:09 -05006094std::string InputDispatcher::getConnectionNameLocked(const sp<IBinder>& connectionToken) const {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006095 std::shared_ptr<Connection> connection = getConnectionLocked(connectionToken);
Siarhei Vishniakouad991402020-10-28 11:40:09 -05006096 if (connection == nullptr) {
6097 return "<nullptr>";
6098 }
6099 return connection->getInputChannelName();
6100}
6101
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006102void InputDispatcher::removeConnectionLocked(const std::shared_ptr<Connection>& connection) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006103 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00006104 mConnectionsByToken.erase(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07006105}
6106
Prabir Pradhancef936d2021-07-21 16:17:52 +00006107void InputDispatcher::doDispatchCycleFinishedCommand(nsecs_t finishTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006108 const std::shared_ptr<Connection>& connection,
6109 uint32_t seq, bool handled,
6110 nsecs_t consumeTime) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006111 // Handle post-event policy actions.
6112 std::deque<DispatchEntry*>::iterator dispatchEntryIt = connection->findWaitQueueEntry(seq);
6113 if (dispatchEntryIt == connection->waitQueue.end()) {
6114 return;
6115 }
6116 DispatchEntry* dispatchEntry = *dispatchEntryIt;
6117 const nsecs_t eventDuration = finishTime - dispatchEntry->deliveryTime;
6118 if (eventDuration > SLOW_EVENT_PROCESSING_WARNING_TIMEOUT) {
6119 ALOGI("%s spent %" PRId64 "ms processing %s", connection->getWindowName().c_str(),
6120 ns2ms(eventDuration), dispatchEntry->eventEntry->getDescription().c_str());
6121 }
6122 if (shouldReportFinishedEvent(*dispatchEntry, *connection)) {
6123 mLatencyTracker.trackFinishedEvent(dispatchEntry->eventEntry->id,
6124 connection->inputChannel->getConnectionToken(),
6125 dispatchEntry->deliveryTime, consumeTime, finishTime);
6126 }
6127
6128 bool restartEvent;
6129 if (dispatchEntry->eventEntry->type == EventEntry::Type::KEY) {
6130 KeyEntry& keyEntry = static_cast<KeyEntry&>(*(dispatchEntry->eventEntry));
6131 restartEvent =
6132 afterKeyEventLockedInterruptable(connection, dispatchEntry, keyEntry, handled);
6133 } else if (dispatchEntry->eventEntry->type == EventEntry::Type::MOTION) {
6134 MotionEntry& motionEntry = static_cast<MotionEntry&>(*(dispatchEntry->eventEntry));
6135 restartEvent = afterMotionEventLockedInterruptable(connection, dispatchEntry, motionEntry,
6136 handled);
6137 } else {
6138 restartEvent = false;
6139 }
6140
6141 // Dequeue the event and start the next cycle.
6142 // Because the lock might have been released, it is possible that the
6143 // contents of the wait queue to have been drained, so we need to double-check
6144 // a few things.
6145 dispatchEntryIt = connection->findWaitQueueEntry(seq);
6146 if (dispatchEntryIt != connection->waitQueue.end()) {
6147 dispatchEntry = *dispatchEntryIt;
6148 connection->waitQueue.erase(dispatchEntryIt);
6149 const sp<IBinder>& connectionToken = connection->inputChannel->getConnectionToken();
6150 mAnrTracker.erase(dispatchEntry->timeoutTime, connectionToken);
6151 if (!connection->responsive) {
6152 connection->responsive = isConnectionResponsive(*connection);
6153 if (connection->responsive) {
6154 // The connection was unresponsive, and now it's responsive.
6155 processConnectionResponsiveLocked(*connection);
6156 }
6157 }
6158 traceWaitQueueLength(*connection);
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08006159 if (restartEvent && connection->status == Connection::Status::NORMAL) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006160 connection->outboundQueue.push_front(dispatchEntry);
6161 traceOutboundQueueLength(*connection);
6162 } else {
6163 releaseDispatchEntry(dispatchEntry);
6164 }
6165 }
6166
6167 // Start the next dispatch cycle for this connection.
6168 startDispatchCycleLocked(now(), connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006169}
6170
Prabir Pradhancef936d2021-07-21 16:17:52 +00006171void InputDispatcher::sendFocusChangedCommandLocked(const sp<IBinder>& oldToken,
6172 const sp<IBinder>& newToken) {
6173 auto command = [this, oldToken, newToken]() REQUIRES(mLock) {
6174 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00006175 mPolicy.notifyFocusChanged(oldToken, newToken);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006176 };
6177 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08006178}
6179
Prabir Pradhancef936d2021-07-21 16:17:52 +00006180void InputDispatcher::sendDropWindowCommandLocked(const sp<IBinder>& token, float x, float y) {
6181 auto command = [this, token, x, y]() REQUIRES(mLock) {
6182 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00006183 mPolicy.notifyDropWindow(token, x, y);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006184 };
6185 postCommandLocked(std::move(command));
Robert Carrf759f162018-11-13 12:57:11 -08006186}
6187
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006188void InputDispatcher::onAnrLocked(const std::shared_ptr<Connection>& connection) {
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006189 if (connection == nullptr) {
6190 LOG_ALWAYS_FATAL("Caller must check for nullness");
6191 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006192 // Since we are allowing the policy to extend the timeout, maybe the waitQueue
6193 // is already healthy again. Don't raise ANR in this situation
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006194 if (connection->waitQueue.empty()) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006195 ALOGI("Not raising ANR because the connection %s has recovered",
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006196 connection->inputChannel->getName().c_str());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006197 return;
6198 }
6199 /**
6200 * The "oldestEntry" is the entry that was first sent to the application. That entry, however,
6201 * may not be the one that caused the timeout to occur. One possibility is that window timeout
6202 * has changed. This could cause newer entries to time out before the already dispatched
6203 * entries. In that situation, the newest entries caused ANR. But in all likelihood, the app
6204 * processes the events linearly. So providing information about the oldest entry seems to be
6205 * most useful.
6206 */
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006207 DispatchEntry* oldestEntry = *connection->waitQueue.begin();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006208 const nsecs_t currentWait = now() - oldestEntry->deliveryTime;
6209 std::string reason =
6210 android::base::StringPrintf("%s is not responding. Waited %" PRId64 "ms for %s",
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006211 connection->inputChannel->getName().c_str(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006212 ns2ms(currentWait),
6213 oldestEntry->eventEntry->getDescription().c_str());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006214 sp<IBinder> connectionToken = connection->inputChannel->getConnectionToken();
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -06006215 updateLastAnrStateLocked(getWindowHandleLocked(connectionToken), reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006216
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006217 processConnectionUnresponsiveLocked(*connection, std::move(reason));
6218
6219 // Stop waking up for events on this connection, it is already unresponsive
6220 cancelEventsForAnrLocked(connection);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006221}
6222
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05006223void InputDispatcher::onAnrLocked(std::shared_ptr<InputApplicationHandle> application) {
6224 std::string reason =
6225 StringPrintf("%s does not have a focused window", application->getName().c_str());
6226 updateLastAnrStateLocked(*application, reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006227
Yabin Cui8eb9c552023-06-08 18:05:07 +00006228 auto command = [this, app = std::move(application)]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006229 scoped_unlock unlock(mLock);
Yabin Cuiced952f2023-06-09 21:12:51 +00006230 mPolicy.notifyNoFocusedWindowAnr(app);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006231 };
6232 postCommandLocked(std::move(command));
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00006233}
6234
chaviw98318de2021-05-19 16:45:23 -05006235void InputDispatcher::updateLastAnrStateLocked(const sp<WindowInfoHandle>& window,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006236 const std::string& reason) {
6237 const std::string windowLabel = getApplicationWindowLabel(nullptr, window);
6238 updateLastAnrStateLocked(windowLabel, reason);
6239}
6240
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05006241void InputDispatcher::updateLastAnrStateLocked(const InputApplicationHandle& application,
6242 const std::string& reason) {
6243 const std::string windowLabel = getApplicationWindowLabel(&application, nullptr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006244 updateLastAnrStateLocked(windowLabel, reason);
6245}
6246
6247void InputDispatcher::updateLastAnrStateLocked(const std::string& windowLabel,
6248 const std::string& reason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006249 // Capture a record of the InputDispatcher state at the time of the ANR.
Yi Kong9b14ac62018-07-17 13:48:38 -07006250 time_t t = time(nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006251 struct tm tm;
6252 localtime_r(&t, &tm);
6253 char timestr[64];
6254 strftime(timestr, sizeof(timestr), "%F %T", &tm);
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006255 mLastAnrState.clear();
6256 mLastAnrState += INDENT "ANR:\n";
6257 mLastAnrState += StringPrintf(INDENT2 "Time: %s\n", timestr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006258 mLastAnrState += StringPrintf(INDENT2 "Reason: %s\n", reason.c_str());
6259 mLastAnrState += StringPrintf(INDENT2 "Window: %s\n", windowLabel.c_str());
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006260 dumpDispatchStateLocked(mLastAnrState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006261}
6262
Prabir Pradhancef936d2021-07-21 16:17:52 +00006263void InputDispatcher::doInterceptKeyBeforeDispatchingCommand(const sp<IBinder>& focusedWindowToken,
6264 KeyEntry& entry) {
6265 const KeyEvent event = createKeyEvent(entry);
6266 nsecs_t delay = 0;
6267 { // release lock
6268 scoped_unlock unlock(mLock);
6269 android::base::Timer t;
Prabir Pradhana41d2442023-04-20 21:30:40 +00006270 delay = mPolicy.interceptKeyBeforeDispatching(focusedWindowToken, event, entry.policyFlags);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006271 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
6272 ALOGW("Excessive delay in interceptKeyBeforeDispatching; took %s ms",
6273 std::to_string(t.duration().count()).c_str());
6274 }
6275 } // acquire lock
Michael Wrightd02c5b62014-02-10 15:10:22 -08006276
6277 if (delay < 0) {
Michael Wright5caf55a2022-11-24 22:31:42 +00006278 entry.interceptKeyResult = KeyEntry::InterceptKeyResult::SKIP;
Prabir Pradhancef936d2021-07-21 16:17:52 +00006279 } else if (delay == 0) {
Michael Wright5caf55a2022-11-24 22:31:42 +00006280 entry.interceptKeyResult = KeyEntry::InterceptKeyResult::CONTINUE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006281 } else {
Michael Wright5caf55a2022-11-24 22:31:42 +00006282 entry.interceptKeyResult = KeyEntry::InterceptKeyResult::TRY_AGAIN_LATER;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006283 entry.interceptKeyWakeupTime = now() + delay;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006284 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006285}
6286
Prabir Pradhancef936d2021-07-21 16:17:52 +00006287void InputDispatcher::sendWindowUnresponsiveCommandLocked(const sp<IBinder>& token,
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00006288 std::optional<gui::Pid> pid,
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006289 std::string reason) {
Yabin Cui8eb9c552023-06-08 18:05:07 +00006290 auto command = [this, token, pid, r = std::move(reason)]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006291 scoped_unlock unlock(mLock);
Yabin Cuiced952f2023-06-09 21:12:51 +00006292 mPolicy.notifyWindowUnresponsive(token, pid, r);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006293 };
6294 postCommandLocked(std::move(command));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006295}
6296
Prabir Pradhanedd96402022-02-15 01:46:16 -08006297void InputDispatcher::sendWindowResponsiveCommandLocked(const sp<IBinder>& token,
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00006298 std::optional<gui::Pid> pid) {
Prabir Pradhanedd96402022-02-15 01:46:16 -08006299 auto command = [this, token, pid]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006300 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00006301 mPolicy.notifyWindowResponsive(token, pid);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006302 };
6303 postCommandLocked(std::move(command));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006304}
6305
6306/**
6307 * Tell the policy that a connection has become unresponsive so that it can start ANR.
6308 * Check whether the connection of interest is a monitor or a window, and add the corresponding
6309 * command entry to the command queue.
6310 */
6311void InputDispatcher::processConnectionUnresponsiveLocked(const Connection& connection,
6312 std::string reason) {
6313 const sp<IBinder>& connectionToken = connection.inputChannel->getConnectionToken();
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00006314 std::optional<gui::Pid> pid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006315 if (connection.monitor) {
6316 ALOGW("Monitor %s is unresponsive: %s", connection.inputChannel->getName().c_str(),
6317 reason.c_str());
Prabir Pradhanedd96402022-02-15 01:46:16 -08006318 pid = findMonitorPidByTokenLocked(connectionToken);
6319 } else {
6320 // The connection is a window
6321 ALOGW("Window %s is unresponsive: %s", connection.inputChannel->getName().c_str(),
6322 reason.c_str());
6323 const sp<WindowInfoHandle> handle = getWindowHandleLocked(connectionToken);
6324 if (handle != nullptr) {
6325 pid = handle->getInfo()->ownerPid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006326 }
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006327 }
Prabir Pradhanedd96402022-02-15 01:46:16 -08006328 sendWindowUnresponsiveCommandLocked(connectionToken, pid, std::move(reason));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006329}
6330
6331/**
6332 * Tell the policy that a connection has become responsive so that it can stop ANR.
6333 */
6334void InputDispatcher::processConnectionResponsiveLocked(const Connection& connection) {
6335 const sp<IBinder>& connectionToken = connection.inputChannel->getConnectionToken();
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00006336 std::optional<gui::Pid> pid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006337 if (connection.monitor) {
Prabir Pradhanedd96402022-02-15 01:46:16 -08006338 pid = findMonitorPidByTokenLocked(connectionToken);
6339 } else {
6340 // The connection is a window
6341 const sp<WindowInfoHandle> handle = getWindowHandleLocked(connectionToken);
6342 if (handle != nullptr) {
6343 pid = handle->getInfo()->ownerPid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006344 }
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006345 }
Prabir Pradhanedd96402022-02-15 01:46:16 -08006346 sendWindowResponsiveCommandLocked(connectionToken, pid);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006347}
6348
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006349bool InputDispatcher::afterKeyEventLockedInterruptable(
6350 const std::shared_ptr<Connection>& connection, DispatchEntry* dispatchEntry,
6351 KeyEntry& keyEntry, bool handled) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006352 if (keyEntry.flags & AKEY_EVENT_FLAG_FALLBACK) {
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006353 if (!handled) {
6354 // Report the key as unhandled, since the fallback was not handled.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006355 mReporter->reportUnhandledKey(keyEntry.id);
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006356 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006357 return false;
6358 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006359
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006360 // Get the fallback key state.
6361 // Clear it out after dispatching the UP.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006362 int32_t originalKeyCode = keyEntry.keyCode;
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006363 std::optional<int32_t> fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006364 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006365 connection->inputState.removeFallbackKey(originalKeyCode);
6366 }
6367
6368 if (handled || !dispatchEntry->hasForegroundTarget()) {
6369 // If the application handles the original key for which we previously
6370 // generated a fallback or if the window is not a foreground window,
6371 // then cancel the associated fallback key, if any.
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006372 if (fallbackKeyCode) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006373 // Dispatch the unhandled key to the policy with the cancel flag.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006374 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6375 ALOGD("Unhandled key event: Asking policy to cancel fallback action. "
6376 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6377 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount,
6378 keyEntry.policyFlags);
6379 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006380 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006381 event.setFlags(event.getFlags() | AKEY_EVENT_FLAG_CANCELED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006382
6383 mLock.unlock();
6384
Prabir Pradhana41d2442023-04-20 21:30:40 +00006385 if (const auto unhandledKeyFallback =
6386 mPolicy.dispatchUnhandledKey(connection->inputChannel->getConnectionToken(),
6387 event, keyEntry.policyFlags);
6388 unhandledKeyFallback) {
6389 event = *unhandledKeyFallback;
6390 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006391
6392 mLock.lock();
6393
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006394 // Cancel the fallback key.
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006395 if (*fallbackKeyCode != AKEYCODE_UNKNOWN) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00006396 CancelationOptions options(CancelationOptions::Mode::CANCEL_FALLBACK_EVENTS,
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006397 "application handled the original non-fallback key "
6398 "or is no longer a foreground target, "
6399 "canceling previously dispatched fallback key");
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006400 options.keyCode = *fallbackKeyCode;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006401 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006402 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006403 connection->inputState.removeFallbackKey(originalKeyCode);
6404 }
6405 } else {
6406 // If the application did not handle a non-fallback key, first check
6407 // that we are in a good state to perform unhandled key event processing
6408 // Then ask the policy what to do with it.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006409 bool initialDown = keyEntry.action == AKEY_EVENT_ACTION_DOWN && keyEntry.repeatCount == 0;
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006410 if (!fallbackKeyCode && !initialDown) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006411 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6412 ALOGD("Unhandled key event: Skipping unhandled key event processing "
6413 "since this is not an initial down. "
6414 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6415 originalKeyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
6416 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006417 return false;
6418 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006419
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006420 // Dispatch the unhandled key to the policy.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006421 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6422 ALOGD("Unhandled key event: Asking policy to perform fallback action. "
6423 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6424 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
6425 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006426 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006427
6428 mLock.unlock();
6429
Prabir Pradhana41d2442023-04-20 21:30:40 +00006430 bool fallback = false;
6431 if (auto fb = mPolicy.dispatchUnhandledKey(connection->inputChannel->getConnectionToken(),
6432 event, keyEntry.policyFlags);
6433 fb) {
6434 fallback = true;
6435 event = *fb;
6436 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006437
6438 mLock.lock();
6439
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08006440 if (connection->status != Connection::Status::NORMAL) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006441 connection->inputState.removeFallbackKey(originalKeyCode);
6442 return false;
6443 }
6444
6445 // Latch the fallback keycode for this key on an initial down.
6446 // The fallback keycode cannot change at any other point in the lifecycle.
6447 if (initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006448 if (fallback) {
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006449 *fallbackKeyCode = event.getKeyCode();
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006450 } else {
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006451 *fallbackKeyCode = AKEYCODE_UNKNOWN;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006452 }
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006453 connection->inputState.setFallbackKey(originalKeyCode, *fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006454 }
6455
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006456 ALOG_ASSERT(fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006457
6458 // Cancel the fallback key if the policy decides not to send it anymore.
6459 // We will continue to dispatch the key to the policy but we will no
6460 // longer dispatch a fallback key to the application.
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006461 if (*fallbackKeyCode != AKEYCODE_UNKNOWN &&
6462 (!fallback || *fallbackKeyCode != event.getKeyCode())) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006463 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6464 if (fallback) {
6465 ALOGD("Unhandled key event: Policy requested to send key %d"
6466 "as a fallback for %d, but on the DOWN it had requested "
6467 "to send %d instead. Fallback canceled.",
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006468 event.getKeyCode(), originalKeyCode, *fallbackKeyCode);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006469 } else {
6470 ALOGD("Unhandled key event: Policy did not request fallback for %d, "
6471 "but on the DOWN it had requested to send %d. "
6472 "Fallback canceled.",
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006473 originalKeyCode, *fallbackKeyCode);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006474 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006475 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006476
Michael Wrightfb04fd52022-11-24 22:31:11 +00006477 CancelationOptions options(CancelationOptions::Mode::CANCEL_FALLBACK_EVENTS,
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006478 "canceling fallback, policy no longer desires it");
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006479 options.keyCode = *fallbackKeyCode;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006480 synthesizeCancelationEventsForConnectionLocked(connection, options);
6481
6482 fallback = false;
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006483 *fallbackKeyCode = AKEYCODE_UNKNOWN;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006484 if (keyEntry.action != AKEY_EVENT_ACTION_UP) {
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006485 connection->inputState.setFallbackKey(originalKeyCode, *fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006486 }
6487 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006488
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006489 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6490 {
6491 std::string msg;
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006492 const std::map<int32_t, int32_t>& fallbackKeys =
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006493 connection->inputState.getFallbackKeys();
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006494 for (const auto& [key, value] : fallbackKeys) {
6495 msg += StringPrintf(", %d->%d", key, value);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006496 }
6497 ALOGD("Unhandled key event: %zu currently tracked fallback keys%s.",
6498 fallbackKeys.size(), msg.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006499 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006500 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006501
6502 if (fallback) {
6503 // Restart the dispatch cycle using the fallback key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006504 keyEntry.eventTime = event.getEventTime();
6505 keyEntry.deviceId = event.getDeviceId();
6506 keyEntry.source = event.getSource();
6507 keyEntry.displayId = event.getDisplayId();
6508 keyEntry.flags = event.getFlags() | AKEY_EVENT_FLAG_FALLBACK;
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006509 keyEntry.keyCode = *fallbackKeyCode;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006510 keyEntry.scanCode = event.getScanCode();
6511 keyEntry.metaState = event.getMetaState();
6512 keyEntry.repeatCount = event.getRepeatCount();
6513 keyEntry.downTime = event.getDownTime();
6514 keyEntry.syntheticRepeat = false;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006515
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006516 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6517 ALOGD("Unhandled key event: Dispatching fallback key. "
6518 "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006519 originalKeyCode, *fallbackKeyCode, keyEntry.metaState);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006520 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006521 return true; // restart the event
6522 } else {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006523 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6524 ALOGD("Unhandled key event: No fallback key.");
6525 }
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006526
6527 // Report the key as unhandled, since there is no fallback key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006528 mReporter->reportUnhandledKey(keyEntry.id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006529 }
6530 }
6531 return false;
6532}
6533
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006534bool InputDispatcher::afterMotionEventLockedInterruptable(
6535 const std::shared_ptr<Connection>& connection, DispatchEntry* dispatchEntry,
6536 MotionEntry& motionEntry, bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006537 return false;
6538}
6539
Michael Wrightd02c5b62014-02-10 15:10:22 -08006540void InputDispatcher::traceInboundQueueLengthLocked() {
6541 if (ATRACE_ENABLED()) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07006542 ATRACE_INT("iq", mInboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006543 }
6544}
6545
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006546void InputDispatcher::traceOutboundQueueLength(const Connection& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006547 if (ATRACE_ENABLED()) {
6548 char counterName[40];
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006549 snprintf(counterName, sizeof(counterName), "oq:%s", connection.getWindowName().c_str());
6550 ATRACE_INT(counterName, connection.outboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006551 }
6552}
6553
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006554void InputDispatcher::traceWaitQueueLength(const Connection& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006555 if (ATRACE_ENABLED()) {
6556 char counterName[40];
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006557 snprintf(counterName, sizeof(counterName), "wq:%s", connection.getWindowName().c_str());
6558 ATRACE_INT(counterName, connection.waitQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006559 }
6560}
6561
Siarhei Vishniakou5e20f272023-06-08 17:24:44 -07006562void InputDispatcher::dump(std::string& dump) const {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006563 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006564
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006565 dump += "Input Dispatcher State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08006566 dumpDispatchStateLocked(dump);
6567
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006568 if (!mLastAnrState.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006569 dump += "\nInput Dispatcher State at time of last ANR:\n";
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006570 dump += mLastAnrState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006571 }
6572}
6573
6574void InputDispatcher::monitor() {
6575 // Acquire and release the lock to ensure that the dispatcher has not deadlocked.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006576 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006577 mLooper->wake();
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006578 mDispatcherIsAlive.wait(_l);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006579}
6580
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08006581/**
6582 * Wake up the dispatcher and wait until it processes all events and commands.
6583 * The notification of mDispatcherEnteredIdle is guaranteed to happen after wake(), so
6584 * this method can be safely called from any thread, as long as you've ensured that
6585 * the work you are interested in completing has already been queued.
6586 */
Siarhei Vishniakoua66d65e2023-06-16 10:32:51 -07006587bool InputDispatcher::waitForIdle() const {
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08006588 /**
6589 * Timeout should represent the longest possible time that a device might spend processing
6590 * events and commands.
6591 */
6592 constexpr std::chrono::duration TIMEOUT = 100ms;
6593 std::unique_lock lock(mLock);
6594 mLooper->wake();
6595 std::cv_status result = mDispatcherEnteredIdle.wait_for(lock, TIMEOUT);
6596 return result == std::cv_status::no_timeout;
6597}
6598
Vishnu Naire798b472020-07-23 13:52:21 -07006599/**
6600 * Sets focus to the window identified by the token. This must be called
6601 * after updating any input window handles.
6602 *
6603 * Params:
6604 * request.token - input channel token used to identify the window that should gain focus.
6605 * request.focusedToken - the token that the caller expects currently to be focused. If the
6606 * specified token does not match the currently focused window, this request will be dropped.
6607 * If the specified focused token matches the currently focused window, the call will succeed.
6608 * Set this to "null" if this call should succeed no matter what the currently focused token is.
6609 * request.timestamp - SYSTEM_TIME_MONOTONIC timestamp in nanos set by the client (wm)
6610 * when requesting the focus change. This determines which request gets
6611 * precedence if there is a focus change request from another source such as pointer down.
6612 */
Vishnu Nair958da932020-08-21 17:12:37 -07006613void InputDispatcher::setFocusedWindow(const FocusRequest& request) {
6614 { // acquire lock
6615 std::scoped_lock _l(mLock);
Vishnu Nairc519ff72021-01-21 08:23:08 -08006616 std::optional<FocusResolver::FocusChanges> changes =
6617 mFocusResolver.setFocusedWindow(request, getWindowHandlesLocked(request.displayId));
6618 if (changes) {
6619 onFocusChangedLocked(*changes);
Vishnu Nair958da932020-08-21 17:12:37 -07006620 }
6621 } // release lock
6622 // Wake up poll loop since it may need to make new input dispatching choices.
6623 mLooper->wake();
6624}
6625
Vishnu Nairc519ff72021-01-21 08:23:08 -08006626void InputDispatcher::onFocusChangedLocked(const FocusResolver::FocusChanges& changes) {
6627 if (changes.oldFocus) {
6628 std::shared_ptr<InputChannel> focusedInputChannel = getInputChannelLocked(changes.oldFocus);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006629 if (focusedInputChannel) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00006630 CancelationOptions options(CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS,
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006631 "focus left window");
6632 synthesizeCancelationEventsForInputChannelLocked(focusedInputChannel, options);
Harry Cutts33476232023-01-30 19:57:29 +00006633 enqueueFocusEventLocked(changes.oldFocus, /*hasFocus=*/false, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006634 }
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006635 }
Vishnu Nairc519ff72021-01-21 08:23:08 -08006636 if (changes.newFocus) {
Harry Cutts33476232023-01-30 19:57:29 +00006637 enqueueFocusEventLocked(changes.newFocus, /*hasFocus=*/true, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006638 }
6639
Prabir Pradhan99987712020-11-10 18:43:05 -08006640 // If a window has pointer capture, then it must have focus. We need to ensure that this
6641 // contract is upheld when pointer capture is being disabled due to a loss of window focus.
6642 // If the window loses focus before it loses pointer capture, then the window can be in a state
6643 // where it has pointer capture but not focus, violating the contract. Therefore we must
6644 // dispatch the pointer capture event before the focus event. Since focus events are added to
6645 // the front of the queue (above), we add the pointer capture event to the front of the queue
6646 // after the focus events are added. This ensures the pointer capture event ends up at the
6647 // front.
6648 disablePointerCaptureForcedLocked();
6649
Vishnu Nairc519ff72021-01-21 08:23:08 -08006650 if (mFocusedDisplayId == changes.displayId) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006651 sendFocusChangedCommandLocked(changes.oldFocus, changes.newFocus);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006652 }
6653}
Vishnu Nair958da932020-08-21 17:12:37 -07006654
Prabir Pradhan99987712020-11-10 18:43:05 -08006655void InputDispatcher::disablePointerCaptureForcedLocked() {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006656 if (!mCurrentPointerCaptureRequest.enable && !mWindowTokenWithPointerCapture) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006657 return;
6658 }
6659
6660 ALOGD_IF(DEBUG_FOCUS, "Disabling Pointer Capture because the window lost focus.");
6661
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006662 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006663 setPointerCaptureLocked(false);
6664 }
6665
6666 if (!mWindowTokenWithPointerCapture) {
6667 // No need to send capture changes because no window has capture.
6668 return;
6669 }
6670
6671 if (mPendingEvent != nullptr) {
6672 // Move the pending event to the front of the queue. This will give the chance
6673 // for the pending event to be dropped if it is a captured event.
6674 mInboundQueue.push_front(mPendingEvent);
6675 mPendingEvent = nullptr;
6676 }
6677
6678 auto entry = std::make_unique<PointerCaptureChangedEntry>(mIdGenerator.nextId(), now(),
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006679 mCurrentPointerCaptureRequest);
Prabir Pradhan99987712020-11-10 18:43:05 -08006680 mInboundQueue.push_front(std::move(entry));
6681}
6682
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006683void InputDispatcher::setPointerCaptureLocked(bool enable) {
6684 mCurrentPointerCaptureRequest.enable = enable;
6685 mCurrentPointerCaptureRequest.seq++;
6686 auto command = [this, request = mCurrentPointerCaptureRequest]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006687 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00006688 mPolicy.setPointerCapture(request);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006689 };
6690 postCommandLocked(std::move(command));
Prabir Pradhan99987712020-11-10 18:43:05 -08006691}
6692
Vishnu Nair599f1412021-06-21 10:39:58 -07006693void InputDispatcher::displayRemoved(int32_t displayId) {
6694 { // acquire lock
6695 std::scoped_lock _l(mLock);
6696 // Set an empty list to remove all handles from the specific display.
Harry Cutts101ee9b2023-07-06 18:04:14 +00006697 setInputWindowsLocked(/*windowInfoHandles=*/{}, displayId);
Vishnu Nair599f1412021-06-21 10:39:58 -07006698 setFocusedApplicationLocked(displayId, nullptr);
6699 // Call focus resolver to clean up stale requests. This must be called after input windows
6700 // have been removed for the removed display.
6701 mFocusResolver.displayRemoved(displayId);
Christine Franksb768bb42021-11-29 12:11:31 -08006702 // Reset pointer capture eligibility, regardless of previous state.
6703 std::erase(mIneligibleDisplaysForPointerCapture, displayId);
Antonio Kantek15beb512022-06-13 22:35:41 +00006704 // Remove the associated touch mode state.
6705 mTouchModePerDisplay.erase(displayId);
Siarhei Vishniakou5c02a712023-05-15 15:45:02 -07006706 mVerifiersByDisplay.erase(displayId);
Vishnu Nair599f1412021-06-21 10:39:58 -07006707 } // release lock
6708
6709 // Wake up poll loop since it may need to make new input dispatching choices.
6710 mLooper->wake();
6711}
6712
Patrick Williamsd828f302023-04-28 17:52:08 -05006713void InputDispatcher::onWindowInfosChanged(const gui::WindowInfosUpdate& update) {
chaviw15fab6f2021-06-07 14:15:52 -05006714 // The listener sends the windows as a flattened array. Separate the windows by display for
6715 // more convenient parsing.
6716 std::unordered_map<int32_t, std::vector<sp<WindowInfoHandle>>> handlesPerDisplay;
Patrick Williamsd828f302023-04-28 17:52:08 -05006717 for (const auto& info : update.windowInfos) {
chaviw15fab6f2021-06-07 14:15:52 -05006718 handlesPerDisplay.emplace(info.displayId, std::vector<sp<WindowInfoHandle>>());
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07006719 handlesPerDisplay[info.displayId].push_back(sp<WindowInfoHandle>::make(info));
chaviw15fab6f2021-06-07 14:15:52 -05006720 }
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006721
6722 { // acquire lock
6723 std::scoped_lock _l(mLock);
Prabir Pradhan814fe082022-07-22 20:22:18 +00006724
6725 // Ensure that we have an entry created for all existing displays so that if a displayId has
6726 // no windows, we can tell that the windows were removed from the display.
6727 for (const auto& [displayId, _] : mWindowHandlesByDisplay) {
6728 handlesPerDisplay[displayId];
6729 }
6730
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006731 mDisplayInfos.clear();
Patrick Williamsd828f302023-04-28 17:52:08 -05006732 for (const auto& displayInfo : update.displayInfos) {
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006733 mDisplayInfos.emplace(displayInfo.displayId, displayInfo);
6734 }
6735
6736 for (const auto& [displayId, handles] : handlesPerDisplay) {
6737 setInputWindowsLocked(handles, displayId);
6738 }
Patrick Williams9464b2c2023-05-23 11:22:04 -05006739
6740 if (update.vsyncId < mWindowInfosVsyncId) {
6741 ALOGE("Received out of order window infos update. Last update vsync id: %" PRId64
6742 ", current update vsync id: %" PRId64,
6743 mWindowInfosVsyncId, update.vsyncId);
6744 }
6745 mWindowInfosVsyncId = update.vsyncId;
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006746 }
6747 // Wake up poll loop since it may need to make new input dispatching choices.
6748 mLooper->wake();
chaviw15fab6f2021-06-07 14:15:52 -05006749}
6750
Vishnu Nair062a8672021-09-03 16:07:44 -07006751bool InputDispatcher::shouldDropInput(
6752 const EventEntry& entry, const sp<android::gui::WindowInfoHandle>& windowHandle) const {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006753 if (windowHandle->getInfo()->inputConfig.test(WindowInfo::InputConfig::DROP_INPUT) ||
6754 (windowHandle->getInfo()->inputConfig.test(
6755 WindowInfo::InputConfig::DROP_INPUT_IF_OBSCURED) &&
Vishnu Nair062a8672021-09-03 16:07:44 -07006756 isWindowObscuredLocked(windowHandle))) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006757 ALOGW("Dropping %s event targeting %s as requested by the input configuration {%s} on "
6758 "display %" PRId32 ".",
Vishnu Nair062a8672021-09-03 16:07:44 -07006759 ftl::enum_string(entry.type).c_str(), windowHandle->getName().c_str(),
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006760 windowHandle->getInfo()->inputConfig.string().c_str(),
Vishnu Nair062a8672021-09-03 16:07:44 -07006761 windowHandle->getInfo()->displayId);
6762 return true;
6763 }
6764 return false;
6765}
6766
Siarhei Vishniakou18050092021-09-01 13:32:49 -07006767void InputDispatcher::DispatcherWindowListener::onWindowInfosChanged(
Patrick Williamsd828f302023-04-28 17:52:08 -05006768 const gui::WindowInfosUpdate& update) {
6769 mDispatcher.onWindowInfosChanged(update);
Siarhei Vishniakou18050092021-09-01 13:32:49 -07006770}
6771
Arthur Hungdfd528e2021-12-08 13:23:04 +00006772void InputDispatcher::cancelCurrentTouch() {
6773 {
6774 std::scoped_lock _l(mLock);
6775 ALOGD("Canceling all ongoing pointer gestures on all displays.");
Michael Wrightfb04fd52022-11-24 22:31:11 +00006776 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
Arthur Hungdfd528e2021-12-08 13:23:04 +00006777 "cancel current touch");
6778 synthesizeCancelationEventsForAllConnectionsLocked(options);
6779
6780 mTouchStatesByDisplay.clear();
Arthur Hungdfd528e2021-12-08 13:23:04 +00006781 }
6782 // Wake up poll loop since there might be work to do.
6783 mLooper->wake();
6784}
6785
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006786void InputDispatcher::setMonitorDispatchingTimeoutForTest(std::chrono::nanoseconds timeout) {
6787 std::scoped_lock _l(mLock);
6788 mMonitorDispatchingTimeout = timeout;
6789}
6790
Arthur Hungc539dbb2022-12-08 07:45:36 +00006791void InputDispatcher::slipWallpaperTouch(ftl::Flags<InputTarget::Flags> targetFlags,
6792 const sp<WindowInfoHandle>& oldWindowHandle,
6793 const sp<WindowInfoHandle>& newWindowHandle,
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07006794 TouchState& state, int32_t deviceId, int32_t pointerId,
Siarhei Vishniakoubf880522023-05-01 11:03:22 -07006795 std::vector<InputTarget>& targets) const {
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08006796 std::bitset<MAX_POINTER_ID + 1> pointerIds;
6797 pointerIds.set(pointerId);
Arthur Hungc539dbb2022-12-08 07:45:36 +00006798 const bool oldHasWallpaper = oldWindowHandle->getInfo()->inputConfig.test(
6799 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
6800 const bool newHasWallpaper = targetFlags.test(InputTarget::Flags::FOREGROUND) &&
6801 newWindowHandle->getInfo()->inputConfig.test(
6802 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
6803 const sp<WindowInfoHandle> oldWallpaper =
6804 oldHasWallpaper ? state.getWallpaperWindow() : nullptr;
6805 const sp<WindowInfoHandle> newWallpaper =
6806 newHasWallpaper ? findWallpaperWindowBelow(newWindowHandle) : nullptr;
6807 if (oldWallpaper == newWallpaper) {
6808 return;
6809 }
6810
6811 if (oldWallpaper != nullptr) {
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08006812 const TouchedWindow& oldTouchedWindow = state.getTouchedWindow(oldWallpaper);
6813 addWindowTargetLocked(oldWallpaper,
6814 oldTouchedWindow.targetFlags |
6815 InputTarget::Flags::DISPATCH_AS_SLIPPERY_EXIT,
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07006816 pointerIds, oldTouchedWindow.getDownTimeInTarget(deviceId), targets);
6817 state.removeTouchingPointerFromWindow(deviceId, pointerId, oldWallpaper);
Arthur Hungc539dbb2022-12-08 07:45:36 +00006818 }
6819
6820 if (newWallpaper != nullptr) {
6821 state.addOrUpdateWindow(newWallpaper,
6822 InputTarget::Flags::DISPATCH_AS_SLIPPERY_ENTER |
6823 InputTarget::Flags::WINDOW_IS_OBSCURED |
6824 InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED,
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07006825 deviceId, pointerIds);
Arthur Hungc539dbb2022-12-08 07:45:36 +00006826 }
6827}
6828
6829void InputDispatcher::transferWallpaperTouch(ftl::Flags<InputTarget::Flags> oldTargetFlags,
6830 ftl::Flags<InputTarget::Flags> newTargetFlags,
6831 const sp<WindowInfoHandle> fromWindowHandle,
6832 const sp<WindowInfoHandle> toWindowHandle,
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07006833 TouchState& state, int32_t deviceId,
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08006834 std::bitset<MAX_POINTER_ID + 1> pointerIds) {
Arthur Hungc539dbb2022-12-08 07:45:36 +00006835 const bool oldHasWallpaper = oldTargetFlags.test(InputTarget::Flags::FOREGROUND) &&
6836 fromWindowHandle->getInfo()->inputConfig.test(
6837 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
6838 const bool newHasWallpaper = newTargetFlags.test(InputTarget::Flags::FOREGROUND) &&
6839 toWindowHandle->getInfo()->inputConfig.test(
6840 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
6841
6842 const sp<WindowInfoHandle> oldWallpaper =
6843 oldHasWallpaper ? state.getWallpaperWindow() : nullptr;
6844 const sp<WindowInfoHandle> newWallpaper =
6845 newHasWallpaper ? findWallpaperWindowBelow(toWindowHandle) : nullptr;
6846 if (oldWallpaper == newWallpaper) {
6847 return;
6848 }
6849
6850 if (oldWallpaper != nullptr) {
6851 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
6852 "transferring touch focus to another window");
6853 state.removeWindowByToken(oldWallpaper->getToken());
6854 synthesizeCancelationEventsForWindowLocked(oldWallpaper, options);
6855 }
6856
6857 if (newWallpaper != nullptr) {
6858 nsecs_t downTimeInTarget = now();
6859 ftl::Flags<InputTarget::Flags> wallpaperFlags =
6860 oldTargetFlags & (InputTarget::Flags::SPLIT | InputTarget::Flags::DISPATCH_AS_IS);
6861 wallpaperFlags |= InputTarget::Flags::WINDOW_IS_OBSCURED |
6862 InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED;
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07006863 state.addOrUpdateWindow(newWallpaper, wallpaperFlags, deviceId, pointerIds,
6864 downTimeInTarget);
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006865 std::shared_ptr<Connection> wallpaperConnection =
6866 getConnectionLocked(newWallpaper->getToken());
Arthur Hungc539dbb2022-12-08 07:45:36 +00006867 if (wallpaperConnection != nullptr) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006868 std::shared_ptr<Connection> toConnection =
6869 getConnectionLocked(toWindowHandle->getToken());
Arthur Hungc539dbb2022-12-08 07:45:36 +00006870 toConnection->inputState.mergePointerStateTo(wallpaperConnection->inputState);
6871 synthesizePointerDownEventsForConnectionLocked(downTimeInTarget, wallpaperConnection,
6872 wallpaperFlags);
6873 }
6874 }
6875}
6876
6877sp<WindowInfoHandle> InputDispatcher::findWallpaperWindowBelow(
6878 const sp<WindowInfoHandle>& windowHandle) const {
6879 const std::vector<sp<WindowInfoHandle>>& windowHandles =
6880 getWindowHandlesLocked(windowHandle->getInfo()->displayId);
6881 bool foundWindow = false;
6882 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
6883 if (!foundWindow && otherHandle != windowHandle) {
6884 continue;
6885 }
6886 if (windowHandle == otherHandle) {
6887 foundWindow = true;
6888 continue;
6889 }
6890
6891 if (otherHandle->getInfo()->inputConfig.test(WindowInfo::InputConfig::IS_WALLPAPER)) {
6892 return otherHandle;
6893 }
6894 }
6895 return nullptr;
6896}
6897
Nergi Rahardi730cf3c2023-04-13 12:41:17 +09006898void InputDispatcher::setKeyRepeatConfiguration(nsecs_t timeout, nsecs_t delay) {
6899 std::scoped_lock _l(mLock);
6900
6901 mConfig.keyRepeatTimeout = timeout;
6902 mConfig.keyRepeatDelay = delay;
6903}
6904
Garfield Tane84e6f92019-08-29 17:28:41 -07006905} // namespace android::inputdispatcher