blob: 010e181114f0332317a9677cd159a8e1651ea976 [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 Vishniakou31977182022-09-30 08:51:23 -070029#if defined(__ANDROID__)
chaviw15fab6f2021-06-07 14:15:52 -050030#include <gui/SurfaceComposerClient.h>
Siarhei Vishniakou31977182022-09-30 08:51:23 -070031#endif
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -080032#include <input/InputDevice.h>
Siarhei Vishniakou6e1e9872022-11-08 17:51:35 -080033#include <input/PrintTools.h>
tyiu1573a672023-02-21 22:38:32 +000034#include <openssl/mem.h>
Garfield Tan0fc2fa72019-08-29 17:22:15 -070035#include <powermanager/PowerManager.h>
Michael Wright44753b12020-07-08 13:48:11 +010036#include <unistd.h>
Garfield Tan0fc2fa72019-08-29 17:22:15 -070037#include <utils/Trace.h>
Michael Wrightd02c5b62014-02-10 15:10:22 -080038
Michael Wright44753b12020-07-08 13:48:11 +010039#include <cerrno>
40#include <cinttypes>
41#include <climits>
42#include <cstddef>
43#include <ctime>
44#include <queue>
45#include <sstream>
46
47#include "Connection.h"
Arthur Hung1a1007b2022-05-11 07:15:01 +000048#include "DebugConfig.h"
Chris Yef59a2f42020-10-16 12:55:26 -070049#include "InputDispatcher.h"
Michael Wright44753b12020-07-08 13:48:11 +010050
Michael Wrightd02c5b62014-02-10 15:10:22 -080051#define INDENT " "
52#define INDENT2 " "
53#define INDENT3 " "
54#define INDENT4 " "
55
Siarhei Vishniakou253f4642022-11-09 13:42:06 -080056using namespace android::ftl::flag_operators;
Siarhei Vishniakou6773db62023-04-21 11:30:20 -070057using android::base::Error;
Peter Collingbourneb04b9b82021-02-08 12:09:47 -080058using android::base::HwTimeoutMultiplier;
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +000059using android::base::Result;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080060using android::base::StringPrintf;
Prabir Pradhan48f8cb92021-08-26 14:05:36 -070061using android::gui::DisplayInfo;
chaviw98318de2021-05-19 16:45:23 -050062using android::gui::FocusRequest;
63using android::gui::TouchOcclusionMode;
64using android::gui::WindowInfo;
65using android::gui::WindowInfoHandle;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -080066using android::os::InputEventInjectionResult;
67using android::os::InputEventInjectionSync;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080068
Garfield Tane84e6f92019-08-29 17:28:41 -070069namespace android::inputdispatcher {
Michael Wrightd02c5b62014-02-10 15:10:22 -080070
Prabir Pradhancef936d2021-07-21 16:17:52 +000071namespace {
Prabir Pradhancef936d2021-07-21 16:17:52 +000072// Temporarily releases a held mutex for the lifetime of the instance.
73// Named to match std::scoped_lock
74class scoped_unlock {
75public:
76 explicit scoped_unlock(std::mutex& mutex) : mMutex(mutex) { mMutex.unlock(); }
77 ~scoped_unlock() { mMutex.lock(); }
78
79private:
80 std::mutex& mMutex;
81};
82
Michael Wrightd02c5b62014-02-10 15:10:22 -080083// Default input dispatching timeout if there is no focused application or paused window
84// from which to determine an appropriate dispatching timeout.
Peter Collingbourneb04b9b82021-02-08 12:09:47 -080085const std::chrono::duration DEFAULT_INPUT_DISPATCHING_TIMEOUT = std::chrono::milliseconds(
86 android::os::IInputConstants::UNMULTIPLIED_DEFAULT_DISPATCHING_TIMEOUT_MILLIS *
87 HwTimeoutMultiplier());
Michael Wrightd02c5b62014-02-10 15:10:22 -080088
89// Amount of time to allow for all pending events to be processed when an app switch
90// key is on the way. This is used to preempt input dispatch and drop input events
91// when an application takes too long to respond and the user has pressed an app switch key.
Michael Wright2b3c3302018-03-02 17:19:13 +000092constexpr nsecs_t APP_SWITCH_TIMEOUT = 500 * 1000000LL; // 0.5sec
Michael Wrightd02c5b62014-02-10 15:10:22 -080093
Siarhei Vishniakou289e9242022-02-15 14:50:16 -080094const std::chrono::duration STALE_EVENT_TIMEOUT = std::chrono::seconds(10) * HwTimeoutMultiplier();
Michael Wrightd02c5b62014-02-10 15:10:22 -080095
Michael Wrightd02c5b62014-02-10 15:10:22 -080096// 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 +000097constexpr nsecs_t SLOW_EVENT_PROCESSING_WARNING_TIMEOUT = 2000 * 1000000LL; // 2sec
98
99// Log a warning when an interception call takes longer than this to process.
100constexpr std::chrono::milliseconds SLOW_INTERCEPTION_THRESHOLD = 50ms;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800101
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700102// Additional key latency in case a connection is still processing some motion events.
103// This will help with the case when a user touched a button that opens a new window,
104// and gives us the chance to dispatch the key to this new window.
105constexpr std::chrono::nanoseconds KEY_WAITING_FOR_EVENTS_TIMEOUT = 500ms;
106
Michael Wrightd02c5b62014-02-10 15:10:22 -0800107// Number of recent events to keep for debugging purposes.
Michael Wright2b3c3302018-03-02 17:19:13 +0000108constexpr size_t RECENT_QUEUE_MAX_SIZE = 10;
109
Antonio Kantekea47acb2021-12-23 12:41:25 -0800110// Event log tags. See EventLogTags.logtags for reference.
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +0000111constexpr int LOGTAG_INPUT_INTERACTION = 62000;
112constexpr int LOGTAG_INPUT_FOCUS = 62001;
Arthur Hungb3307ee2021-10-14 10:57:37 +0000113constexpr int LOGTAG_INPUT_CANCEL = 62003;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +0000114
Prabir Pradhan33e3baa2022-12-06 20:30:22 +0000115const ui::Transform kIdentityTransform;
116
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000117inline nsecs_t now() {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800118 return systemTime(SYSTEM_TIME_MONOTONIC);
119}
120
Siarhei Vishniakou63b63612023-04-12 11:00:23 -0700121inline const std::string binderToString(const sp<IBinder>& binder) {
Bernardo Rufino49d99e42021-01-18 15:16:59 +0000122 if (binder == nullptr) {
123 return "<null>";
124 }
125 return StringPrintf("%p", binder.get());
126}
127
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +0000128static std::string uidString(const gui::Uid& uid) {
129 return uid.toString();
130}
131
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000132inline int32_t getMotionEventActionPointerIndex(int32_t action) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700133 return (action & AMOTION_EVENT_ACTION_POINTER_INDEX_MASK) >>
134 AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800135}
136
Siarhei Vishniakou6773db62023-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 Vishniakou6773db62023-04-21 11:30:20 -0700141 return {};
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700142 default:
Siarhei Vishniakou6773db62023-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 Vishniakou6773db62023-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 Vishniakou6773db62023-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 Vishniakou6773db62023-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 Vishniakou6773db62023-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 Vishniakou6773db62023-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 Vishniakou6773db62023-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 Vishniakou6773db62023-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 Vishniakou6773db62023-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 Vishniakou6773db62023-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 Vishniakou6773db62023-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 Vishniakou6773db62023-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 Vishniakou6773db62023-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 Vishniakou6773db62023-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 Pradhan8a5c41d2023-06-08 19:13:46 +0000563bool isWindowOwnedBy(const sp<WindowInfoHandle>& windowHandle, int32_t 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
604 const int32_t pointerIndex = getMotionEventActionPointerIndex(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 Vishniakou8a878352023-01-30 14:05:01 -0800656 touchedWindow.pointerIds.set(pointerId);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000657 out.push_back(touchedWindow);
658 }
659 }
660
661 for (const sp<WindowInfoHandle>& newWindow : newWindows) {
662 TouchedWindow touchedWindow;
663 touchedWindow.windowHandle = newWindow;
664 if (oldWindows.find(newWindow) == oldWindows.end()) {
665 // Any windows that have this pointer now, and didn't have it before, should get
666 // HOVER_ENTER
667 touchedWindow.targetFlags = InputTarget::Flags::DISPATCH_AS_HOVER_ENTER;
668 } else {
669 // This pointer was already sent to the window. Use ACTION_HOVER_MOVE.
Siarhei Vishniakouc2eb8502023-04-11 18:33:36 -0700670 if (CC_UNLIKELY(maskedAction != AMOTION_EVENT_ACTION_HOVER_MOVE)) {
671 LOG(FATAL) << "Expected ACTION_HOVER_MOVE instead of " << entry.getDescription();
672 }
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000673 touchedWindow.targetFlags = InputTarget::Flags::DISPATCH_AS_IS;
674 }
Siarhei Vishniakou8a878352023-01-30 14:05:01 -0800675 touchedWindow.pointerIds.set(pointerId);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000676 if (canReceiveForegroundTouches(*newWindow->getInfo())) {
677 touchedWindow.targetFlags |= InputTarget::Flags::FOREGROUND;
678 }
679 out.push_back(touchedWindow);
680 }
681 return out;
682}
683
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -0800684template <typename T>
685std::vector<T>& operator+=(std::vector<T>& left, const std::vector<T>& right) {
686 left.insert(left.end(), right.begin(), right.end());
687 return left;
688}
689
Harry Cuttsb166c002023-05-09 13:06:05 +0000690// Filter windows in a TouchState and targets in a vector to remove untrusted windows/targets from
691// both.
692void filterUntrustedTargets(TouchState& touchState, std::vector<InputTarget>& targets) {
693 std::erase_if(touchState.windows, [&](const TouchedWindow& window) {
694 if (!window.windowHandle->getInfo()->inputConfig.test(
695 WindowInfo::InputConfig::TRUSTED_OVERLAY)) {
696 // In addition to TouchState, erase this window from the input targets! We don't have a
697 // good way to do this today except by adding a nested loop.
698 // TODO(b/282025641): simplify this code once InputTargets are being identified
699 // separately from TouchedWindows.
700 std::erase_if(targets, [&](const InputTarget& target) {
701 return target.inputChannel->getConnectionToken() == window.windowHandle->getToken();
702 });
703 return true;
704 }
705 return false;
706 });
707}
708
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000709} // namespace
710
Michael Wrightd02c5b62014-02-10 15:10:22 -0800711// --- InputDispatcher ---
712
Prabir Pradhana41d2442023-04-20 21:30:40 +0000713InputDispatcher::InputDispatcher(InputDispatcherPolicyInterface& policy)
Siarhei Vishniakou289e9242022-02-15 14:50:16 -0800714 : InputDispatcher(policy, STALE_EVENT_TIMEOUT) {}
715
Prabir Pradhana41d2442023-04-20 21:30:40 +0000716InputDispatcher::InputDispatcher(InputDispatcherPolicyInterface& policy,
Siarhei Vishniakou289e9242022-02-15 14:50:16 -0800717 std::chrono::nanoseconds staleEventTimeout)
Garfield Tan00f511d2019-06-12 16:55:40 -0700718 : mPolicy(policy),
719 mPendingEvent(nullptr),
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700720 mLastDropReason(DropReason::NOT_DROPPED),
Garfield Tanff1f1bb2020-01-28 13:24:04 -0800721 mIdGenerator(IdGenerator::Source::INPUT_DISPATCHER),
Garfield Tan00f511d2019-06-12 16:55:40 -0700722 mAppSwitchSawKeyDown(false),
Colin Cross5b799302022-10-18 21:52:41 -0700723 mAppSwitchDueTime(LLONG_MAX),
Garfield Tan00f511d2019-06-12 16:55:40 -0700724 mNextUnblockedEvent(nullptr),
Prabir Pradhan1376fcd2022-01-21 09:56:35 -0800725 mMonitorDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT),
Garfield Tan00f511d2019-06-12 16:55:40 -0700726 mDispatchEnabled(false),
727 mDispatchFrozen(false),
728 mInputFilterEnabled(false),
Bernardo Rufinoea97d182020-08-19 14:43:14 +0100729 mMaximumObscuringOpacityForTouch(1.0f),
Siarhei Vishniakou2508b872020-12-03 16:33:53 -1000730 mFocusedDisplayId(ADISPLAY_ID_DEFAULT),
Prabir Pradhan99987712020-11-10 18:43:05 -0800731 mWindowTokenWithPointerCapture(nullptr),
Siarhei Vishniakou289e9242022-02-15 14:50:16 -0800732 mStaleEventTimeout(staleEventTimeout),
Siarhei Vishniakoua04181f2021-03-26 05:56:49 +0000733 mLatencyAggregator(),
Antonio Kantek15beb512022-06-13 22:35:41 +0000734 mLatencyTracker(&mLatencyAggregator) {
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -0700735 mLooper = sp<Looper>::make(false);
Prabir Pradhanf93562f2018-11-29 12:13:37 -0800736 mReporter = createInputReporter();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800737
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -0700738 mWindowInfoListener = sp<DispatcherWindowListener>::make(*this);
Siarhei Vishniakou31977182022-09-30 08:51:23 -0700739#if defined(__ANDROID__)
Siarhei Vishniakou18050092021-09-01 13:32:49 -0700740 SurfaceComposerClient::getDefault()->addWindowInfosListener(mWindowInfoListener);
Siarhei Vishniakou31977182022-09-30 08:51:23 -0700741#endif
Yi Kong9b14ac62018-07-17 13:48:38 -0700742 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800743}
744
745InputDispatcher::~InputDispatcher() {
Prabir Pradhancef936d2021-07-21 16:17:52 +0000746 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800747
Prabir Pradhancef936d2021-07-21 16:17:52 +0000748 resetKeyRepeatLocked();
749 releasePendingEventLocked();
750 drainInboundQueueLocked();
751 mCommandQueue.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800752
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +0000753 while (!mConnectionsByToken.empty()) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -0700754 std::shared_ptr<Connection> connection = mConnectionsByToken.begin()->second;
Harry Cutts33476232023-01-30 19:57:29 +0000755 removeInputChannelLocked(connection->inputChannel->getConnectionToken(), /*notify=*/false);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800756 }
757}
758
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700759status_t InputDispatcher::start() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700760 if (mThread) {
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700761 return ALREADY_EXISTS;
762 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700763 mThread = std::make_unique<InputThread>(
764 "InputDispatcher", [this]() { dispatchOnce(); }, [this]() { mLooper->wake(); });
765 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700766}
767
768status_t InputDispatcher::stop() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700769 if (mThread && mThread->isCallingThread()) {
770 ALOGE("InputDispatcher cannot be stopped from its own thread!");
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700771 return INVALID_OPERATION;
772 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700773 mThread.reset();
774 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700775}
776
Michael Wrightd02c5b62014-02-10 15:10:22 -0800777void InputDispatcher::dispatchOnce() {
Colin Cross5b799302022-10-18 21:52:41 -0700778 nsecs_t nextWakeupTime = LLONG_MAX;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800779 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -0800780 std::scoped_lock _l(mLock);
781 mDispatcherIsAlive.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800782
783 // Run a dispatch loop if there are no pending commands.
784 // The dispatch loop might enqueue commands to run afterwards.
785 if (!haveCommandsLocked()) {
786 dispatchOnceInnerLocked(&nextWakeupTime);
787 }
788
789 // Run all pending commands if there are any.
790 // If any commands were run then force the next poll to wake up immediately.
Prabir Pradhancef936d2021-07-21 16:17:52 +0000791 if (runCommandsLockedInterruptable()) {
Colin Cross5b799302022-10-18 21:52:41 -0700792 nextWakeupTime = LLONG_MIN;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800793 }
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800794
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700795 // If we are still waiting for ack on some events,
796 // we might have to wake up earlier to check if an app is anr'ing.
797 const nsecs_t nextAnrCheck = processAnrsLocked();
798 nextWakeupTime = std::min(nextWakeupTime, nextAnrCheck);
799
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800800 // We are about to enter an infinitely long sleep, because we have no commands or
801 // pending or queued events
Colin Cross5b799302022-10-18 21:52:41 -0700802 if (nextWakeupTime == LLONG_MAX) {
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800803 mDispatcherEnteredIdle.notify_all();
804 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800805 } // release lock
806
807 // Wait for callback or timeout or wake. (make sure we round up, not down)
808 nsecs_t currentTime = now();
809 int timeoutMillis = toMillisecondTimeoutDelay(currentTime, nextWakeupTime);
810 mLooper->pollOnce(timeoutMillis);
811}
812
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700813/**
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500814 * Raise ANR if there is no focused window.
815 * Before the ANR is raised, do a final state check:
816 * 1. The currently focused application must be the same one we are waiting for.
817 * 2. Ensure we still don't have a focused window.
818 */
819void InputDispatcher::processNoFocusedWindowAnrLocked() {
820 // Check if the application that we are waiting for is still focused.
821 std::shared_ptr<InputApplicationHandle> focusedApplication =
822 getValueByKey(mFocusedApplicationHandlesByDisplay, mAwaitedApplicationDisplayId);
823 if (focusedApplication == nullptr ||
824 focusedApplication->getApplicationToken() !=
825 mAwaitedFocusedApplication->getApplicationToken()) {
826 // Unexpected because we should have reset the ANR timer when focused application changed
827 ALOGE("Waited for a focused window, but focused application has already changed to %s",
828 focusedApplication->getName().c_str());
829 return; // The focused application has changed.
830 }
831
chaviw98318de2021-05-19 16:45:23 -0500832 const sp<WindowInfoHandle>& focusedWindowHandle =
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500833 getFocusedWindowHandleLocked(mAwaitedApplicationDisplayId);
834 if (focusedWindowHandle != nullptr) {
835 return; // We now have a focused window. No need for ANR.
836 }
837 onAnrLocked(mAwaitedFocusedApplication);
838}
839
840/**
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700841 * Check if any of the connections' wait queues have events that are too old.
842 * If we waited for events to be ack'ed for more than the window timeout, raise an ANR.
843 * Return the time at which we should wake up next.
844 */
845nsecs_t InputDispatcher::processAnrsLocked() {
846 const nsecs_t currentTime = now();
Colin Cross5b799302022-10-18 21:52:41 -0700847 nsecs_t nextAnrCheck = LLONG_MAX;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700848 // Check if we are waiting for a focused window to appear. Raise ANR if waited too long
849 if (mNoFocusedWindowTimeoutTime.has_value() && mAwaitedFocusedApplication != nullptr) {
850 if (currentTime >= *mNoFocusedWindowTimeoutTime) {
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500851 processNoFocusedWindowAnrLocked();
Chris Yea209fde2020-07-22 13:54:51 -0700852 mAwaitedFocusedApplication.reset();
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500853 mNoFocusedWindowTimeoutTime = std::nullopt;
Colin Cross5b799302022-10-18 21:52:41 -0700854 return LLONG_MIN;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700855 } else {
Siarhei Vishniakou38a6d272020-10-20 20:29:33 -0500856 // Keep waiting. We will drop the event when mNoFocusedWindowTimeoutTime comes.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700857 nextAnrCheck = *mNoFocusedWindowTimeoutTime;
858 }
859 }
860
861 // Check if any connection ANRs are due
862 nextAnrCheck = std::min(nextAnrCheck, mAnrTracker.firstTimeout());
863 if (currentTime < nextAnrCheck) { // most likely scenario
864 return nextAnrCheck; // everything is normal. Let's check again at nextAnrCheck
865 }
866
867 // If we reached here, we have an unresponsive connection.
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -0700868 std::shared_ptr<Connection> connection = getConnectionLocked(mAnrTracker.firstToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700869 if (connection == nullptr) {
870 ALOGE("Could not find connection for entry %" PRId64, mAnrTracker.firstTimeout());
871 return nextAnrCheck;
872 }
873 connection->responsive = false;
874 // Stop waking up for this unresponsive connection
875 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000876 onAnrLocked(connection);
Colin Cross5b799302022-10-18 21:52:41 -0700877 return LLONG_MIN;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700878}
879
Prabir Pradhan1376fcd2022-01-21 09:56:35 -0800880std::chrono::nanoseconds InputDispatcher::getDispatchingTimeoutLocked(
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -0700881 const std::shared_ptr<Connection>& connection) {
Prabir Pradhan1376fcd2022-01-21 09:56:35 -0800882 if (connection->monitor) {
883 return mMonitorDispatchingTimeout;
884 }
885 const sp<WindowInfoHandle> window =
886 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700887 if (window != nullptr) {
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500888 return window->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700889 }
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500890 return DEFAULT_INPUT_DISPATCHING_TIMEOUT;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700891}
892
Michael Wrightd02c5b62014-02-10 15:10:22 -0800893void InputDispatcher::dispatchOnceInnerLocked(nsecs_t* nextWakeupTime) {
894 nsecs_t currentTime = now();
895
Jeff Browndc5992e2014-04-11 01:27:26 -0700896 // Reset the key repeat timer whenever normal dispatch is suspended while the
897 // device is in a non-interactive state. This is to ensure that we abort a key
898 // repeat if the device is just coming out of sleep.
899 if (!mDispatchEnabled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800900 resetKeyRepeatLocked();
901 }
902
903 // If dispatching is frozen, do not process timeouts or try to deliver any new events.
904 if (mDispatchFrozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +0100905 if (DEBUG_FOCUS) {
906 ALOGD("Dispatch frozen. Waiting some more.");
907 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800908 return;
909 }
910
911 // Optimize latency of app switches.
912 // Essentially we start a short timeout when an app switch key (HOME / ENDCALL) has
913 // been pressed. When it expires, we preempt dispatch and drop all other pending events.
914 bool isAppSwitchDue = mAppSwitchDueTime <= currentTime;
915 if (mAppSwitchDueTime < *nextWakeupTime) {
916 *nextWakeupTime = mAppSwitchDueTime;
917 }
918
919 // Ready to start a new event.
920 // If we don't already have a pending event, go grab one.
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700921 if (!mPendingEvent) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700922 if (mInboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800923 if (isAppSwitchDue) {
924 // The inbound queue is empty so the app switch key we were waiting
925 // for will never arrive. Stop waiting for it.
926 resetPendingAppSwitchLocked(false);
927 isAppSwitchDue = false;
928 }
929
930 // Synthesize a key repeat if appropriate.
931 if (mKeyRepeatState.lastKeyEntry) {
932 if (currentTime >= mKeyRepeatState.nextRepeatTime) {
933 mPendingEvent = synthesizeKeyRepeatLocked(currentTime);
934 } else {
935 if (mKeyRepeatState.nextRepeatTime < *nextWakeupTime) {
936 *nextWakeupTime = mKeyRepeatState.nextRepeatTime;
937 }
938 }
939 }
940
941 // Nothing to do if there is no pending event.
942 if (!mPendingEvent) {
943 return;
944 }
945 } else {
946 // Inbound queue has at least one entry.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700947 mPendingEvent = mInboundQueue.front();
948 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800949 traceInboundQueueLengthLocked();
950 }
951
952 // Poke user activity for this event.
953 if (mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700954 pokeUserActivityLocked(*mPendingEvent);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800955 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800956 }
957
958 // Now we have an event to dispatch.
959 // All events are eventually dequeued and processed this way, even if we intend to drop them.
Yi Kong9b14ac62018-07-17 13:48:38 -0700960 ALOG_ASSERT(mPendingEvent != nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800961 bool done = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700962 DropReason dropReason = DropReason::NOT_DROPPED;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800963 if (!(mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700964 dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800965 } else if (!mDispatchEnabled) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700966 dropReason = DropReason::DISABLED;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800967 }
968
969 if (mNextUnblockedEvent == mPendingEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -0700970 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800971 }
972
973 switch (mPendingEvent->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700974 case EventEntry::Type::CONFIGURATION_CHANGED: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700975 const ConfigurationChangedEntry& typedEntry =
976 static_cast<const ConfigurationChangedEntry&>(*mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700977 done = dispatchConfigurationChangedLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700978 dropReason = DropReason::NOT_DROPPED; // configuration changes are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700979 break;
980 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800981
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700982 case EventEntry::Type::DEVICE_RESET: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700983 const DeviceResetEntry& typedEntry =
984 static_cast<const DeviceResetEntry&>(*mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700985 done = dispatchDeviceResetLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700986 dropReason = DropReason::NOT_DROPPED; // device resets are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700987 break;
988 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800989
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100990 case EventEntry::Type::FOCUS: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700991 std::shared_ptr<FocusEntry> typedEntry =
992 std::static_pointer_cast<FocusEntry>(mPendingEvent);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100993 dispatchFocusLocked(currentTime, typedEntry);
994 done = true;
995 dropReason = DropReason::NOT_DROPPED; // focus events are never dropped
996 break;
997 }
998
Antonio Kantek7242d8b2021-08-05 16:07:20 -0700999 case EventEntry::Type::TOUCH_MODE_CHANGED: {
1000 const auto typedEntry = std::static_pointer_cast<TouchModeEntry>(mPendingEvent);
1001 dispatchTouchModeChangeLocked(currentTime, typedEntry);
1002 done = true;
1003 dropReason = DropReason::NOT_DROPPED; // touch mode events are never dropped
1004 break;
1005 }
1006
Prabir Pradhan99987712020-11-10 18:43:05 -08001007 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
1008 const auto typedEntry =
1009 std::static_pointer_cast<PointerCaptureChangedEntry>(mPendingEvent);
1010 dispatchPointerCaptureChangedLocked(currentTime, typedEntry, dropReason);
1011 done = true;
1012 break;
1013 }
1014
arthurhungb89ccb02020-12-30 16:19:01 +08001015 case EventEntry::Type::DRAG: {
1016 std::shared_ptr<DragEntry> typedEntry =
1017 std::static_pointer_cast<DragEntry>(mPendingEvent);
1018 dispatchDragLocked(currentTime, typedEntry);
1019 done = true;
1020 break;
1021 }
1022
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001023 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001024 std::shared_ptr<KeyEntry> keyEntry = std::static_pointer_cast<KeyEntry>(mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001025 if (isAppSwitchDue) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001026 if (isAppSwitchKeyEvent(*keyEntry)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001027 resetPendingAppSwitchLocked(true);
1028 isAppSwitchDue = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001029 } else if (dropReason == DropReason::NOT_DROPPED) {
1030 dropReason = DropReason::APP_SWITCH;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001031 }
1032 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001033 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *keyEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001034 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001035 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001036 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
1037 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001038 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001039 done = dispatchKeyLocked(currentTime, keyEntry, &dropReason, nextWakeupTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001040 break;
1041 }
1042
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001043 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001044 std::shared_ptr<MotionEntry> motionEntry =
1045 std::static_pointer_cast<MotionEntry>(mPendingEvent);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001046 if (dropReason == DropReason::NOT_DROPPED && isAppSwitchDue) {
1047 dropReason = DropReason::APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001048 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001049 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *motionEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001050 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001051 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001052 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
1053 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001054 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001055 done = dispatchMotionLocked(currentTime, motionEntry, &dropReason, nextWakeupTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001056 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001057 }
Chris Yef59a2f42020-10-16 12:55:26 -07001058
1059 case EventEntry::Type::SENSOR: {
1060 std::shared_ptr<SensorEntry> sensorEntry =
1061 std::static_pointer_cast<SensorEntry>(mPendingEvent);
1062 if (dropReason == DropReason::NOT_DROPPED && isAppSwitchDue) {
1063 dropReason = DropReason::APP_SWITCH;
1064 }
1065 // Sensor timestamps use SYSTEM_TIME_BOOTTIME time base, so we can't use
1066 // 'currentTime' here, get SYSTEM_TIME_BOOTTIME instead.
1067 nsecs_t bootTime = systemTime(SYSTEM_TIME_BOOTTIME);
1068 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(bootTime, *sensorEntry)) {
1069 dropReason = DropReason::STALE;
1070 }
1071 dispatchSensorLocked(currentTime, sensorEntry, &dropReason, nextWakeupTime);
1072 done = true;
1073 break;
1074 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001075 }
1076
1077 if (done) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001078 if (dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001079 dropInboundEventLocked(*mPendingEvent, dropReason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001080 }
Michael Wright3a981722015-06-10 15:26:13 +01001081 mLastDropReason = dropReason;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001082
1083 releasePendingEventLocked();
Colin Cross5b799302022-10-18 21:52:41 -07001084 *nextWakeupTime = LLONG_MIN; // force next poll to wake up immediately
Michael Wrightd02c5b62014-02-10 15:10:22 -08001085 }
1086}
1087
Siarhei Vishniakou289e9242022-02-15 14:50:16 -08001088bool InputDispatcher::isStaleEvent(nsecs_t currentTime, const EventEntry& entry) {
1089 return std::chrono::nanoseconds(currentTime - entry.eventTime) >= mStaleEventTimeout;
1090}
1091
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001092/**
1093 * Return true if the events preceding this incoming motion event should be dropped
1094 * Return false otherwise (the default behaviour)
1095 */
1096bool InputDispatcher::shouldPruneInboundQueueLocked(const MotionEntry& motionEntry) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001097 const bool isPointerDownEvent = motionEntry.action == AMOTION_EVENT_ACTION_DOWN &&
Prabir Pradhanaa561d12021-09-24 06:57:33 -07001098 isFromSource(motionEntry.source, AINPUT_SOURCE_CLASS_POINTER);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001099
1100 // Optimize case where the current application is unresponsive and the user
1101 // decides to touch a window in a different application.
1102 // If the application takes too long to catch up then we drop all events preceding
1103 // the touch into the other window.
1104 if (isPointerDownEvent && mAwaitedFocusedApplication != nullptr) {
Siarhei Vishniakou9306c382022-09-30 15:30:31 -07001105 const int32_t displayId = motionEntry.displayId;
1106 const auto [x, y] = resolveTouchedPosition(motionEntry);
Harry Cutts33476232023-01-30 19:57:29 +00001107 const bool isStylus = isPointerFromStylus(motionEntry, /*pointerIndex=*/0);
Siarhei Vishniakou9306c382022-09-30 15:30:31 -07001108
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08001109 auto [touchedWindowHandle, _] = findTouchedWindowAtLocked(displayId, x, y, isStylus);
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001110 if (touchedWindowHandle != nullptr &&
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001111 touchedWindowHandle->getApplicationToken() !=
1112 mAwaitedFocusedApplication->getApplicationToken()) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001113 // User touched a different application than the one we are waiting on.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001114 ALOGI("Pruning input queue because user touched a different application while waiting "
1115 "for %s",
1116 mAwaitedFocusedApplication->getName().c_str());
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001117 return true;
1118 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001119
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08001120 // Alternatively, maybe there's a spy window that could handle this event.
1121 const std::vector<sp<WindowInfoHandle>> touchedSpies =
1122 findTouchedSpyWindowsAtLocked(displayId, x, y, isStylus);
1123 for (const auto& windowHandle : touchedSpies) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07001124 const std::shared_ptr<Connection> connection =
1125 getConnectionLocked(windowHandle->getToken());
Siarhei Vishniakou34ed4d42020-06-18 00:43:02 +00001126 if (connection != nullptr && connection->responsive) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08001127 // This spy window could take more input. Drop all events preceding this
1128 // event, so that the spy window can get a chance to receive the stream.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001129 ALOGW("Pruning the input queue because %s is unresponsive, but we have a "
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08001130 "responsive spy window that may handle the event.",
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001131 mAwaitedFocusedApplication->getName().c_str());
1132 return true;
1133 }
1134 }
1135 }
1136
1137 // Prevent getting stuck: if we have a pending key event, and some motion events that have not
1138 // yet been processed by some connections, the dispatcher will wait for these motion
1139 // events to be processed before dispatching the key event. This is because these motion events
1140 // may cause a new window to be launched, which the user might expect to receive focus.
1141 // To prevent waiting forever for such events, just send the key to the currently focused window
1142 if (isPointerDownEvent && mKeyIsWaitingForEventsTimeout) {
1143 ALOGD("Received a new pointer down event, stop waiting for events to process and "
1144 "just send the pending key event to the focused window.");
1145 mKeyIsWaitingForEventsTimeout = now();
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001146 }
1147 return false;
1148}
1149
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001150bool InputDispatcher::enqueueInboundEventLocked(std::unique_ptr<EventEntry> newEntry) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001151 bool needWake = mInboundQueue.empty();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001152 mInboundQueue.push_back(std::move(newEntry));
1153 EventEntry& entry = *(mInboundQueue.back());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001154 traceInboundQueueLengthLocked();
1155
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001156 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001157 case EventEntry::Type::KEY: {
Prabir Pradhan5735a322022-04-11 17:23:34 +00001158 LOG_ALWAYS_FATAL_IF((entry.policyFlags & POLICY_FLAG_TRUSTED) == 0,
1159 "Unexpected untrusted event.");
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001160 // Optimize app switch latency.
1161 // If the application takes too long to catch up then we drop all events preceding
1162 // the app switch key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001163 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001164 if (isAppSwitchKeyEvent(keyEntry)) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001165 if (keyEntry.action == AKEY_EVENT_ACTION_DOWN) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001166 mAppSwitchSawKeyDown = true;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001167 } else if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001168 if (mAppSwitchSawKeyDown) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001169 if (DEBUG_APP_SWITCH) {
1170 ALOGD("App switch is pending!");
1171 }
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001172 mAppSwitchDueTime = keyEntry.eventTime + APP_SWITCH_TIMEOUT;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001173 mAppSwitchSawKeyDown = false;
1174 needWake = true;
1175 }
1176 }
1177 }
Arthur Hung2ee6d0b2022-03-03 20:19:38 +08001178
1179 // If a new up event comes in, and the pending event with same key code has been asked
1180 // to try again later because of the policy. We have to reset the intercept key wake up
1181 // time for it may have been handled in the policy and could be dropped.
1182 if (keyEntry.action == AKEY_EVENT_ACTION_UP && mPendingEvent &&
1183 mPendingEvent->type == EventEntry::Type::KEY) {
1184 KeyEntry& pendingKey = static_cast<KeyEntry&>(*mPendingEvent);
1185 if (pendingKey.keyCode == keyEntry.keyCode &&
1186 pendingKey.interceptKeyResult ==
Michael Wright5caf55a2022-11-24 22:31:42 +00001187 KeyEntry::InterceptKeyResult::TRY_AGAIN_LATER) {
1188 pendingKey.interceptKeyResult = KeyEntry::InterceptKeyResult::UNKNOWN;
Arthur Hung2ee6d0b2022-03-03 20:19:38 +08001189 pendingKey.interceptKeyWakeupTime = 0;
1190 needWake = true;
1191 }
1192 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001193 break;
1194 }
1195
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001196 case EventEntry::Type::MOTION: {
Prabir Pradhan5735a322022-04-11 17:23:34 +00001197 LOG_ALWAYS_FATAL_IF((entry.policyFlags & POLICY_FLAG_TRUSTED) == 0,
1198 "Unexpected untrusted event.");
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001199 if (shouldPruneInboundQueueLocked(static_cast<MotionEntry&>(entry))) {
1200 mNextUnblockedEvent = mInboundQueue.back();
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001201 needWake = true;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001202 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001203 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001204 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001205 case EventEntry::Type::FOCUS: {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001206 LOG_ALWAYS_FATAL("Focus events should be inserted using enqueueFocusEventLocked");
1207 break;
1208 }
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001209 case EventEntry::Type::TOUCH_MODE_CHANGED:
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001210 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08001211 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07001212 case EventEntry::Type::SENSOR:
arthurhungb89ccb02020-12-30 16:19:01 +08001213 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
1214 case EventEntry::Type::DRAG: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001215 // nothing to do
1216 break;
1217 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001218 }
1219
1220 return needWake;
1221}
1222
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001223void InputDispatcher::addRecentEventLocked(std::shared_ptr<EventEntry> entry) {
Chris Yef59a2f42020-10-16 12:55:26 -07001224 // Do not store sensor event in recent queue to avoid flooding the queue.
1225 if (entry->type != EventEntry::Type::SENSOR) {
1226 mRecentQueue.push_back(entry);
1227 }
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001228 if (mRecentQueue.size() > RECENT_QUEUE_MAX_SIZE) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001229 mRecentQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001230 }
1231}
1232
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08001233std::pair<sp<WindowInfoHandle>, std::vector<InputTarget>>
Prabir Pradhan82e081e2022-12-06 09:50:09 +00001234InputDispatcher::findTouchedWindowAtLocked(int32_t displayId, float x, float y, bool isStylus,
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08001235 bool ignoreDragWindow) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001236 // Traverse windows from front to back to find touched window.
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08001237 std::vector<InputTarget> outsideTargets;
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001238 const auto& windowHandles = getWindowHandlesLocked(displayId);
chaviw98318de2021-05-19 16:45:23 -05001239 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
arthurhung6d4bed92021-03-17 11:59:33 +08001240 if (ignoreDragWindow && haveSameToken(windowHandle, mDragState->dragWindow)) {
arthurhungb89ccb02020-12-30 16:19:01 +08001241 continue;
1242 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001243
Prabir Pradhan3f90d312021-11-19 03:57:24 -08001244 const WindowInfo& info = *windowHandle->getInfo();
Prabir Pradhan33e3baa2022-12-06 20:30:22 +00001245 if (!info.isSpy() &&
1246 windowAcceptsTouchAt(info, displayId, x, y, isStylus, getTransformLocked(displayId))) {
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08001247 return {windowHandle, outsideTargets};
Prabir Pradhan3f90d312021-11-19 03:57:24 -08001248 }
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001249
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08001250 if (info.inputConfig.test(WindowInfo::InputConfig::WATCH_OUTSIDE_TOUCH)) {
1251 addWindowTargetLocked(windowHandle, InputTarget::Flags::DISPATCH_AS_OUTSIDE,
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08001252 /*pointerIds=*/{}, /*firstDownTimeInTarget=*/std::nullopt,
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08001253 outsideTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001254 }
1255 }
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08001256 return {nullptr, {}};
Michael Wrightd02c5b62014-02-10 15:10:22 -08001257}
1258
Prabir Pradhand65552b2021-10-07 11:23:50 -07001259std::vector<sp<WindowInfoHandle>> InputDispatcher::findTouchedSpyWindowsAtLocked(
Prabir Pradhan82e081e2022-12-06 09:50:09 +00001260 int32_t displayId, float x, float y, bool isStylus) const {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001261 // Traverse windows from front to back and gather the touched spy windows.
1262 std::vector<sp<WindowInfoHandle>> spyWindows;
1263 const auto& windowHandles = getWindowHandlesLocked(displayId);
1264 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
1265 const WindowInfo& info = *windowHandle->getInfo();
1266
Prabir Pradhan33e3baa2022-12-06 20:30:22 +00001267 if (!windowAcceptsTouchAt(info, displayId, x, y, isStylus, getTransformLocked(displayId))) {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001268 continue;
1269 }
1270 if (!info.isSpy()) {
1271 // The first touched non-spy window was found, so return the spy windows touched so far.
1272 return spyWindows;
1273 }
1274 spyWindows.push_back(windowHandle);
1275 }
1276 return spyWindows;
1277}
1278
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001279void InputDispatcher::dropInboundEventLocked(const EventEntry& entry, DropReason dropReason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001280 const char* reason;
1281 switch (dropReason) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001282 case DropReason::POLICY:
Prabir Pradhan65613802023-02-22 23:36:58 +00001283 if (debugInboundEventDetails()) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001284 ALOGD("Dropped event because policy consumed it.");
1285 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001286 reason = "inbound event was dropped because the policy consumed it";
1287 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001288 case DropReason::DISABLED:
1289 if (mLastDropReason != DropReason::DISABLED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001290 ALOGI("Dropped event because input dispatch is disabled.");
1291 }
1292 reason = "inbound event was dropped because input dispatch is disabled";
1293 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001294 case DropReason::APP_SWITCH:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001295 ALOGI("Dropped event because of pending overdue app switch.");
1296 reason = "inbound event was dropped because of pending overdue app switch";
1297 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001298 case DropReason::BLOCKED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001299 ALOGI("Dropped event because the current application is not responding and the user "
1300 "has started interacting with a different application.");
1301 reason = "inbound event was dropped because the current application is not responding "
1302 "and the user has started interacting with a different application";
1303 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001304 case DropReason::STALE:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001305 ALOGI("Dropped event because it is stale.");
1306 reason = "inbound event was dropped because it is stale";
1307 break;
Prabir Pradhan99987712020-11-10 18:43:05 -08001308 case DropReason::NO_POINTER_CAPTURE:
1309 ALOGI("Dropped event because there is no window with Pointer Capture.");
1310 reason = "inbound event was dropped because there is no window with Pointer Capture";
1311 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001312 case DropReason::NOT_DROPPED: {
1313 LOG_ALWAYS_FATAL("Should not be dropping a NOT_DROPPED event");
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001314 return;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001315 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001316 }
1317
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001318 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001319 case EventEntry::Type::KEY: {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001320 CancelationOptions options(CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS, reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001321 synthesizeCancelationEventsForAllConnectionsLocked(options);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001322 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001323 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001324 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001325 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
1326 if (motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001327 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS, reason);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001328 synthesizeCancelationEventsForAllConnectionsLocked(options);
1329 } else {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001330 CancelationOptions options(CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS,
1331 reason);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001332 synthesizeCancelationEventsForAllConnectionsLocked(options);
1333 }
1334 break;
1335 }
Chris Yef59a2f42020-10-16 12:55:26 -07001336 case EventEntry::Type::SENSOR: {
1337 break;
1338 }
arthurhungb89ccb02020-12-30 16:19:01 +08001339 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
1340 case EventEntry::Type::DRAG: {
Prabir Pradhan99987712020-11-10 18:43:05 -08001341 break;
1342 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001343 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001344 case EventEntry::Type::TOUCH_MODE_CHANGED:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001345 case EventEntry::Type::CONFIGURATION_CHANGED:
1346 case EventEntry::Type::DEVICE_RESET: {
Dominik Laskowski75788452021-02-09 18:51:25 -08001347 LOG_ALWAYS_FATAL("Should not drop %s events", ftl::enum_string(entry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001348 break;
1349 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001350 }
1351}
1352
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08001353static bool isAppSwitchKeyCode(int32_t keyCode) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001354 return keyCode == AKEYCODE_HOME || keyCode == AKEYCODE_ENDCALL ||
1355 keyCode == AKEYCODE_APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001356}
1357
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001358bool InputDispatcher::isAppSwitchKeyEvent(const KeyEntry& keyEntry) {
1359 return !(keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) && isAppSwitchKeyCode(keyEntry.keyCode) &&
1360 (keyEntry.policyFlags & POLICY_FLAG_TRUSTED) &&
1361 (keyEntry.policyFlags & POLICY_FLAG_PASS_TO_USER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001362}
1363
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07001364bool InputDispatcher::isAppSwitchPendingLocked() const {
Colin Cross5b799302022-10-18 21:52:41 -07001365 return mAppSwitchDueTime != LLONG_MAX;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001366}
1367
1368void InputDispatcher::resetPendingAppSwitchLocked(bool handled) {
Colin Cross5b799302022-10-18 21:52:41 -07001369 mAppSwitchDueTime = LLONG_MAX;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001370
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001371 if (DEBUG_APP_SWITCH) {
1372 if (handled) {
1373 ALOGD("App switch has arrived.");
1374 } else {
1375 ALOGD("App switch was abandoned.");
1376 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001377 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001378}
1379
Michael Wrightd02c5b62014-02-10 15:10:22 -08001380bool InputDispatcher::haveCommandsLocked() const {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001381 return !mCommandQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001382}
1383
Prabir Pradhancef936d2021-07-21 16:17:52 +00001384bool InputDispatcher::runCommandsLockedInterruptable() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001385 if (mCommandQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001386 return false;
1387 }
1388
1389 do {
Prabir Pradhancef936d2021-07-21 16:17:52 +00001390 auto command = std::move(mCommandQueue.front());
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001391 mCommandQueue.pop_front();
Prabir Pradhancef936d2021-07-21 16:17:52 +00001392 // Commands are run with the lock held, but may release and re-acquire the lock from within.
1393 command();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001394 } while (!mCommandQueue.empty());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001395 return true;
1396}
1397
Prabir Pradhancef936d2021-07-21 16:17:52 +00001398void InputDispatcher::postCommandLocked(Command&& command) {
1399 mCommandQueue.push_back(command);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001400}
1401
1402void InputDispatcher::drainInboundQueueLocked() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001403 while (!mInboundQueue.empty()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001404 std::shared_ptr<EventEntry> entry = mInboundQueue.front();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001405 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001406 releaseInboundEventLocked(entry);
1407 }
1408 traceInboundQueueLengthLocked();
1409}
1410
1411void InputDispatcher::releasePendingEventLocked() {
1412 if (mPendingEvent) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001413 releaseInboundEventLocked(mPendingEvent);
Yi Kong9b14ac62018-07-17 13:48:38 -07001414 mPendingEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001415 }
1416}
1417
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001418void InputDispatcher::releaseInboundEventLocked(std::shared_ptr<EventEntry> entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001419 InjectionState* injectionState = entry->injectionState;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001420 if (injectionState && injectionState->injectionResult == InputEventInjectionResult::PENDING) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001421 if (DEBUG_DISPATCH_CYCLE) {
1422 ALOGD("Injected inbound event was dropped.");
1423 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001424 setInjectionResult(*entry, InputEventInjectionResult::FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001425 }
1426 if (entry == mNextUnblockedEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001427 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001428 }
1429 addRecentEventLocked(entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001430}
1431
1432void InputDispatcher::resetKeyRepeatLocked() {
1433 if (mKeyRepeatState.lastKeyEntry) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001434 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001435 }
1436}
1437
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001438std::shared_ptr<KeyEntry> InputDispatcher::synthesizeKeyRepeatLocked(nsecs_t currentTime) {
1439 std::shared_ptr<KeyEntry> entry = mKeyRepeatState.lastKeyEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001440
Michael Wright2e732952014-09-24 13:26:59 -07001441 uint32_t policyFlags = entry->policyFlags &
1442 (POLICY_FLAG_RAW_MASK | POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_TRUSTED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001443
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001444 std::shared_ptr<KeyEntry> newEntry =
1445 std::make_unique<KeyEntry>(mIdGenerator.nextId(), currentTime, entry->deviceId,
1446 entry->source, entry->displayId, policyFlags, entry->action,
1447 entry->flags, entry->keyCode, entry->scanCode,
1448 entry->metaState, entry->repeatCount + 1, entry->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001449
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001450 newEntry->syntheticRepeat = true;
1451 mKeyRepeatState.lastKeyEntry = newEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001452 mKeyRepeatState.nextRepeatTime = currentTime + mConfig.keyRepeatDelay;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001453 return newEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001454}
1455
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001456bool InputDispatcher::dispatchConfigurationChangedLocked(nsecs_t currentTime,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001457 const ConfigurationChangedEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001458 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1459 ALOGD("dispatchConfigurationChanged - eventTime=%" PRId64, entry.eventTime);
1460 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001461
1462 // Reset key repeating in case a keyboard device was added or removed or something.
1463 resetKeyRepeatLocked();
1464
1465 // Enqueue a command to run outside the lock to tell the policy that the configuration changed.
Prabir Pradhancef936d2021-07-21 16:17:52 +00001466 auto command = [this, eventTime = entry.eventTime]() REQUIRES(mLock) {
1467 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00001468 mPolicy.notifyConfigurationChanged(eventTime);
Prabir Pradhancef936d2021-07-21 16:17:52 +00001469 };
1470 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001471 return true;
1472}
1473
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001474bool InputDispatcher::dispatchDeviceResetLocked(nsecs_t currentTime,
1475 const DeviceResetEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001476 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1477 ALOGD("dispatchDeviceReset - eventTime=%" PRId64 ", deviceId=%d", entry.eventTime,
1478 entry.deviceId);
1479 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001480
liushenxiang42232912021-05-21 20:24:09 +08001481 // Reset key repeating in case a keyboard device was disabled or enabled.
1482 if (mKeyRepeatState.lastKeyEntry && mKeyRepeatState.lastKeyEntry->deviceId == entry.deviceId) {
1483 resetKeyRepeatLocked();
1484 }
1485
Michael Wrightfb04fd52022-11-24 22:31:11 +00001486 CancelationOptions options(CancelationOptions::Mode::CANCEL_ALL_EVENTS, "device was reset");
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001487 options.deviceId = entry.deviceId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001488 synthesizeCancelationEventsForAllConnectionsLocked(options);
Siarhei Vishniakou0686f0c2023-05-02 11:56:15 -07001489
1490 // Remove all active pointers from this device
1491 for (auto& [_, touchState] : mTouchStatesByDisplay) {
1492 touchState.removeAllPointersForDevice(entry.deviceId);
1493 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001494 return true;
1495}
1496
Vishnu Nairad321cd2020-08-20 16:40:21 -07001497void InputDispatcher::enqueueFocusEventLocked(const sp<IBinder>& windowToken, bool hasFocus,
Vishnu Nairc519ff72021-01-21 08:23:08 -08001498 const std::string& reason) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001499 if (mPendingEvent != nullptr) {
1500 // Move the pending event to the front of the queue. This will give the chance
1501 // for the pending event to get dispatched to the newly focused window
1502 mInboundQueue.push_front(mPendingEvent);
1503 mPendingEvent = nullptr;
1504 }
1505
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001506 std::unique_ptr<FocusEntry> focusEntry =
1507 std::make_unique<FocusEntry>(mIdGenerator.nextId(), now(), windowToken, hasFocus,
1508 reason);
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001509
1510 // This event should go to the front of the queue, but behind all other focus events
1511 // Find the last focus event, and insert right after it
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001512 std::deque<std::shared_ptr<EventEntry>>::reverse_iterator it =
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001513 std::find_if(mInboundQueue.rbegin(), mInboundQueue.rend(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001514 [](const std::shared_ptr<EventEntry>& event) {
1515 return event->type == EventEntry::Type::FOCUS;
1516 });
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001517
1518 // Maintain the order of focus events. Insert the entry after all other focus events.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001519 mInboundQueue.insert(it.base(), std::move(focusEntry));
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001520}
1521
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001522void InputDispatcher::dispatchFocusLocked(nsecs_t currentTime, std::shared_ptr<FocusEntry> entry) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05001523 std::shared_ptr<InputChannel> channel = getInputChannelLocked(entry->connectionToken);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001524 if (channel == nullptr) {
1525 return; // Window has gone away
1526 }
1527 InputTarget target;
1528 target.inputChannel = channel;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08001529 target.flags = InputTarget::Flags::DISPATCH_AS_IS;
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001530 entry->dispatchInProgress = true;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00001531 std::string message = std::string("Focus ") + (entry->hasFocus ? "entering " : "leaving ") +
1532 channel->getName();
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07001533 std::string reason = std::string("reason=").append(entry->reason);
1534 android_log_event_list(LOGTAG_INPUT_FOCUS) << message << reason << LOG_ID_EVENTS;
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001535 dispatchEventLocked(currentTime, entry, {target});
1536}
1537
Prabir Pradhan99987712020-11-10 18:43:05 -08001538void InputDispatcher::dispatchPointerCaptureChangedLocked(
1539 nsecs_t currentTime, const std::shared_ptr<PointerCaptureChangedEntry>& entry,
1540 DropReason& dropReason) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001541 dropReason = DropReason::NOT_DROPPED;
1542
Prabir Pradhan99987712020-11-10 18:43:05 -08001543 const bool haveWindowWithPointerCapture = mWindowTokenWithPointerCapture != nullptr;
Prabir Pradhan99987712020-11-10 18:43:05 -08001544 sp<IBinder> token;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001545
1546 if (entry->pointerCaptureRequest.enable) {
1547 // Enable Pointer Capture.
1548 if (haveWindowWithPointerCapture &&
1549 (entry->pointerCaptureRequest == mCurrentPointerCaptureRequest)) {
Prabir Pradhan7092e262022-05-03 16:51:09 +00001550 // This can happen if pointer capture is disabled and re-enabled before we notify the
1551 // app of the state change, so there is no need to notify the app.
1552 ALOGI("Skipping dispatch of Pointer Capture being enabled: no state change.");
1553 return;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001554 }
1555 if (!mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08001556 // This can happen if a window requests capture and immediately releases capture.
1557 ALOGW("No window requested Pointer Capture.");
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001558 dropReason = DropReason::NO_POINTER_CAPTURE;
Prabir Pradhan99987712020-11-10 18:43:05 -08001559 return;
1560 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001561 if (entry->pointerCaptureRequest.seq != mCurrentPointerCaptureRequest.seq) {
1562 ALOGI("Skipping dispatch of Pointer Capture being enabled: sequence number mismatch.");
1563 return;
1564 }
1565
Vishnu Nairc519ff72021-01-21 08:23:08 -08001566 token = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Prabir Pradhan99987712020-11-10 18:43:05 -08001567 LOG_ALWAYS_FATAL_IF(!token, "Cannot find focused window for Pointer Capture.");
1568 mWindowTokenWithPointerCapture = token;
1569 } else {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001570 // Disable Pointer Capture.
1571 // We do not check if the sequence number matches for requests to disable Pointer Capture
1572 // for two reasons:
1573 // 1. Pointer Capture can be disabled by a focus change, which means we can get two entries
1574 // to disable capture with the same sequence number: one generated by
1575 // disablePointerCaptureForcedLocked() and another as an acknowledgement of Pointer
1576 // Capture being disabled in InputReader.
1577 // 2. We respect any request to disable Pointer Capture generated by InputReader, since the
1578 // actual Pointer Capture state that affects events being generated by input devices is
1579 // in InputReader.
1580 if (!haveWindowWithPointerCapture) {
1581 // Pointer capture was already forcefully disabled because of focus change.
1582 dropReason = DropReason::NOT_DROPPED;
1583 return;
1584 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001585 token = mWindowTokenWithPointerCapture;
1586 mWindowTokenWithPointerCapture = nullptr;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001587 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan7d030382020-12-21 07:58:35 -08001588 setPointerCaptureLocked(false);
1589 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001590 }
1591
1592 auto channel = getInputChannelLocked(token);
1593 if (channel == nullptr) {
1594 // Window has gone away, clean up Pointer Capture state.
1595 mWindowTokenWithPointerCapture = nullptr;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001596 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan7d030382020-12-21 07:58:35 -08001597 setPointerCaptureLocked(false);
1598 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001599 return;
1600 }
1601 InputTarget target;
1602 target.inputChannel = channel;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08001603 target.flags = InputTarget::Flags::DISPATCH_AS_IS;
Prabir Pradhan99987712020-11-10 18:43:05 -08001604 entry->dispatchInProgress = true;
1605 dispatchEventLocked(currentTime, entry, {target});
1606
1607 dropReason = DropReason::NOT_DROPPED;
1608}
1609
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001610void InputDispatcher::dispatchTouchModeChangeLocked(nsecs_t currentTime,
1611 const std::shared_ptr<TouchModeEntry>& entry) {
1612 const std::vector<sp<WindowInfoHandle>>& windowHandles =
Antonio Kantek15beb512022-06-13 22:35:41 +00001613 getWindowHandlesLocked(entry->displayId);
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001614 if (windowHandles.empty()) {
1615 return;
1616 }
1617 const std::vector<InputTarget> inputTargets =
1618 getInputTargetsFromWindowHandlesLocked(windowHandles);
1619 if (inputTargets.empty()) {
1620 return;
1621 }
1622 entry->dispatchInProgress = true;
1623 dispatchEventLocked(currentTime, entry, inputTargets);
1624}
1625
1626std::vector<InputTarget> InputDispatcher::getInputTargetsFromWindowHandlesLocked(
1627 const std::vector<sp<WindowInfoHandle>>& windowHandles) const {
1628 std::vector<InputTarget> inputTargets;
1629 for (const sp<WindowInfoHandle>& handle : windowHandles) {
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001630 const sp<IBinder>& token = handle->getToken();
1631 if (token == nullptr) {
1632 continue;
1633 }
1634 std::shared_ptr<InputChannel> channel = getInputChannelLocked(token);
1635 if (channel == nullptr) {
1636 continue; // Window has gone away
1637 }
1638 InputTarget target;
1639 target.inputChannel = channel;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08001640 target.flags = InputTarget::Flags::DISPATCH_AS_IS;
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001641 inputTargets.push_back(target);
1642 }
1643 return inputTargets;
1644}
1645
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001646bool InputDispatcher::dispatchKeyLocked(nsecs_t currentTime, std::shared_ptr<KeyEntry> entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001647 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001648 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001649 if (!entry->dispatchInProgress) {
1650 if (entry->repeatCount == 0 && entry->action == AKEY_EVENT_ACTION_DOWN &&
1651 (entry->policyFlags & POLICY_FLAG_TRUSTED) &&
1652 (!(entry->policyFlags & POLICY_FLAG_DISABLE_KEY_REPEAT))) {
1653 if (mKeyRepeatState.lastKeyEntry &&
Chris Ye2ad95392020-09-01 13:44:44 -07001654 mKeyRepeatState.lastKeyEntry->keyCode == entry->keyCode &&
Michael Wrightd02c5b62014-02-10 15:10:22 -08001655 // We have seen two identical key downs in a row which indicates that the device
1656 // driver is automatically generating key repeats itself. We take note of the
1657 // repeat here, but we disable our own next key repeat timer since it is clear that
1658 // we will not need to synthesize key repeats ourselves.
Chris Ye2ad95392020-09-01 13:44:44 -07001659 mKeyRepeatState.lastKeyEntry->deviceId == entry->deviceId) {
1660 // Make sure we don't get key down from a different device. If a different
1661 // device Id has same key pressed down, the new device Id will replace the
1662 // current one to hold the key repeat with repeat count reset.
1663 // In the future when got a KEY_UP on the device id, drop it and do not
1664 // stop the key repeat on current device.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001665 entry->repeatCount = mKeyRepeatState.lastKeyEntry->repeatCount + 1;
1666 resetKeyRepeatLocked();
Colin Cross5b799302022-10-18 21:52:41 -07001667 mKeyRepeatState.nextRepeatTime = LLONG_MAX; // don't generate repeats ourselves
Michael Wrightd02c5b62014-02-10 15:10:22 -08001668 } else {
1669 // Not a repeat. Save key down state in case we do see a repeat later.
1670 resetKeyRepeatLocked();
1671 mKeyRepeatState.nextRepeatTime = entry->eventTime + mConfig.keyRepeatTimeout;
1672 }
1673 mKeyRepeatState.lastKeyEntry = entry;
Chris Ye2ad95392020-09-01 13:44:44 -07001674 } else if (entry->action == AKEY_EVENT_ACTION_UP && mKeyRepeatState.lastKeyEntry &&
1675 mKeyRepeatState.lastKeyEntry->deviceId != entry->deviceId) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001676 // The key on device 'deviceId' is still down, do not stop key repeat
Prabir Pradhan65613802023-02-22 23:36:58 +00001677 if (debugInboundEventDetails()) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001678 ALOGD("deviceId=%d got KEY_UP as stale", entry->deviceId);
1679 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001680 } else if (!entry->syntheticRepeat) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001681 resetKeyRepeatLocked();
1682 }
1683
1684 if (entry->repeatCount == 1) {
1685 entry->flags |= AKEY_EVENT_FLAG_LONG_PRESS;
1686 } else {
1687 entry->flags &= ~AKEY_EVENT_FLAG_LONG_PRESS;
1688 }
1689
1690 entry->dispatchInProgress = true;
1691
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001692 logOutboundKeyDetails("dispatchKey - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001693 }
1694
1695 // Handle case where the policy asked us to try again later last time.
Michael Wright5caf55a2022-11-24 22:31:42 +00001696 if (entry->interceptKeyResult == KeyEntry::InterceptKeyResult::TRY_AGAIN_LATER) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001697 if (currentTime < entry->interceptKeyWakeupTime) {
1698 if (entry->interceptKeyWakeupTime < *nextWakeupTime) {
1699 *nextWakeupTime = entry->interceptKeyWakeupTime;
1700 }
1701 return false; // wait until next wakeup
1702 }
Michael Wright5caf55a2022-11-24 22:31:42 +00001703 entry->interceptKeyResult = KeyEntry::InterceptKeyResult::UNKNOWN;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001704 entry->interceptKeyWakeupTime = 0;
1705 }
1706
1707 // Give the policy a chance to intercept the key.
Michael Wright5caf55a2022-11-24 22:31:42 +00001708 if (entry->interceptKeyResult == KeyEntry::InterceptKeyResult::UNKNOWN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001709 if (entry->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07001710 sp<IBinder> focusedWindowToken =
Vishnu Nairc519ff72021-01-21 08:23:08 -08001711 mFocusResolver.getFocusedWindowToken(getTargetDisplayId(*entry));
Prabir Pradhancef936d2021-07-21 16:17:52 +00001712
1713 auto command = [this, focusedWindowToken, entry]() REQUIRES(mLock) {
1714 doInterceptKeyBeforeDispatchingCommand(focusedWindowToken, *entry);
1715 };
1716 postCommandLocked(std::move(command));
Josep del Riob3981622023-04-18 15:49:45 +00001717 // Poke user activity for keys not passed to user
1718 pokeUserActivityLocked(*entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001719 return false; // wait for the command to run
1720 } else {
Michael Wright5caf55a2022-11-24 22:31:42 +00001721 entry->interceptKeyResult = KeyEntry::InterceptKeyResult::CONTINUE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001722 }
Michael Wright5caf55a2022-11-24 22:31:42 +00001723 } else if (entry->interceptKeyResult == KeyEntry::InterceptKeyResult::SKIP) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001724 if (*dropReason == DropReason::NOT_DROPPED) {
1725 *dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001726 }
1727 }
1728
1729 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001730 if (*dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001731 setInjectionResult(*entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001732 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
1733 : InputEventInjectionResult::FAILED);
Garfield Tan6a5a14e2020-01-28 13:24:04 -08001734 mReporter->reportDroppedKey(entry->id);
Josep del Riob3981622023-04-18 15:49:45 +00001735 // Poke user activity for undispatched keys
1736 pokeUserActivityLocked(*entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001737 return true;
1738 }
1739
1740 // Identify targets.
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001741 InputEventInjectionResult injectionResult;
1742 sp<WindowInfoHandle> focusedWindow =
1743 findFocusedWindowTargetLocked(currentTime, *entry, nextWakeupTime,
1744 /*byref*/ injectionResult);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001745 if (injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001746 return false;
1747 }
1748
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001749 setInjectionResult(*entry, injectionResult);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001750 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001751 return true;
1752 }
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001753 LOG_ALWAYS_FATAL_IF(focusedWindow == nullptr);
1754
1755 std::vector<InputTarget> inputTargets;
1756 addWindowTargetLocked(focusedWindow,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08001757 InputTarget::Flags::FOREGROUND | InputTarget::Flags::DISPATCH_AS_IS,
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08001758 /*pointerIds=*/{}, getDownTime(*entry), inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001759
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001760 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001761 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001762
1763 // Dispatch the key.
1764 dispatchEventLocked(currentTime, entry, inputTargets);
1765 return true;
1766}
1767
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001768void InputDispatcher::logOutboundKeyDetails(const char* prefix, const KeyEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001769 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1770 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32 ", "
1771 "policyFlags=0x%x, action=0x%x, flags=0x%x, keyCode=0x%x, scanCode=0x%x, "
1772 "metaState=0x%x, repeatCount=%d, downTime=%" PRId64,
1773 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId,
1774 entry.policyFlags, entry.action, entry.flags, entry.keyCode, entry.scanCode,
1775 entry.metaState, entry.repeatCount, entry.downTime);
1776 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001777}
1778
Prabir Pradhancef936d2021-07-21 16:17:52 +00001779void InputDispatcher::dispatchSensorLocked(nsecs_t currentTime,
1780 const std::shared_ptr<SensorEntry>& entry,
Chris Yef59a2f42020-10-16 12:55:26 -07001781 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001782 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1783 ALOGD("notifySensorEvent eventTime=%" PRId64 ", hwTimestamp=%" PRId64 ", deviceId=%d, "
1784 "source=0x%x, sensorType=%s",
1785 entry->eventTime, entry->hwTimestamp, entry->deviceId, entry->source,
Dominik Laskowski75788452021-02-09 18:51:25 -08001786 ftl::enum_string(entry->sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001787 }
Prabir Pradhancef936d2021-07-21 16:17:52 +00001788 auto command = [this, entry]() REQUIRES(mLock) {
1789 scoped_unlock unlock(mLock);
1790
1791 if (entry->accuracyChanged) {
Prabir Pradhana41d2442023-04-20 21:30:40 +00001792 mPolicy.notifySensorAccuracy(entry->deviceId, entry->sensorType, entry->accuracy);
Prabir Pradhancef936d2021-07-21 16:17:52 +00001793 }
Prabir Pradhana41d2442023-04-20 21:30:40 +00001794 mPolicy.notifySensorEvent(entry->deviceId, entry->sensorType, entry->accuracy,
1795 entry->hwTimestamp, entry->values);
Prabir Pradhancef936d2021-07-21 16:17:52 +00001796 };
1797 postCommandLocked(std::move(command));
Chris Yef59a2f42020-10-16 12:55:26 -07001798}
1799
1800bool InputDispatcher::flushSensor(int deviceId, InputDeviceSensorType sensorType) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001801 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1802 ALOGD("flushSensor deviceId=%d, sensorType=%s", deviceId,
Dominik Laskowski75788452021-02-09 18:51:25 -08001803 ftl::enum_string(sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001804 }
Chris Yef59a2f42020-10-16 12:55:26 -07001805 { // acquire lock
1806 std::scoped_lock _l(mLock);
1807
1808 for (auto it = mInboundQueue.begin(); it != mInboundQueue.end(); it++) {
1809 std::shared_ptr<EventEntry> entry = *it;
1810 if (entry->type == EventEntry::Type::SENSOR) {
1811 it = mInboundQueue.erase(it);
1812 releaseInboundEventLocked(entry);
1813 }
1814 }
1815 }
1816 return true;
1817}
1818
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001819bool InputDispatcher::dispatchMotionLocked(nsecs_t currentTime, std::shared_ptr<MotionEntry> entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001820 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001821 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001822 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001823 if (!entry->dispatchInProgress) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001824 entry->dispatchInProgress = true;
1825
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001826 logOutboundMotionDetails("dispatchMotion - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001827 }
1828
1829 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001830 if (*dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001831 setInjectionResult(*entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001832 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
1833 : InputEventInjectionResult::FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001834 return true;
1835 }
1836
Prabir Pradhanaa561d12021-09-24 06:57:33 -07001837 const bool isPointerEvent = isFromSource(entry->source, AINPUT_SOURCE_CLASS_POINTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001838
1839 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001840 std::vector<InputTarget> inputTargets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001841
1842 bool conflictingPointerActions = false;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001843 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001844 if (isPointerEvent) {
1845 // Pointer event. (eg. touchscreen)
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00001846
1847 if (mDragState &&
1848 (entry->action & AMOTION_EVENT_ACTION_MASK) == AMOTION_EVENT_ACTION_POINTER_DOWN) {
1849 // If drag and drop ongoing and pointer down occur: pilfer drag window pointers
1850 pilferPointersLocked(mDragState->dragWindow->getToken());
1851 }
1852
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08001853 inputTargets =
Siarhei Vishniakou4fe57392022-10-25 13:44:30 -07001854 findTouchedWindowTargetsLocked(currentTime, *entry, &conflictingPointerActions,
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001855 /*byref*/ injectionResult);
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08001856 LOG_ALWAYS_FATAL_IF(injectionResult != InputEventInjectionResult::SUCCEEDED &&
1857 !inputTargets.empty());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001858 } else {
1859 // Non touch event. (eg. trackball)
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001860 sp<WindowInfoHandle> focusedWindow =
1861 findFocusedWindowTargetLocked(currentTime, *entry, nextWakeupTime, injectionResult);
1862 if (injectionResult == InputEventInjectionResult::SUCCEEDED) {
1863 LOG_ALWAYS_FATAL_IF(focusedWindow == nullptr);
1864 addWindowTargetLocked(focusedWindow,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08001865 InputTarget::Flags::FOREGROUND |
1866 InputTarget::Flags::DISPATCH_AS_IS,
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08001867 /*pointerIds=*/{}, getDownTime(*entry), inputTargets);
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001868 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001869 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001870 if (injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001871 return false;
1872 }
1873
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001874 setInjectionResult(*entry, injectionResult);
Prabir Pradhan5735a322022-04-11 17:23:34 +00001875 if (injectionResult == InputEventInjectionResult::TARGET_MISMATCH) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001876 return true;
1877 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001878 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001879 CancelationOptions::Mode mode(
1880 isPointerEvent ? CancelationOptions::Mode::CANCEL_POINTER_EVENTS
1881 : CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS);
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001882 CancelationOptions options(mode, "input event injection failed");
1883 synthesizeCancelationEventsForMonitorsLocked(options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001884 return true;
1885 }
1886
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001887 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001888 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001889
1890 // Dispatch the motion.
1891 if (conflictingPointerActions) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001892 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001893 "conflicting pointer actions");
Michael Wrightd02c5b62014-02-10 15:10:22 -08001894 synthesizeCancelationEventsForAllConnectionsLocked(options);
1895 }
1896 dispatchEventLocked(currentTime, entry, inputTargets);
1897 return true;
1898}
1899
chaviw98318de2021-05-19 16:45:23 -05001900void InputDispatcher::enqueueDragEventLocked(const sp<WindowInfoHandle>& windowHandle,
Arthur Hung54745652022-04-20 07:17:41 +00001901 bool isExiting, const int32_t rawX,
1902 const int32_t rawY) {
1903 const vec2 xy = windowHandle->getInfo()->transform.transform(vec2(rawX, rawY));
arthurhungb89ccb02020-12-30 16:19:01 +08001904 std::unique_ptr<DragEntry> dragEntry =
Arthur Hung54745652022-04-20 07:17:41 +00001905 std::make_unique<DragEntry>(mIdGenerator.nextId(), now(), windowHandle->getToken(),
1906 isExiting, xy.x, xy.y);
arthurhungb89ccb02020-12-30 16:19:01 +08001907
1908 enqueueInboundEventLocked(std::move(dragEntry));
1909}
1910
1911void InputDispatcher::dispatchDragLocked(nsecs_t currentTime, std::shared_ptr<DragEntry> entry) {
1912 std::shared_ptr<InputChannel> channel = getInputChannelLocked(entry->connectionToken);
1913 if (channel == nullptr) {
1914 return; // Window has gone away
1915 }
1916 InputTarget target;
1917 target.inputChannel = channel;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08001918 target.flags = InputTarget::Flags::DISPATCH_AS_IS;
arthurhungb89ccb02020-12-30 16:19:01 +08001919 entry->dispatchInProgress = true;
1920 dispatchEventLocked(currentTime, entry, {target});
1921}
1922
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001923void InputDispatcher::logOutboundMotionDetails(const char* prefix, const MotionEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001924 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -08001925 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=%s, displayId=%" PRId32
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001926 ", policyFlags=0x%x, "
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001927 "action=%s, actionButton=0x%x, flags=0x%x, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001928 "metaState=0x%x, buttonState=0x%x,"
1929 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%" PRId64,
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -08001930 prefix, entry.eventTime, entry.deviceId,
1931 inputEventSourceToString(entry.source).c_str(), entry.displayId, entry.policyFlags,
1932 MotionEvent::actionToString(entry.action).c_str(), entry.actionButton, entry.flags,
1933 entry.metaState, entry.buttonState, entry.edgeFlags, entry.xPrecision,
1934 entry.yPrecision, entry.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001935
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001936 for (uint32_t i = 0; i < entry.pointerCount; i++) {
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07001937 ALOGD(" Pointer %d: id=%d, toolType=%s, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001938 "x=%f, y=%f, pressure=%f, size=%f, "
1939 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
1940 "orientation=%f",
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07001941 i, entry.pointerProperties[i].id,
1942 ftl::enum_string(entry.pointerProperties[i].toolType).c_str(),
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001943 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
1944 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
1945 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
1946 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
1947 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
1948 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
1949 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
1950 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
1951 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
1952 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001953 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001954}
1955
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001956void InputDispatcher::dispatchEventLocked(nsecs_t currentTime,
1957 std::shared_ptr<EventEntry> eventEntry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001958 const std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001959 ATRACE_CALL();
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001960 if (DEBUG_DISPATCH_CYCLE) {
1961 ALOGD("dispatchEventToCurrentInputTargets");
1962 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001963
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00001964 processInteractionsLocked(*eventEntry, inputTargets);
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00001965
Michael Wrightd02c5b62014-02-10 15:10:22 -08001966 ALOG_ASSERT(eventEntry->dispatchInProgress); // should already have been set to true
1967
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001968 pokeUserActivityLocked(*eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001969
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001970 for (const InputTarget& inputTarget : inputTargets) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07001971 std::shared_ptr<Connection> connection =
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07001972 getConnectionLocked(inputTarget.inputChannel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07001973 if (connection != nullptr) {
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08001974 prepareDispatchCycleLocked(currentTime, connection, eventEntry, inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001975 } else {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001976 if (DEBUG_FOCUS) {
1977 ALOGD("Dropping event delivery to target with channel '%s' because it "
1978 "is no longer registered with the input dispatcher.",
1979 inputTarget.inputChannel->getName().c_str());
1980 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001981 }
1982 }
1983}
1984
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07001985void InputDispatcher::cancelEventsForAnrLocked(const std::shared_ptr<Connection>& connection) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001986 // We will not be breaking any connections here, even if the policy wants us to abort dispatch.
1987 // If the policy decides to close the app, we will get a channel removal event via
1988 // unregisterInputChannel, and will clean up the connection that way. We are already not
1989 // sending new pointers to the connection when it blocked, but focused events will continue to
1990 // pile up.
1991 ALOGW("Canceling events for %s because it is unresponsive",
1992 connection->inputChannel->getName().c_str());
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08001993 if (connection->status == Connection::Status::NORMAL) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001994 CancelationOptions options(CancelationOptions::Mode::CANCEL_ALL_EVENTS,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001995 "application not responding");
1996 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001997 }
1998}
1999
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002000void InputDispatcher::resetNoFocusedWindowTimeoutLocked() {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002001 if (DEBUG_FOCUS) {
2002 ALOGD("Resetting ANR timeouts.");
2003 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002004
2005 // Reset input target wait timeout.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002006 mNoFocusedWindowTimeoutTime = std::nullopt;
Chris Yea209fde2020-07-22 13:54:51 -07002007 mAwaitedFocusedApplication.reset();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002008}
2009
Tiger Huang721e26f2018-07-24 22:26:19 +08002010/**
2011 * Get the display id that the given event should go to. If this event specifies a valid display id,
2012 * then it should be dispatched to that display. Otherwise, the event goes to the focused display.
2013 * Focused display is the display that the user most recently interacted with.
2014 */
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002015int32_t InputDispatcher::getTargetDisplayId(const EventEntry& entry) {
Tiger Huang721e26f2018-07-24 22:26:19 +08002016 int32_t displayId;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002017 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002018 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002019 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
2020 displayId = keyEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002021 break;
2022 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002023 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002024 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
2025 displayId = motionEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002026 break;
2027 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00002028 case EventEntry::Type::TOUCH_MODE_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08002029 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002030 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002031 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07002032 case EventEntry::Type::DEVICE_RESET:
arthurhungb89ccb02020-12-30 16:19:01 +08002033 case EventEntry::Type::SENSOR:
2034 case EventEntry::Type::DRAG: {
Dominik Laskowski75788452021-02-09 18:51:25 -08002035 ALOGE("%s events do not have a target display", ftl::enum_string(entry.type).c_str());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002036 return ADISPLAY_ID_NONE;
2037 }
Tiger Huang721e26f2018-07-24 22:26:19 +08002038 }
2039 return displayId == ADISPLAY_ID_NONE ? mFocusedDisplayId : displayId;
2040}
2041
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002042bool InputDispatcher::shouldWaitToSendKeyLocked(nsecs_t currentTime,
2043 const char* focusedWindowName) {
2044 if (mAnrTracker.empty()) {
2045 // already processed all events that we waited for
2046 mKeyIsWaitingForEventsTimeout = std::nullopt;
2047 return false;
2048 }
2049
2050 if (!mKeyIsWaitingForEventsTimeout.has_value()) {
2051 // Start the timer
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00002052 // Wait to send key because there are unprocessed events that may cause focus to change
Siarhei Vishniakou70622952020-07-30 11:17:23 -05002053 mKeyIsWaitingForEventsTimeout = currentTime +
2054 std::chrono::duration_cast<std::chrono::nanoseconds>(KEY_WAITING_FOR_EVENTS_TIMEOUT)
2055 .count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002056 return true;
2057 }
2058
2059 // We still have pending events, and already started the timer
2060 if (currentTime < *mKeyIsWaitingForEventsTimeout) {
2061 return true; // Still waiting
2062 }
2063
2064 // Waited too long, and some connection still hasn't processed all motions
2065 // Just send the key to the focused window
2066 ALOGW("Dispatching key to %s even though there are other unprocessed events",
2067 focusedWindowName);
2068 mKeyIsWaitingForEventsTimeout = std::nullopt;
2069 return false;
2070}
2071
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002072sp<WindowInfoHandle> InputDispatcher::findFocusedWindowTargetLocked(
2073 nsecs_t currentTime, const EventEntry& entry, nsecs_t* nextWakeupTime,
2074 InputEventInjectionResult& outInjectionResult) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002075 std::string reason;
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002076 outInjectionResult = InputEventInjectionResult::FAILED; // Default result
Michael Wrightd02c5b62014-02-10 15:10:22 -08002077
Tiger Huang721e26f2018-07-24 22:26:19 +08002078 int32_t displayId = getTargetDisplayId(entry);
chaviw98318de2021-05-19 16:45:23 -05002079 sp<WindowInfoHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Chris Yea209fde2020-07-22 13:54:51 -07002080 std::shared_ptr<InputApplicationHandle> focusedApplicationHandle =
Tiger Huang721e26f2018-07-24 22:26:19 +08002081 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
2082
Michael Wrightd02c5b62014-02-10 15:10:22 -08002083 // If there is no currently focused window and no focused application
2084 // then drop the event.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002085 if (focusedWindowHandle == nullptr && focusedApplicationHandle == nullptr) {
2086 ALOGI("Dropping %s event because there is no focused window or focused application in "
2087 "display %" PRId32 ".",
Dominik Laskowski75788452021-02-09 18:51:25 -08002088 ftl::enum_string(entry.type).c_str(), displayId);
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002089 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002090 }
2091
Vishnu Nair062a8672021-09-03 16:07:44 -07002092 // Drop key events if requested by input feature
2093 if (focusedWindowHandle != nullptr && shouldDropInput(entry, focusedWindowHandle)) {
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002094 return nullptr;
Vishnu Nair062a8672021-09-03 16:07:44 -07002095 }
2096
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002097 // Compatibility behavior: raise ANR if there is a focused application, but no focused window.
2098 // Only start counting when we have a focused event to dispatch. The ANR is canceled if we
2099 // start interacting with another application via touch (app switch). This code can be removed
2100 // if the "no focused window ANR" is moved to the policy. Input doesn't know whether
2101 // an app is expected to have a focused window.
2102 if (focusedWindowHandle == nullptr && focusedApplicationHandle != nullptr) {
2103 if (!mNoFocusedWindowTimeoutTime.has_value()) {
2104 // We just discovered that there's no focused window. Start the ANR timer
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05002105 std::chrono::nanoseconds timeout = focusedApplicationHandle->getDispatchingTimeout(
2106 DEFAULT_INPUT_DISPATCHING_TIMEOUT);
2107 mNoFocusedWindowTimeoutTime = currentTime + timeout.count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002108 mAwaitedFocusedApplication = focusedApplicationHandle;
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05002109 mAwaitedApplicationDisplayId = displayId;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002110 ALOGW("Waiting because no window has focus but %s may eventually add a "
2111 "window when it finishes starting up. Will wait for %" PRId64 "ms",
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05002112 mAwaitedFocusedApplication->getName().c_str(), millis(timeout));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002113 *nextWakeupTime = *mNoFocusedWindowTimeoutTime;
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002114 outInjectionResult = InputEventInjectionResult::PENDING;
2115 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002116 } else if (currentTime > *mNoFocusedWindowTimeoutTime) {
2117 // Already raised ANR. Drop the event
2118 ALOGE("Dropping %s event because there is no focused window",
Dominik Laskowski75788452021-02-09 18:51:25 -08002119 ftl::enum_string(entry.type).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002120 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002121 } else {
2122 // Still waiting for the focused window
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002123 outInjectionResult = InputEventInjectionResult::PENDING;
2124 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002125 }
2126 }
2127
2128 // we have a valid, non-null focused window
2129 resetNoFocusedWindowTimeoutLocked();
2130
Prabir Pradhan5735a322022-04-11 17:23:34 +00002131 // Verify targeted injection.
2132 if (const auto err = verifyTargetedInjection(focusedWindowHandle, entry); err) {
2133 ALOGW("Dropping injected event: %s", (*err).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002134 outInjectionResult = InputEventInjectionResult::TARGET_MISMATCH;
2135 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002136 }
2137
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002138 if (focusedWindowHandle->getInfo()->inputConfig.test(
2139 WindowInfo::InputConfig::PAUSE_DISPATCHING)) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002140 ALOGI("Waiting because %s is paused", focusedWindowHandle->getName().c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002141 outInjectionResult = InputEventInjectionResult::PENDING;
2142 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002143 }
2144
2145 // If the event is a key event, then we must wait for all previous events to
2146 // complete before delivering it because previous events may have the
2147 // side-effect of transferring focus to a different window and we want to
2148 // ensure that the following keys are sent to the new window.
2149 //
2150 // Suppose the user touches a button in a window then immediately presses "A".
2151 // If the button causes a pop-up window to appear then we want to ensure that
2152 // the "A" key is delivered to the new pop-up window. This is because users
2153 // often anticipate pending UI changes when typing on a keyboard.
2154 // To obtain this behavior, we must serialize key events with respect to all
2155 // prior input events.
2156 if (entry.type == EventEntry::Type::KEY) {
2157 if (shouldWaitToSendKeyLocked(currentTime, focusedWindowHandle->getName().c_str())) {
2158 *nextWakeupTime = *mKeyIsWaitingForEventsTimeout;
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002159 outInjectionResult = InputEventInjectionResult::PENDING;
2160 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002161 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002162 }
2163
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002164 outInjectionResult = InputEventInjectionResult::SUCCEEDED;
2165 return focusedWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002166}
2167
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002168/**
2169 * Given a list of monitors, remove the ones we cannot find a connection for, and the ones
2170 * that are currently unresponsive.
2171 */
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002172std::vector<Monitor> InputDispatcher::selectResponsiveMonitorsLocked(
2173 const std::vector<Monitor>& monitors) const {
2174 std::vector<Monitor> responsiveMonitors;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002175 std::copy_if(monitors.begin(), monitors.end(), std::back_inserter(responsiveMonitors),
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002176 [this](const Monitor& monitor) REQUIRES(mLock) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07002177 std::shared_ptr<Connection> connection =
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002178 getConnectionLocked(monitor.inputChannel->getConnectionToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002179 if (connection == nullptr) {
2180 ALOGE("Could not find connection for monitor %s",
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002181 monitor.inputChannel->getName().c_str());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002182 return false;
2183 }
2184 if (!connection->responsive) {
2185 ALOGW("Unresponsive monitor %s will not get the new gesture",
2186 connection->inputChannel->getName().c_str());
2187 return false;
2188 }
2189 return true;
2190 });
2191 return responsiveMonitors;
2192}
2193
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07002194/**
2195 * In general, touch should be always split between windows. Some exceptions:
2196 * 1. Don't split touch is if we have an active pointer down, and a new pointer is going down that's
2197 * from the same device, *and* the window that's receiving the current pointer does not support
2198 * split touch.
2199 * 2. Don't split mouse events
2200 */
2201bool InputDispatcher::shouldSplitTouch(const TouchState& touchState,
2202 const MotionEntry& entry) const {
2203 if (isFromSource(entry.source, AINPUT_SOURCE_MOUSE)) {
2204 // We should never split mouse events
2205 return false;
2206 }
2207 for (const TouchedWindow& touchedWindow : touchState.windows) {
2208 if (touchedWindow.windowHandle->getInfo()->isSpy()) {
2209 // Spy windows should not affect whether or not touch is split.
2210 continue;
2211 }
2212 if (touchedWindow.windowHandle->getInfo()->supportsSplitTouch()) {
2213 continue;
2214 }
Arthur Hungc539dbb2022-12-08 07:45:36 +00002215 if (touchedWindow.windowHandle->getInfo()->inputConfig.test(
2216 gui::WindowInfo::InputConfig::IS_WALLPAPER)) {
2217 // Wallpaper window should not affect whether or not touch is split
2218 continue;
2219 }
2220
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07002221 // Eventually, touchedWindow will contain the deviceId of each pointer that's currently
2222 // being sent there. For now, use deviceId from touch state.
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08002223 if (entry.deviceId == touchState.deviceId && touchedWindow.pointerIds.any()) {
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07002224 return false;
2225 }
2226 }
2227 return true;
2228}
2229
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002230std::vector<InputTarget> InputDispatcher::findTouchedWindowTargetsLocked(
Siarhei Vishniakou4fe57392022-10-25 13:44:30 -07002231 nsecs_t currentTime, const MotionEntry& entry, bool* outConflictingPointerActions,
2232 InputEventInjectionResult& outInjectionResult) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002233 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002234
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002235 std::vector<InputTarget> targets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002236 // For security reasons, we defer updating the touch state until we are sure that
2237 // event injection will be allowed.
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002238 const int32_t displayId = entry.displayId;
2239 const int32_t action = entry.action;
Siarhei Vishniakoubf880522023-05-01 11:03:22 -07002240 const int32_t maskedAction = MotionEvent::getActionMasked(action);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002241
2242 // Update the touch state as needed based on the properties of the touch event.
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002243 outInjectionResult = InputEventInjectionResult::PENDING;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002244
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002245 // Copy current touch state into tempTouchState.
2246 // This state will be used to update mTouchStatesByDisplay at the end of this function.
2247 // If no state for the specified display exists, then our initial state will be empty.
Yi Kong9b14ac62018-07-17 13:48:38 -07002248 const TouchState* oldState = nullptr;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002249 TouchState tempTouchState;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002250 if (const auto it = mTouchStatesByDisplay.find(displayId); it != mTouchStatesByDisplay.end()) {
2251 oldState = &(it->second);
Prabir Pradhane680f9b2022-02-04 04:24:00 -08002252 tempTouchState = *oldState;
Jeff Brownf086ddb2014-02-11 14:28:48 -08002253 }
2254
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07002255 bool isSplit = shouldSplitTouch(tempTouchState, entry);
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07002256 const bool switchedDevice = (oldState != nullptr) &&
Siarhei Vishniakou5cee1e32022-11-29 12:35:39 -08002257 (oldState->deviceId != entry.deviceId || oldState->source != entry.source);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002258
2259 const bool isHoverAction = (maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE ||
2260 maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2261 maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT);
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002262 // A DOWN could be generated from POINTER_DOWN if the initial pointers did not land into any
2263 // touchable windows.
2264 const bool wasDown = oldState != nullptr && oldState->isDown();
2265 const bool isDown = (maskedAction == AMOTION_EVENT_ACTION_DOWN) ||
2266 (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN && !wasDown);
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07002267 const bool newGesture = isDown || maskedAction == AMOTION_EVENT_ACTION_SCROLL ||
2268 maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2269 maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE;
Prabir Pradhanaa561d12021-09-24 06:57:33 -07002270 const bool isFromMouse = isFromSource(entry.source, AINPUT_SOURCE_MOUSE);
Siarhei Vishniakou5cee1e32022-11-29 12:35:39 -08002271
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002272 // If pointers are already down, let's finish the current gesture and ignore the new events
2273 // from another device. However, if the new event is a down event, let's cancel the current
2274 // touch and let the new one take over.
2275 if (switchedDevice && wasDown && !isDown) {
2276 LOG(INFO) << "Dropping event because a pointer for device " << oldState->deviceId
2277 << " is already down in display " << displayId << ": " << entry.getDescription();
2278 // TODO(b/211379801): test multiple simultaneous input streams.
2279 outInjectionResult = InputEventInjectionResult::FAILED;
2280 return {}; // wrong device
2281 }
2282
Michael Wrightd02c5b62014-02-10 15:10:22 -08002283 if (newGesture) {
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002284 // If a new gesture is starting, clear the touch state completely.
2285 tempTouchState.reset();
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002286 tempTouchState.deviceId = entry.deviceId;
2287 tempTouchState.source = entry.source;
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);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002307 const int32_t pointerIndex = getMotionEventActionPointerIndex(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 Vishniakoud44dddf2020-03-25 16:16:40 -07002340 newTouchedWindowHandle = nullptr;
2341 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002342 } else {
2343 // No window is touched, so set split to true. This will allow the next pointer down to
Prabir Pradhan713bb3e2021-12-20 02:07:40 -08002344 // be delivered to a new window which supports split touch. Pointers from a mouse device
2345 // should never be split.
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07002346 isSplit = !isFromMouse;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002347 }
2348
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002349 std::vector<sp<WindowInfoHandle>> newTouchedWindows =
Prabir Pradhand65552b2021-10-07 11:23:50 -07002350 findTouchedSpyWindowsAtLocked(displayId, x, y, isStylus);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002351 if (newTouchedWindowHandle != nullptr) {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002352 // Process the foreground window first so that it is the first to receive the event.
2353 newTouchedWindows.insert(newTouchedWindows.begin(), newTouchedWindowHandle);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002354 }
2355
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002356 if (newTouchedWindows.empty()) {
Prabir Pradhan82e081e2022-12-06 09:50:09 +00002357 ALOGI("Dropping event because there is no touchable window at (%.1f, %.1f) on display "
2358 "%d.",
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002359 x, y, displayId);
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002360 outInjectionResult = InputEventInjectionResult::FAILED;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002361 return {};
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002362 }
2363
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002364 for (const sp<WindowInfoHandle>& windowHandle : newTouchedWindows) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07002365 if (!canWindowReceiveMotionLocked(windowHandle, entry)) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002366 continue;
2367 }
2368
Siarhei Vishniakoub681c202023-05-01 11:22:33 -07002369 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2370 maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE) {
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002371 const int32_t pointerId = entry.pointerProperties[0].id;
Siarhei Vishniakoub681c202023-05-01 11:22:33 -07002372 // The "windowHandle" is the target of this hovering pointer.
2373 tempTouchState.addHoveringPointerToWindow(windowHandle, entry.deviceId, pointerId);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002374 }
2375
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002376 // Set target flags.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002377 ftl::Flags<InputTarget::Flags> targetFlags = InputTarget::Flags::DISPATCH_AS_IS;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002378
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002379 if (canReceiveForegroundTouches(*windowHandle->getInfo())) {
2380 // There should only be one touched window that can be "foreground" for the pointer.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002381 targetFlags |= InputTarget::Flags::FOREGROUND;
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002382 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002383
2384 if (isSplit) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002385 targetFlags |= InputTarget::Flags::SPLIT;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002386 }
2387 if (isWindowObscuredAtPointLocked(windowHandle, x, y)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002388 targetFlags |= InputTarget::Flags::WINDOW_IS_OBSCURED;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002389 } else if (isWindowObscuredLocked(windowHandle)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002390 targetFlags |= InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002391 }
Michael Wright3dd60e22019-03-27 22:06:44 +00002392
2393 // Update the temporary touch state.
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08002394 std::bitset<MAX_POINTER_ID + 1> pointerIds;
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002395 if (!isHoverAction) {
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08002396 pointerIds.set(entry.pointerProperties[pointerIndex].id);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002397 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002398
Siarhei Vishniakoue0431e42023-01-28 17:01:39 -08002399 const bool isDownOrPointerDown = maskedAction == AMOTION_EVENT_ACTION_DOWN ||
2400 maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN;
2401
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002402 // TODO(b/211379801): Currently, even if pointerIds are empty (hover case), we would
2403 // still add a window to the touch state. We should avoid doing that, but some of the
2404 // later checks ("at least one foreground window") rely on this in order to dispatch
2405 // the event properly, so that needs to be updated, possibly by looking at InputTargets.
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002406 tempTouchState.addOrUpdateWindow(windowHandle, targetFlags, pointerIds,
Siarhei Vishniakoue0431e42023-01-28 17:01:39 -08002407 isDownOrPointerDown
2408 ? std::make_optional(entry.eventTime)
2409 : std::nullopt);
Arthur Hungc539dbb2022-12-08 07:45:36 +00002410
2411 // If this is the pointer going down and the touched window has a wallpaper
2412 // then also add the touched wallpaper windows so they are locked in for the duration
2413 // of the touch gesture.
2414 // We do not collect wallpapers during HOVER_MOVE or SCROLL because the wallpaper
2415 // engine only supports touch events. We would need to add a mechanism similar
2416 // to View.onGenericMotionEvent to enable wallpapers to handle these events.
Siarhei Vishniakoue0431e42023-01-28 17:01:39 -08002417 if (isDownOrPointerDown) {
Arthur Hungc539dbb2022-12-08 07:45:36 +00002418 if (targetFlags.test(InputTarget::Flags::FOREGROUND) &&
2419 windowHandle->getInfo()->inputConfig.test(
2420 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER)) {
2421 sp<WindowInfoHandle> wallpaper = findWallpaperWindowBelow(windowHandle);
2422 if (wallpaper != nullptr) {
2423 ftl::Flags<InputTarget::Flags> wallpaperFlags =
2424 InputTarget::Flags::WINDOW_IS_OBSCURED |
2425 InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED |
2426 InputTarget::Flags::DISPATCH_AS_IS;
2427 if (isSplit) {
2428 wallpaperFlags |= InputTarget::Flags::SPLIT;
2429 }
2430 tempTouchState.addOrUpdateWindow(wallpaper, wallpaperFlags, pointerIds,
2431 entry.eventTime);
2432 }
2433 }
2434 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002435 }
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00002436
Siarhei Vishniakou060f82b2023-01-27 06:39:14 -08002437 // If a window is already pilfering some pointers, give it this new pointer as well and
2438 // make it pilfering. This will prevent other non-spy windows from getting this pointer,
2439 // which is a specific behaviour that we want.
2440 const int32_t pointerId = entry.pointerProperties[pointerIndex].id;
2441 for (TouchedWindow& touchedWindow : tempTouchState.windows) {
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08002442 if (touchedWindow.pointerIds.test(pointerId) &&
Siarhei Vishniakou060f82b2023-01-27 06:39:14 -08002443 touchedWindow.pilferedPointerIds.count() > 0) {
2444 // This window is already pilfering some pointers, and this new pointer is also
2445 // going to it. Therefore, take over this pointer and don't give it to anyone
2446 // else.
2447 touchedWindow.pilferedPointerIds.set(pointerId);
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00002448 }
2449 }
Siarhei Vishniakou060f82b2023-01-27 06:39:14 -08002450
2451 // Restrict all pilfered pointers to the pilfering windows.
2452 tempTouchState.cancelPointersForNonPilferingWindows();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002453 } else {
2454 /* Case 2: Pointer move, up, cancel or non-splittable pointer down. */
2455
2456 // If the pointer is not currently down, then ignore the event.
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07002457 if (!tempTouchState.isDown() && maskedAction != AMOTION_EVENT_ACTION_HOVER_EXIT) {
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002458 LOG(INFO) << "Dropping event because the pointer is not down or we previously "
2459 "dropped the pointer down event in display "
2460 << displayId << ": " << entry.getDescription();
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002461 outInjectionResult = InputEventInjectionResult::FAILED;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002462 return {};
Michael Wrightd02c5b62014-02-10 15:10:22 -08002463 }
2464
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07002465 // If the pointer is not currently hovering, then ignore the event.
2466 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT) {
2467 const int32_t pointerId = entry.pointerProperties[0].id;
2468 if (oldState == nullptr ||
2469 oldState->getWindowsWithHoveringPointer(entry.deviceId, pointerId).empty()) {
2470 LOG(INFO) << "Dropping event because the hovering pointer is not in any windows in "
2471 "display "
2472 << displayId << ": " << entry.getDescription();
2473 outInjectionResult = InputEventInjectionResult::FAILED;
2474 return {};
2475 }
2476 tempTouchState.removeHoveringPointer(entry.deviceId, pointerId);
2477 }
2478
arthurhung6d4bed92021-03-17 11:59:33 +08002479 addDragEventLocked(entry);
arthurhungb89ccb02020-12-30 16:19:01 +08002480
Michael Wrightd02c5b62014-02-10 15:10:22 -08002481 // Check whether touches should slip outside of the current foreground window.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002482 if (maskedAction == AMOTION_EVENT_ACTION_MOVE && entry.pointerCount == 1 &&
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002483 tempTouchState.isSlippery()) {
Siarhei Vishniakou9306c382022-09-30 15:30:31 -07002484 const auto [x, y] = resolveTouchedPosition(entry);
Harry Cutts33476232023-01-30 19:57:29 +00002485 const bool isStylus = isPointerFromStylus(entry, /*pointerIndex=*/0);
chaviw98318de2021-05-19 16:45:23 -05002486 sp<WindowInfoHandle> oldTouchedWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002487 tempTouchState.getFirstForegroundWindowHandle();
Siarhei Vishniakou0f6558d2023-04-21 12:05:13 -07002488 LOG_ALWAYS_FATAL_IF(oldTouchedWindowHandle == nullptr);
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002489 auto [newTouchedWindowHandle, _] = findTouchedWindowAtLocked(displayId, x, y, isStylus);
Vishnu Nair062a8672021-09-03 16:07:44 -07002490
Prabir Pradhan5735a322022-04-11 17:23:34 +00002491 // Verify targeted injection.
2492 if (const auto err = verifyTargetedInjection(newTouchedWindowHandle, entry); err) {
2493 ALOGW("Dropping injected event: %s", (*err).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002494 outInjectionResult = os::InputEventInjectionResult::TARGET_MISMATCH;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002495 return {};
Prabir Pradhan5735a322022-04-11 17:23:34 +00002496 }
2497
Vishnu Nair062a8672021-09-03 16:07:44 -07002498 // Drop touch events if requested by input feature
2499 if (newTouchedWindowHandle != nullptr &&
2500 shouldDropInput(entry, newTouchedWindowHandle)) {
2501 newTouchedWindowHandle = nullptr;
2502 }
2503
Siarhei Vishniakouafa08cc2023-05-08 22:35:50 -07002504 if (newTouchedWindowHandle != nullptr &&
2505 !haveSameToken(oldTouchedWindowHandle, newTouchedWindowHandle)) {
Siarhei Vishniakou0f6558d2023-04-21 12:05:13 -07002506 ALOGD("Touch is slipping out of window %s into window %s in display %" PRId32,
2507 oldTouchedWindowHandle->getName().c_str(),
2508 newTouchedWindowHandle->getName().c_str(), displayId);
2509
Michael Wrightd02c5b62014-02-10 15:10:22 -08002510 // Make a slippery exit from the old window.
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08002511 std::bitset<MAX_POINTER_ID + 1> pointerIds;
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002512 const int32_t pointerId = entry.pointerProperties[0].id;
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08002513 pointerIds.set(pointerId);
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002514
2515 const TouchedWindow& touchedWindow =
2516 tempTouchState.getTouchedWindow(oldTouchedWindowHandle);
2517 addWindowTargetLocked(oldTouchedWindowHandle,
2518 InputTarget::Flags::DISPATCH_AS_SLIPPERY_EXIT, pointerIds,
2519 touchedWindow.firstDownTimeInTarget, targets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002520
2521 // Make a slippery entrance into the new window.
2522 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
Prabir Pradhan713bb3e2021-12-20 02:07:40 -08002523 isSplit = !isFromMouse;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002524 }
2525
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002526 ftl::Flags<InputTarget::Flags> targetFlags =
2527 InputTarget::Flags::DISPATCH_AS_SLIPPERY_ENTER;
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002528 if (canReceiveForegroundTouches(*newTouchedWindowHandle->getInfo())) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002529 targetFlags |= InputTarget::Flags::FOREGROUND;
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002530 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002531 if (isSplit) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002532 targetFlags |= InputTarget::Flags::SPLIT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002533 }
2534 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002535 targetFlags |= InputTarget::Flags::WINDOW_IS_OBSCURED;
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002536 } else if (isWindowObscuredLocked(newTouchedWindowHandle)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002537 targetFlags |= InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002538 }
2539
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002540 tempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds,
2541 entry.eventTime);
Arthur Hungc539dbb2022-12-08 07:45:36 +00002542
2543 // Check if the wallpaper window should deliver the corresponding event.
2544 slipWallpaperTouch(targetFlags, oldTouchedWindowHandle, newTouchedWindowHandle,
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002545 tempTouchState, pointerId, targets);
2546 tempTouchState.removeTouchedPointerFromWindow(pointerId, oldTouchedWindowHandle);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002547 }
2548 }
Arthur Hung96483742022-11-15 03:30:48 +00002549
2550 // Update the pointerIds for non-splittable when it received pointer down.
2551 if (!isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN) {
2552 // If no split, we suppose all touched windows should receive pointer down.
2553 const int32_t pointerIndex = getMotionEventActionPointerIndex(action);
2554 for (size_t i = 0; i < tempTouchState.windows.size(); i++) {
2555 TouchedWindow& touchedWindow = tempTouchState.windows[i];
2556 // Ignore drag window for it should just track one pointer.
2557 if (mDragState && mDragState->dragWindow == touchedWindow.windowHandle) {
2558 continue;
2559 }
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08002560 touchedWindow.pointerIds.set(entry.pointerProperties[pointerIndex].id);
Arthur Hung96483742022-11-15 03:30:48 +00002561 }
2562 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002563 }
2564
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002565 // Update dispatching for hover enter and exit.
Sam Dubeyf886dec2023-01-27 13:28:19 +00002566 {
2567 std::vector<TouchedWindow> hoveringWindows =
2568 getHoveringWindowsLocked(oldState, tempTouchState, entry);
2569 for (const TouchedWindow& touchedWindow : hoveringWindows) {
Siarhei Vishniakoud5876ba2023-05-15 17:58:34 -07002570 std::optional<InputTarget> target =
2571 createInputTargetLocked(touchedWindow.windowHandle, touchedWindow.targetFlags,
2572 touchedWindow.firstDownTimeInTarget);
2573 if (!target) {
2574 continue;
2575 }
2576 // Hardcode to single hovering pointer for now.
2577 std::bitset<MAX_POINTER_ID + 1> pointerIds;
2578 pointerIds.set(entry.pointerProperties[0].id);
2579 target->addPointers(pointerIds, touchedWindow.windowHandle->getInfo()->transform);
2580 targets.push_back(*target);
Sam Dubeyf886dec2023-01-27 13:28:19 +00002581 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002582 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002583
Prabir Pradhan5735a322022-04-11 17:23:34 +00002584 // Ensure that all touched windows are valid for injection.
2585 if (entry.injectionState != nullptr) {
2586 std::string errs;
2587 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Prabir Pradhan5735a322022-04-11 17:23:34 +00002588 const auto err = verifyTargetedInjection(touchedWindow.windowHandle, entry);
2589 if (err) errs += "\n - " + *err;
2590 }
2591 if (!errs.empty()) {
2592 ALOGW("Dropping targeted injection: At least one touched window is not owned by uid "
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00002593 "%s:%s",
2594 entry.injectionState->targetUid->toString().c_str(), errs.c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002595 outInjectionResult = InputEventInjectionResult::TARGET_MISMATCH;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002596 return {};
Prabir Pradhan5735a322022-04-11 17:23:34 +00002597 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002598 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002599
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002600 // Check whether windows listening for outside touches are owned by the same UID. If the owner
2601 // has a different UID, then we will not reveal coordinate information to this window.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002602 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
chaviw98318de2021-05-19 16:45:23 -05002603 sp<WindowInfoHandle> foregroundWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002604 tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002605 if (foregroundWindowHandle) {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00002606 const auto foregroundWindowUid = foregroundWindowHandle->getInfo()->ownerUid;
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002607 for (InputTarget& target : targets) {
2608 if (target.flags.test(InputTarget::Flags::DISPATCH_AS_OUTSIDE)) {
2609 sp<WindowInfoHandle> targetWindow =
2610 getWindowHandleLocked(target.inputChannel->getConnectionToken());
2611 if (targetWindow->getInfo()->ownerUid != foregroundWindowUid) {
2612 target.flags |= InputTarget::Flags::ZERO_COORDS;
Michael Wright3dd60e22019-03-27 22:06:44 +00002613 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002614 }
2615 }
2616 }
2617 }
2618
Harry Cuttsb166c002023-05-09 13:06:05 +00002619 // If this is a touchpad navigation gesture, it needs to only be sent to trusted targets, as we
2620 // only want the system UI to handle these gestures.
2621 const bool isTouchpadNavGesture = isFromSource(entry.source, AINPUT_SOURCE_MOUSE) &&
2622 entry.classification == MotionClassification::MULTI_FINGER_SWIPE;
2623 if (isTouchpadNavGesture) {
2624 filterUntrustedTargets(/* byref */ tempTouchState, /* byref */ targets);
2625 }
2626
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07002627 // Output targets from the touch state.
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002628 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08002629 if (touchedWindow.pointerIds.none() && !touchedWindow.hasHoveringPointers(entry.deviceId)) {
Siarhei Vishniakoue0431e42023-01-28 17:01:39 -08002630 // Windows with hovering pointers are getting persisted inside TouchState.
2631 // Do not send this event to those windows.
2632 continue;
2633 }
Harry Cuttsb166c002023-05-09 13:06:05 +00002634
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002635 addWindowTargetLocked(touchedWindow.windowHandle, touchedWindow.targetFlags,
2636 touchedWindow.pointerIds, touchedWindow.firstDownTimeInTarget,
2637 targets);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002638 }
Sam Dubey39d37cf2022-12-07 18:05:35 +00002639
Siarhei Vishniakou580fb3a2023-05-05 15:02:20 -07002640 // During targeted injection, only allow owned targets to receive events
2641 std::erase_if(targets, [&](const InputTarget& target) {
2642 LOG_ALWAYS_FATAL_IF(target.windowHandle == nullptr);
2643 const auto err = verifyTargetedInjection(target.windowHandle, entry);
2644 if (err) {
2645 LOG(WARNING) << "Dropping injected event from " << target.windowHandle->getName()
2646 << ": " << (*err);
2647 return true;
2648 }
2649 return false;
2650 });
2651
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07002652 if (targets.empty()) {
2653 LOG(INFO) << "Dropping event because no targets were found: " << entry.getDescription();
2654 outInjectionResult = InputEventInjectionResult::FAILED;
2655 return {};
2656 }
2657
2658 // If we only have windows getting ACTION_OUTSIDE, then drop the event, because there is no
2659 // window that is actually receiving the entire gesture.
2660 if (std::all_of(targets.begin(), targets.end(), [](const InputTarget& target) {
2661 return target.flags.test(InputTarget::Flags::DISPATCH_AS_OUTSIDE);
2662 })) {
2663 LOG(INFO) << "Dropping event because all windows would just receive ACTION_OUTSIDE: "
2664 << entry.getDescription();
2665 outInjectionResult = InputEventInjectionResult::FAILED;
2666 return {};
2667 }
2668
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002669 outInjectionResult = InputEventInjectionResult::SUCCEEDED;
Sam Dubeyf886dec2023-01-27 13:28:19 +00002670 // Drop the outside or hover touch windows since we will not care about them
2671 // in the next iteration.
2672 tempTouchState.filterNonAsIsTouchWindows();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002673
Michael Wrightd02c5b62014-02-10 15:10:22 -08002674 // Update final pieces of touch state if the injector had permission.
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002675 if (switchedDevice) {
2676 if (DEBUG_FOCUS) {
2677 ALOGD("Conflicting pointer actions: Switched to a different device.");
2678 }
2679 *outConflictingPointerActions = true;
2680 }
2681
2682 if (isHoverAction) {
2683 // Started hovering, therefore no longer down.
Siarhei Vishniakou3ad385b2022-11-04 10:09:53 -07002684 if (oldState && oldState->isDown()) {
Siarhei Vishniakou6e1e9872022-11-08 17:51:35 -08002685 ALOGD_IF(DEBUG_FOCUS,
2686 "Conflicting pointer actions: Hover received while pointer was down.");
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002687 *outConflictingPointerActions = true;
2688 }
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002689 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2690 maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE) {
2691 tempTouchState.deviceId = entry.deviceId;
2692 tempTouchState.source = entry.source;
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002693 }
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002694 } else if (maskedAction == AMOTION_EVENT_ACTION_UP) {
2695 // Pointer went up.
2696 tempTouchState.removeTouchedPointer(entry.pointerProperties[0].id);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002697 } else if (maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002698 // All pointers up or canceled.
2699 tempTouchState.reset();
2700 } else if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
2701 // First pointer went down.
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002702 if (oldState && (oldState->isDown() || oldState->hasHoveringPointers())) {
2703 ALOGD("Conflicting pointer actions: Down received while already down or hovering.");
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002704 *outConflictingPointerActions = true;
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002705 }
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002706 } else if (maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
2707 // One pointer went up.
2708 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
2709 uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002710
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002711 for (size_t i = 0; i < tempTouchState.windows.size();) {
2712 TouchedWindow& touchedWindow = tempTouchState.windows[i];
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08002713 touchedWindow.pointerIds.reset(pointerId);
2714 if (touchedWindow.pointerIds.none()) {
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002715 tempTouchState.windows.erase(tempTouchState.windows.begin() + i);
2716 continue;
2717 }
2718 i += 1;
2719 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002720 }
2721
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002722 // Save changes unless the action was scroll in which case the temporary touch
2723 // state was only valid for this one action.
2724 if (maskedAction != AMOTION_EVENT_ACTION_SCROLL) {
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07002725 if (displayId >= 0) {
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002726 tempTouchState.clearWindowsWithoutPointers();
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002727 mTouchStatesByDisplay[displayId] = tempTouchState;
2728 } else {
2729 mTouchStatesByDisplay.erase(displayId);
2730 }
2731 }
2732
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -08002733 if (tempTouchState.windows.empty()) {
2734 mTouchStatesByDisplay.erase(displayId);
2735 }
2736
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002737 return targets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002738}
2739
arthurhung6d4bed92021-03-17 11:59:33 +08002740void InputDispatcher::finishDragAndDrop(int32_t displayId, float x, float y) {
Prabir Pradhand65552b2021-10-07 11:23:50 -07002741 // Prevent stylus interceptor windows from affecting drag and drop behavior for now, until we
2742 // have an explicit reason to support it.
2743 constexpr bool isStylus = false;
2744
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002745 auto [dropWindow, _] =
Harry Cutts33476232023-01-30 19:57:29 +00002746 findTouchedWindowAtLocked(displayId, x, y, isStylus, /*ignoreDragWindow=*/true);
arthurhung6d4bed92021-03-17 11:59:33 +08002747 if (dropWindow) {
2748 vec2 local = dropWindow->getInfo()->transform.transform(x, y);
Prabir Pradhancef936d2021-07-21 16:17:52 +00002749 sendDropWindowCommandLocked(dropWindow->getToken(), local.x, local.y);
Arthur Hung6d0571e2021-04-09 20:18:16 +08002750 } else {
Arthur Hung54745652022-04-20 07:17:41 +00002751 ALOGW("No window found when drop.");
Prabir Pradhancef936d2021-07-21 16:17:52 +00002752 sendDropWindowCommandLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08002753 }
2754 mDragState.reset();
2755}
2756
2757void InputDispatcher::addDragEventLocked(const MotionEntry& entry) {
Arthur Hung3915c1f2022-05-31 07:17:17 +00002758 if (!mDragState || mDragState->dragWindow->getInfo()->displayId != entry.displayId) {
arthurhungb89ccb02020-12-30 16:19:01 +08002759 return;
2760 }
2761
arthurhung6d4bed92021-03-17 11:59:33 +08002762 if (!mDragState->isStartDrag) {
2763 mDragState->isStartDrag = true;
2764 mDragState->isStylusButtonDownAtStart =
2765 (entry.buttonState & AMOTION_EVENT_BUTTON_STYLUS_PRIMARY) != 0;
2766 }
2767
Arthur Hung54745652022-04-20 07:17:41 +00002768 // Find the pointer index by id.
2769 int32_t pointerIndex = 0;
2770 for (; static_cast<uint32_t>(pointerIndex) < entry.pointerCount; pointerIndex++) {
2771 const PointerProperties& pointerProperties = entry.pointerProperties[pointerIndex];
2772 if (pointerProperties.id == mDragState->pointerId) {
2773 break;
arthurhung6d4bed92021-03-17 11:59:33 +08002774 }
Arthur Hung54745652022-04-20 07:17:41 +00002775 }
arthurhung6d4bed92021-03-17 11:59:33 +08002776
Arthur Hung54745652022-04-20 07:17:41 +00002777 if (uint32_t(pointerIndex) == entry.pointerCount) {
2778 LOG_ALWAYS_FATAL("Should find a valid pointer index by id %d", mDragState->pointerId);
Arthur Hung54745652022-04-20 07:17:41 +00002779 }
2780
2781 const int32_t maskedAction = entry.action & AMOTION_EVENT_ACTION_MASK;
2782 const int32_t x = entry.pointerCoords[pointerIndex].getX();
2783 const int32_t y = entry.pointerCoords[pointerIndex].getY();
2784
2785 switch (maskedAction) {
2786 case AMOTION_EVENT_ACTION_MOVE: {
2787 // Handle the special case : stylus button no longer pressed.
2788 bool isStylusButtonDown =
2789 (entry.buttonState & AMOTION_EVENT_BUTTON_STYLUS_PRIMARY) != 0;
2790 if (mDragState->isStylusButtonDownAtStart && !isStylusButtonDown) {
2791 finishDragAndDrop(entry.displayId, x, y);
2792 return;
2793 }
2794
2795 // Prevent stylus interceptor windows from affecting drag and drop behavior for now,
2796 // until we have an explicit reason to support it.
2797 constexpr bool isStylus = false;
2798
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002799 auto [hoverWindowHandle, _] = findTouchedWindowAtLocked(entry.displayId, x, y, isStylus,
Harry Cutts33476232023-01-30 19:57:29 +00002800 /*ignoreDragWindow=*/true);
Arthur Hung54745652022-04-20 07:17:41 +00002801 // enqueue drag exit if needed.
2802 if (hoverWindowHandle != mDragState->dragHoverWindowHandle &&
2803 !haveSameToken(hoverWindowHandle, mDragState->dragHoverWindowHandle)) {
2804 if (mDragState->dragHoverWindowHandle != nullptr) {
Harry Cutts33476232023-01-30 19:57:29 +00002805 enqueueDragEventLocked(mDragState->dragHoverWindowHandle, /*isExiting=*/true, x,
Arthur Hung54745652022-04-20 07:17:41 +00002806 y);
2807 }
2808 mDragState->dragHoverWindowHandle = hoverWindowHandle;
2809 }
2810 // enqueue drag location if needed.
2811 if (hoverWindowHandle != nullptr) {
Harry Cutts33476232023-01-30 19:57:29 +00002812 enqueueDragEventLocked(hoverWindowHandle, /*isExiting=*/false, x, y);
Arthur Hung54745652022-04-20 07:17:41 +00002813 }
2814 break;
2815 }
2816
2817 case AMOTION_EVENT_ACTION_POINTER_UP:
2818 if (getMotionEventActionPointerIndex(entry.action) != pointerIndex) {
2819 break;
2820 }
2821 // The drag pointer is up.
2822 [[fallthrough]];
2823 case AMOTION_EVENT_ACTION_UP:
2824 finishDragAndDrop(entry.displayId, x, y);
2825 break;
2826 case AMOTION_EVENT_ACTION_CANCEL: {
2827 ALOGD("Receiving cancel when drag and drop.");
2828 sendDropWindowCommandLocked(nullptr, 0, 0);
2829 mDragState.reset();
2830 break;
2831 }
arthurhungb89ccb02020-12-30 16:19:01 +08002832 }
2833}
2834
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002835std::optional<InputTarget> InputDispatcher::createInputTargetLocked(
2836 const sp<android::gui::WindowInfoHandle>& windowHandle,
2837 ftl::Flags<InputTarget::Flags> targetFlags,
2838 std::optional<nsecs_t> firstDownTimeInTarget) const {
2839 std::shared_ptr<InputChannel> inputChannel = getInputChannelLocked(windowHandle->getToken());
2840 if (inputChannel == nullptr) {
2841 ALOGW("Not creating InputTarget for %s, no input channel", windowHandle->getName().c_str());
2842 return {};
2843 }
2844 InputTarget inputTarget;
2845 inputTarget.inputChannel = inputChannel;
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00002846 inputTarget.windowHandle = windowHandle;
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002847 inputTarget.flags = targetFlags;
2848 inputTarget.globalScaleFactor = windowHandle->getInfo()->globalScaleFactor;
2849 inputTarget.firstDownTimeInTarget = firstDownTimeInTarget;
2850 const auto& displayInfoIt = mDisplayInfos.find(windowHandle->getInfo()->displayId);
2851 if (displayInfoIt != mDisplayInfos.end()) {
2852 inputTarget.displayTransform = displayInfoIt->second.transform;
2853 } else {
Siarhei Vishniakou580fb3a2023-05-05 15:02:20 -07002854 // DisplayInfo not found for this window on display windowHandle->getInfo()->displayId.
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002855 // TODO(b/198444055): Make this an error message after 'setInputWindows' API is removed.
2856 }
2857 return inputTarget;
2858}
2859
chaviw98318de2021-05-19 16:45:23 -05002860void InputDispatcher::addWindowTargetLocked(const sp<WindowInfoHandle>& windowHandle,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002861 ftl::Flags<InputTarget::Flags> targetFlags,
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08002862 std::bitset<MAX_POINTER_ID + 1> pointerIds,
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002863 std::optional<nsecs_t> firstDownTimeInTarget,
Siarhei Vishniakouf75cddb2022-10-25 10:42:16 -07002864 std::vector<InputTarget>& inputTargets) const {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002865 std::vector<InputTarget>::iterator it =
2866 std::find_if(inputTargets.begin(), inputTargets.end(),
2867 [&windowHandle](const InputTarget& inputTarget) {
2868 return inputTarget.inputChannel->getConnectionToken() ==
2869 windowHandle->getToken();
2870 });
Chavi Weingarten97b8eec2020-01-09 18:09:08 +00002871
chaviw98318de2021-05-19 16:45:23 -05002872 const WindowInfo* windowInfo = windowHandle->getInfo();
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002873
2874 if (it == inputTargets.end()) {
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002875 std::optional<InputTarget> target =
2876 createInputTargetLocked(windowHandle, targetFlags, firstDownTimeInTarget);
2877 if (!target) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002878 return;
2879 }
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002880 inputTargets.push_back(*target);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002881 it = inputTargets.end() - 1;
2882 }
2883
2884 ALOG_ASSERT(it->flags == targetFlags);
2885 ALOG_ASSERT(it->globalScaleFactor == windowInfo->globalScaleFactor);
2886
chaviw1ff3d1e2020-07-01 15:53:47 -07002887 it->addPointers(pointerIds, windowInfo->transform);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002888}
2889
Michael Wright3dd60e22019-03-27 22:06:44 +00002890void InputDispatcher::addGlobalMonitoringTargetsLocked(std::vector<InputTarget>& inputTargets,
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002891 int32_t displayId) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002892 auto monitorsIt = mGlobalMonitorsByDisplay.find(displayId);
2893 if (monitorsIt == mGlobalMonitorsByDisplay.end()) return;
Michael Wright3dd60e22019-03-27 22:06:44 +00002894
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002895 for (const Monitor& monitor : selectResponsiveMonitorsLocked(monitorsIt->second)) {
2896 InputTarget target;
2897 target.inputChannel = monitor.inputChannel;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002898 target.flags = InputTarget::Flags::DISPATCH_AS_IS;
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002899 // target.firstDownTimeInTarget is not set for global monitors. It is only required in split
2900 // touch and global monitoring works as intended even without setting firstDownTimeInTarget
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002901 if (const auto& it = mDisplayInfos.find(displayId); it != mDisplayInfos.end()) {
2902 target.displayTransform = it->second.transform;
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002903 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002904 target.setDefaultPointerTransform(target.displayTransform);
2905 inputTargets.push_back(target);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002906 }
2907}
2908
Robert Carrc9bf1d32020-04-13 17:21:08 -07002909/**
2910 * Indicate whether one window handle should be considered as obscuring
2911 * another window handle. We only check a few preconditions. Actually
2912 * checking the bounds is left to the caller.
2913 */
chaviw98318de2021-05-19 16:45:23 -05002914static bool canBeObscuredBy(const sp<WindowInfoHandle>& windowHandle,
2915 const sp<WindowInfoHandle>& otherHandle) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002916 // Compare by token so cloned layers aren't counted
2917 if (haveSameToken(windowHandle, otherHandle)) {
2918 return false;
2919 }
2920 auto info = windowHandle->getInfo();
2921 auto otherInfo = otherHandle->getInfo();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002922 if (otherInfo->inputConfig.test(WindowInfo::InputConfig::NOT_VISIBLE)) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002923 return false;
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002924 } else if (otherInfo->alpha == 0 &&
2925 otherInfo->inputConfig.test(WindowInfo::InputConfig::NOT_TOUCHABLE)) {
Bernardo Rufino653d2e02020-10-20 17:32:40 +00002926 // Those act as if they were invisible, so we don't need to flag them.
2927 // We do want to potentially flag touchable windows even if they have 0
2928 // opacity, since they can consume touches and alter the effects of the
2929 // user interaction (eg. apps that rely on
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002930 // Flags::WINDOW_IS_PARTIALLY_OBSCURED should still be told about those
Bernardo Rufino653d2e02020-10-20 17:32:40 +00002931 // windows), hence we also check for FLAG_NOT_TOUCHABLE.
2932 return false;
Bernardo Rufino8007daf2020-09-22 09:40:01 +00002933 } else if (info->ownerUid == otherInfo->ownerUid) {
2934 // If ownerUid is the same we don't generate occlusion events as there
2935 // is no security boundary within an uid.
Robert Carrc9bf1d32020-04-13 17:21:08 -07002936 return false;
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002937 } else if (otherInfo->inputConfig.test(gui::WindowInfo::InputConfig::TRUSTED_OVERLAY)) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002938 return false;
2939 } else if (otherInfo->displayId != info->displayId) {
2940 return false;
2941 }
2942 return true;
2943}
2944
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002945/**
2946 * Returns touch occlusion information in the form of TouchOcclusionInfo. To check if the touch is
2947 * untrusted, one should check:
2948 *
2949 * 1. If result.hasBlockingOcclusion is true.
2950 * If it's, it means the touch should be blocked due to a window with occlusion mode of
2951 * BLOCK_UNTRUSTED.
2952 *
2953 * 2. If result.obscuringOpacity > mMaximumObscuringOpacityForTouch.
2954 * If it is (and 1 is false), then the touch should be blocked because a stack of windows
2955 * (possibly only one) with occlusion mode of USE_OPACITY from one UID resulted in a composed
2956 * obscuring opacity above the threshold. Note that if there was no window of occlusion mode
2957 * USE_OPACITY, result.obscuringOpacity would've been 0 and since
2958 * mMaximumObscuringOpacityForTouch >= 0, the condition above would never be true.
2959 *
2960 * If neither of those is true, then it means the touch can be allowed.
2961 */
2962InputDispatcher::TouchOcclusionInfo InputDispatcher::computeTouchOcclusionInfoLocked(
chaviw98318de2021-05-19 16:45:23 -05002963 const sp<WindowInfoHandle>& windowHandle, int32_t x, int32_t y) const {
2964 const WindowInfo* windowInfo = windowHandle->getInfo();
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002965 int32_t displayId = windowInfo->displayId;
chaviw98318de2021-05-19 16:45:23 -05002966 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002967 TouchOcclusionInfo info;
2968 info.hasBlockingOcclusion = false;
2969 info.obscuringOpacity = 0;
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00002970 info.obscuringUid = gui::Uid::INVALID;
2971 std::map<gui::Uid, float> opacityByUid;
chaviw98318de2021-05-19 16:45:23 -05002972 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002973 if (windowHandle == otherHandle) {
2974 break; // All future windows are below us. Exit early.
2975 }
chaviw98318de2021-05-19 16:45:23 -05002976 const WindowInfo* otherInfo = otherHandle->getInfo();
Bernardo Rufino1ff9d592021-01-18 16:58:57 +00002977 if (canBeObscuredBy(windowHandle, otherHandle) && otherInfo->frameContainsPoint(x, y) &&
2978 !haveSameApplicationToken(windowInfo, otherInfo)) {
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002979 if (DEBUG_TOUCH_OCCLUSION) {
2980 info.debugInfo.push_back(
2981 dumpWindowForTouchOcclusion(otherInfo, /* isTouchedWindow */ false));
2982 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002983 // canBeObscuredBy() has returned true above, which means this window is untrusted, so
2984 // we perform the checks below to see if the touch can be propagated or not based on the
2985 // window's touch occlusion mode
2986 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::BLOCK_UNTRUSTED) {
2987 info.hasBlockingOcclusion = true;
2988 info.obscuringUid = otherInfo->ownerUid;
2989 info.obscuringPackage = otherInfo->packageName;
2990 break;
2991 }
2992 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::USE_OPACITY) {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00002993 const auto uid = otherInfo->ownerUid;
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002994 float opacity =
2995 (opacityByUid.find(uid) == opacityByUid.end()) ? 0 : opacityByUid[uid];
2996 // Given windows A and B:
2997 // opacity(A, B) = 1 - [1 - opacity(A)] * [1 - opacity(B)]
2998 opacity = 1 - (1 - opacity) * (1 - otherInfo->alpha);
2999 opacityByUid[uid] = opacity;
3000 if (opacity > info.obscuringOpacity) {
3001 info.obscuringOpacity = opacity;
3002 info.obscuringUid = uid;
3003 info.obscuringPackage = otherInfo->packageName;
3004 }
3005 }
3006 }
3007 }
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00003008 if (DEBUG_TOUCH_OCCLUSION) {
3009 info.debugInfo.push_back(
3010 dumpWindowForTouchOcclusion(windowInfo, /* isTouchedWindow */ true));
3011 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003012 return info;
3013}
3014
chaviw98318de2021-05-19 16:45:23 -05003015std::string InputDispatcher::dumpWindowForTouchOcclusion(const WindowInfo* info,
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00003016 bool isTouchedWindow) const {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003017 return StringPrintf(INDENT2 "* %spackage=%s/%s, id=%" PRId32 ", mode=%s, alpha=%.2f, "
Prabir Pradhan51e7db02022-02-07 06:02:57 -08003018 "frame=[%" PRId32 ",%" PRId32 "][%" PRId32 ",%" PRId32
3019 "], touchableRegion=%s, window={%s}, inputConfig={%s}, "
3020 "hasToken=%s, applicationInfo.name=%s, applicationInfo.token=%s\n",
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08003021 isTouchedWindow ? "[TOUCHED] " : "", info->packageName.c_str(),
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003022 info->ownerUid.toString().c_str(), info->id,
3023 toString(info->touchOcclusionMode).c_str(), info->alpha, info->frameLeft,
3024 info->frameTop, info->frameRight, info->frameBottom,
3025 dumpRegion(info->touchableRegion).c_str(), info->name.c_str(),
3026 info->inputConfig.string().c_str(), toString(info->token != nullptr),
3027 info->applicationInfo.name.c_str(),
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07003028 binderToString(info->applicationInfo.token).c_str());
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00003029}
3030
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003031bool InputDispatcher::isTouchTrustedLocked(const TouchOcclusionInfo& occlusionInfo) const {
3032 if (occlusionInfo.hasBlockingOcclusion) {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003033 ALOGW("Untrusted touch due to occlusion by %s/%s", occlusionInfo.obscuringPackage.c_str(),
3034 occlusionInfo.obscuringUid.toString().c_str());
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003035 return false;
3036 }
3037 if (occlusionInfo.obscuringOpacity > mMaximumObscuringOpacityForTouch) {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003038 ALOGW("Untrusted touch due to occlusion by %s/%s (obscuring opacity = "
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003039 "%.2f, maximum allowed = %.2f)",
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003040 occlusionInfo.obscuringPackage.c_str(), occlusionInfo.obscuringUid.toString().c_str(),
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003041 occlusionInfo.obscuringOpacity, mMaximumObscuringOpacityForTouch);
3042 return false;
3043 }
3044 return true;
3045}
3046
chaviw98318de2021-05-19 16:45:23 -05003047bool InputDispatcher::isWindowObscuredAtPointLocked(const sp<WindowInfoHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003048 int32_t x, int32_t y) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003049 int32_t displayId = windowHandle->getInfo()->displayId;
chaviw98318de2021-05-19 16:45:23 -05003050 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
3051 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07003052 if (windowHandle == otherHandle) {
3053 break; // All future windows are below us. Exit early.
Michael Wrightd02c5b62014-02-10 15:10:22 -08003054 }
chaviw98318de2021-05-19 16:45:23 -05003055 const WindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07003056 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08003057 otherInfo->frameContainsPoint(x, y)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003058 return true;
3059 }
3060 }
3061 return false;
3062}
3063
chaviw98318de2021-05-19 16:45:23 -05003064bool InputDispatcher::isWindowObscuredLocked(const sp<WindowInfoHandle>& windowHandle) const {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07003065 int32_t displayId = windowHandle->getInfo()->displayId;
chaviw98318de2021-05-19 16:45:23 -05003066 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
3067 const WindowInfo* windowInfo = windowHandle->getInfo();
3068 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07003069 if (windowHandle == otherHandle) {
3070 break; // All future windows are below us. Exit early.
Michael Wrightcdcd8f22016-03-22 16:52:13 -07003071 }
chaviw98318de2021-05-19 16:45:23 -05003072 const WindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07003073 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08003074 otherInfo->overlaps(windowInfo)) {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07003075 return true;
3076 }
3077 }
3078 return false;
3079}
3080
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08003081std::string InputDispatcher::getApplicationWindowLabel(
chaviw98318de2021-05-19 16:45:23 -05003082 const InputApplicationHandle* applicationHandle, const sp<WindowInfoHandle>& windowHandle) {
Yi Kong9b14ac62018-07-17 13:48:38 -07003083 if (applicationHandle != nullptr) {
3084 if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07003085 return applicationHandle->getName() + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003086 } else {
3087 return applicationHandle->getName();
3088 }
Yi Kong9b14ac62018-07-17 13:48:38 -07003089 } else if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07003090 return windowHandle->getInfo()->applicationInfo.name + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003091 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003092 return "<unknown application or window>";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003093 }
3094}
3095
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003096void InputDispatcher::pokeUserActivityLocked(const EventEntry& eventEntry) {
Antonio Kantekf16f2832021-09-28 04:39:20 +00003097 if (!isUserActivityEvent(eventEntry)) {
3098 // Not poking user activity if the event type does not represent a user activity
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003099 return;
3100 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003101 int32_t displayId = getTargetDisplayId(eventEntry);
chaviw98318de2021-05-19 16:45:23 -05003102 sp<WindowInfoHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Josep del Riob3981622023-04-18 15:49:45 +00003103 const WindowInfo* windowDisablingUserActivityInfo = nullptr;
Tiger Huang721e26f2018-07-24 22:26:19 +08003104 if (focusedWindowHandle != nullptr) {
chaviw98318de2021-05-19 16:45:23 -05003105 const WindowInfo* info = focusedWindowHandle->getInfo();
Prabir Pradhan51e7db02022-02-07 06:02:57 -08003106 if (info->inputConfig.test(WindowInfo::InputConfig::DISABLE_USER_ACTIVITY)) {
Josep del Riob3981622023-04-18 15:49:45 +00003107 windowDisablingUserActivityInfo = info;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003108 }
3109 }
3110
3111 int32_t eventType = USER_ACTIVITY_EVENT_OTHER;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003112 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003113 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003114 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
3115 if (motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003116 return;
3117 }
Josep del Riob3981622023-04-18 15:49:45 +00003118 if (windowDisablingUserActivityInfo != nullptr) {
3119 if (DEBUG_DISPATCH_CYCLE) {
3120 ALOGD("Not poking user activity: disabled by window '%s'.",
3121 windowDisablingUserActivityInfo->name.c_str());
3122 }
3123 return;
3124 }
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003125 if (MotionEvent::isTouchEvent(motionEntry.source, motionEntry.action)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003126 eventType = USER_ACTIVITY_EVENT_TOUCH;
3127 }
3128 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003129 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003130 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003131 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
3132 if (keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003133 return;
3134 }
Josep del Riob3981622023-04-18 15:49:45 +00003135 // If the key code is unknown, we don't consider it user activity
3136 if (keyEntry.keyCode == AKEYCODE_UNKNOWN) {
3137 return;
3138 }
3139 // Don't inhibit events that were intercepted or are not passed to
3140 // the apps, like system shortcuts
3141 if (windowDisablingUserActivityInfo != nullptr &&
3142 keyEntry.interceptKeyResult != KeyEntry::InterceptKeyResult::SKIP &&
3143 keyEntry.policyFlags & POLICY_FLAG_PASS_TO_USER) {
3144 if (DEBUG_DISPATCH_CYCLE) {
3145 ALOGD("Not poking user activity: disabled by window '%s'.",
3146 windowDisablingUserActivityInfo->name.c_str());
3147 }
3148 return;
3149 }
3150
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003151 eventType = USER_ACTIVITY_EVENT_BUTTON;
3152 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003153 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00003154 default: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003155 LOG_ALWAYS_FATAL("%s events are not user activity",
Dominik Laskowski75788452021-02-09 18:51:25 -08003156 ftl::enum_string(eventEntry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003157 break;
3158 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003159 }
3160
Prabir Pradhancef936d2021-07-21 16:17:52 +00003161 auto command = [this, eventTime = eventEntry.eventTime, eventType, displayId]()
3162 REQUIRES(mLock) {
3163 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00003164 mPolicy.pokeUserActivity(eventTime, eventType, displayId);
Prabir Pradhancef936d2021-07-21 16:17:52 +00003165 };
3166 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003167}
3168
3169void InputDispatcher::prepareDispatchCycleLocked(nsecs_t currentTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003170 const std::shared_ptr<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003171 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003172 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003173 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003174 std::string message =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003175 StringPrintf("prepareDispatchCycleLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003176 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00003177 ATRACE_NAME(message.c_str());
3178 }
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003179 if (DEBUG_DISPATCH_CYCLE) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003180 ALOGD("channel '%s' ~ prepareDispatchCycle - flags=%s, "
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08003181 "globalScaleFactor=%f, pointerIds=%s %s",
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003182 connection->getInputChannelName().c_str(), inputTarget.flags.string().c_str(),
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08003183 inputTarget.globalScaleFactor, bitsetToString(inputTarget.pointerIds).c_str(),
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003184 inputTarget.getPointerInfoString().c_str());
3185 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003186
3187 // Skip this event if the connection status is not normal.
3188 // We don't want to enqueue additional outbound events if the connection is broken.
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003189 if (connection->status != Connection::Status::NORMAL) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003190 if (DEBUG_DISPATCH_CYCLE) {
3191 ALOGD("channel '%s' ~ Dropping event because the channel status is %s",
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003192 connection->getInputChannelName().c_str(),
3193 ftl::enum_string(connection->status).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003194 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003195 return;
3196 }
3197
3198 // Split a motion event if needed.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003199 if (inputTarget.flags.test(InputTarget::Flags::SPLIT)) {
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003200 LOG_ALWAYS_FATAL_IF(eventEntry->type != EventEntry::Type::MOTION,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003201 "Entry type %s should not have Flags::SPLIT",
Dominik Laskowski75788452021-02-09 18:51:25 -08003202 ftl::enum_string(eventEntry->type).c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003203
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003204 const MotionEntry& originalMotionEntry = static_cast<const MotionEntry&>(*eventEntry);
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003205 if (inputTarget.pointerIds.count() != originalMotionEntry.pointerCount) {
Siarhei Vishniakou16e4fa02023-02-16 17:48:56 -08003206 if (!inputTarget.firstDownTimeInTarget.has_value()) {
3207 logDispatchStateLocked();
3208 LOG(FATAL) << "Splitting motion events requires a down time to be set for the "
3209 "target on connection "
3210 << connection->getInputChannelName() << " for "
3211 << originalMotionEntry.getDescription();
3212 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003213 std::unique_ptr<MotionEntry> splitMotionEntry =
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00003214 splitMotionEvent(originalMotionEntry, inputTarget.pointerIds,
3215 inputTarget.firstDownTimeInTarget.value());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003216 if (!splitMotionEntry) {
3217 return; // split event was dropped
3218 }
Arthur Hungb3307ee2021-10-14 10:57:37 +00003219 if (splitMotionEntry->action == AMOTION_EVENT_ACTION_CANCEL) {
3220 std::string reason = std::string("reason=pointer cancel on split window");
3221 android_log_event_list(LOGTAG_INPUT_CANCEL)
3222 << connection->getInputChannelName().c_str() << reason << LOG_ID_EVENTS;
3223 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003224 if (DEBUG_FOCUS) {
3225 ALOGD("channel '%s' ~ Split motion event.",
3226 connection->getInputChannelName().c_str());
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003227 logOutboundMotionDetails(" ", *splitMotionEntry);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003228 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003229 enqueueDispatchEntriesLocked(currentTime, connection, std::move(splitMotionEntry),
3230 inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003231 return;
3232 }
3233 }
3234
3235 // Not splitting. Enqueue dispatch entries for the event as is.
3236 enqueueDispatchEntriesLocked(currentTime, connection, eventEntry, inputTarget);
3237}
3238
3239void InputDispatcher::enqueueDispatchEntriesLocked(nsecs_t currentTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003240 const std::shared_ptr<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003241 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003242 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003243 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003244 std::string message =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003245 StringPrintf("enqueueDispatchEntriesLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003246 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00003247 ATRACE_NAME(message.c_str());
3248 }
Siarhei Vishniakou5cee1e32022-11-29 12:35:39 -08003249 LOG_ALWAYS_FATAL_IF(!inputTarget.flags.any(InputTarget::DISPATCH_MASK),
3250 "No dispatch flags are set for %s", eventEntry->getDescription().c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00003251
hongzuo liu95785e22022-09-06 02:51:35 +00003252 const bool wasEmpty = connection->outboundQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003253
3254 // Enqueue dispatch entries for the requested modes.
chaviw8c9cf542019-03-25 13:02:48 -07003255 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003256 InputTarget::Flags::DISPATCH_AS_HOVER_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07003257 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003258 InputTarget::Flags::DISPATCH_AS_OUTSIDE);
chaviw8c9cf542019-03-25 13:02:48 -07003259 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003260 InputTarget::Flags::DISPATCH_AS_HOVER_ENTER);
chaviw8c9cf542019-03-25 13:02:48 -07003261 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003262 InputTarget::Flags::DISPATCH_AS_IS);
chaviw8c9cf542019-03-25 13:02:48 -07003263 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003264 InputTarget::Flags::DISPATCH_AS_SLIPPERY_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07003265 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003266 InputTarget::Flags::DISPATCH_AS_SLIPPERY_ENTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003267
3268 // If the outbound queue was previously empty, start the dispatch cycle going.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003269 if (wasEmpty && !connection->outboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003270 startDispatchCycleLocked(currentTime, connection);
3271 }
3272}
3273
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003274void InputDispatcher::enqueueDispatchEntryLocked(const std::shared_ptr<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003275 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003276 const InputTarget& inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003277 ftl::Flags<InputTarget::Flags> dispatchMode) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003278 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003279 std::string message = StringPrintf("enqueueDispatchEntry(inputChannel=%s, dispatchMode=%s)",
3280 connection->getInputChannelName().c_str(),
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003281 dispatchMode.string().c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00003282 ATRACE_NAME(message.c_str());
3283 }
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003284 ftl::Flags<InputTarget::Flags> inputTargetFlags = inputTarget.flags;
3285 if (!inputTargetFlags.any(dispatchMode)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003286 return;
3287 }
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003288
3289 inputTargetFlags.clear(InputTarget::DISPATCH_MASK);
3290 inputTargetFlags |= dispatchMode;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003291
3292 // This is a new event.
3293 // Enqueue a new dispatch entry onto the outbound queue for this connection.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003294 std::unique_ptr<DispatchEntry> dispatchEntry =
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003295 createDispatchEntry(inputTarget, eventEntry, inputTargetFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003296
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003297 // Use the eventEntry from dispatchEntry since the entry may have changed and can now be a
3298 // different EventEntry than what was passed in.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003299 EventEntry& newEntry = *(dispatchEntry->eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003300 // Apply target flags and update the connection's input state.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003301 switch (newEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003302 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003303 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003304 dispatchEntry->resolvedEventId = keyEntry.id;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003305 dispatchEntry->resolvedAction = keyEntry.action;
3306 dispatchEntry->resolvedFlags = keyEntry.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003307
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003308 if (!connection->inputState.trackKey(keyEntry, dispatchEntry->resolvedAction,
3309 dispatchEntry->resolvedFlags)) {
Siarhei Vishniakouc94dafe2023-05-26 10:24:19 -07003310 LOG(WARNING) << "channel " << connection->getInputChannelName()
3311 << "~ dropping inconsistent event: " << *dispatchEntry;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003312 return; // skip the inconsistent event
3313 }
3314 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003315 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003316
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003317 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003318 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003319 // Assign a default value to dispatchEntry that will never be generated by InputReader,
3320 // and assign a InputDispatcher value if it doesn't change in the if-else chain below.
3321 constexpr int32_t DEFAULT_RESOLVED_EVENT_ID =
3322 static_cast<int32_t>(IdGenerator::Source::OTHER);
3323 dispatchEntry->resolvedEventId = DEFAULT_RESOLVED_EVENT_ID;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003324 if (dispatchMode.test(InputTarget::Flags::DISPATCH_AS_OUTSIDE)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003325 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_OUTSIDE;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003326 } else if (dispatchMode.test(InputTarget::Flags::DISPATCH_AS_HOVER_EXIT)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003327 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_EXIT;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003328 } else if (dispatchMode.test(InputTarget::Flags::DISPATCH_AS_HOVER_ENTER)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003329 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003330 } else if (dispatchMode.test(InputTarget::Flags::DISPATCH_AS_SLIPPERY_EXIT)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003331 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_CANCEL;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003332 } else if (dispatchMode.test(InputTarget::Flags::DISPATCH_AS_SLIPPERY_ENTER)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003333 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_DOWN;
3334 } else {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003335 dispatchEntry->resolvedAction = motionEntry.action;
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003336 dispatchEntry->resolvedEventId = motionEntry.id;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003337 }
3338 if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_HOVER_MOVE &&
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003339 !connection->inputState.isHovering(motionEntry.deviceId, motionEntry.source,
3340 motionEntry.displayId)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003341 if (DEBUG_DISPATCH_CYCLE) {
3342 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: filling in missing hover "
3343 "enter event",
3344 connection->getInputChannelName().c_str());
3345 }
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00003346 // We keep the 'resolvedEventId' here equal to the original 'motionEntry.id' because
3347 // this is a one-to-one event conversion.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003348 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
3349 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003350
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003351 dispatchEntry->resolvedFlags = motionEntry.flags;
Siarhei Vishniakou1ae72f12023-01-29 12:55:30 -08003352 if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_CANCEL) {
3353 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_CANCELED;
3354 }
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003355 if (dispatchEntry->targetFlags.test(InputTarget::Flags::WINDOW_IS_OBSCURED)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003356 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED;
3357 }
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003358 if (dispatchEntry->targetFlags.test(InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003359 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
3360 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003361
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003362 if (!connection->inputState.trackMotion(motionEntry, dispatchEntry->resolvedAction,
3363 dispatchEntry->resolvedFlags)) {
Siarhei Vishniakouc94dafe2023-05-26 10:24:19 -07003364 LOG(WARNING) << "channel " << connection->getInputChannelName()
3365 << "~ dropping inconsistent event: " << *dispatchEntry;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003366 return; // skip the inconsistent event
3367 }
3368
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003369 dispatchEntry->resolvedEventId =
3370 dispatchEntry->resolvedEventId == DEFAULT_RESOLVED_EVENT_ID
3371 ? mIdGenerator.nextId()
3372 : motionEntry.id;
3373 if (ATRACE_ENABLED() && dispatchEntry->resolvedEventId != motionEntry.id) {
3374 std::string message = StringPrintf("Transmute MotionEvent(id=0x%" PRIx32
3375 ") to MotionEvent(id=0x%" PRIx32 ").",
3376 motionEntry.id, dispatchEntry->resolvedEventId);
3377 ATRACE_NAME(message.c_str());
3378 }
3379
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08003380 if ((motionEntry.flags & AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE) &&
3381 (motionEntry.policyFlags & POLICY_FLAG_TRUSTED)) {
3382 // Skip reporting pointer down outside focus to the policy.
3383 break;
3384 }
3385
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003386 dispatchPointerDownOutsideFocus(motionEntry.source, dispatchEntry->resolvedAction,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003387 inputTarget.inputChannel->getConnectionToken());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003388
3389 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003390 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003391 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003392 case EventEntry::Type::TOUCH_MODE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08003393 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
3394 case EventEntry::Type::DRAG: {
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003395 break;
3396 }
Chris Yef59a2f42020-10-16 12:55:26 -07003397 case EventEntry::Type::SENSOR: {
3398 LOG_ALWAYS_FATAL("SENSOR events should not go to apps via input channel");
3399 break;
3400 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003401 case EventEntry::Type::CONFIGURATION_CHANGED:
3402 case EventEntry::Type::DEVICE_RESET: {
3403 LOG_ALWAYS_FATAL("%s events should not go to apps",
Dominik Laskowski75788452021-02-09 18:51:25 -08003404 ftl::enum_string(newEntry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003405 break;
3406 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003407 }
3408
3409 // Remember that we are waiting for this dispatch to complete.
3410 if (dispatchEntry->hasForegroundTarget()) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003411 incrementPendingForegroundDispatches(newEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003412 }
3413
3414 // Enqueue the dispatch entry.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003415 connection->outboundQueue.push_back(dispatchEntry.release());
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003416 traceOutboundQueueLength(*connection);
chaviw8c9cf542019-03-25 13:02:48 -07003417}
3418
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003419/**
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003420 * This function is for debugging and metrics collection. It has two roles.
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003421 *
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003422 * The first role is to log input interaction with windows, which helps determine what the user was
3423 * interacting with. For example, if user is touching launcher, we will see an input_interaction log
3424 * that user started interacting with launcher window, as well as any other window that received
3425 * that gesture, such as the wallpaper or other spy windows. A new input_interaction is only logged
3426 * when the set of tokens that received the event changes. It is not logged again as long as the
3427 * user is interacting with the same windows.
3428 *
3429 * The second role is to track input device activity for metrics collection. For each input event,
3430 * we report the set of UIDs that the input device interacted with to the policy. Unlike for the
3431 * input_interaction logs, the device interaction is reported even when the set of interaction
3432 * tokens do not change.
3433 *
3434 * For these purposes, we do not count ACTION_OUTSIDE, ACTION_UP and ACTION_CANCEL actions as
3435 * interaction. This includes up and cancel events for both keys and motions.
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003436 */
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003437void InputDispatcher::processInteractionsLocked(const EventEntry& entry,
3438 const std::vector<InputTarget>& targets) {
3439 int32_t deviceId;
3440 nsecs_t eventTime;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003441 // Skip ACTION_UP events, and all events other than keys and motions
3442 if (entry.type == EventEntry::Type::KEY) {
3443 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
3444 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
3445 return;
3446 }
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003447 deviceId = keyEntry.deviceId;
3448 eventTime = keyEntry.eventTime;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003449 } else if (entry.type == EventEntry::Type::MOTION) {
3450 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
3451 if (motionEntry.action == AMOTION_EVENT_ACTION_UP ||
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003452 motionEntry.action == AMOTION_EVENT_ACTION_CANCEL ||
3453 MotionEvent::getActionMasked(motionEntry.action) == AMOTION_EVENT_ACTION_POINTER_UP) {
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003454 return;
3455 }
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003456 deviceId = motionEntry.deviceId;
3457 eventTime = motionEntry.eventTime;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003458 } else {
3459 return; // Not a key or a motion
3460 }
3461
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003462 std::set<gui::Uid> interactionUids;
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07003463 std::unordered_set<sp<IBinder>, StrongPointerHash<IBinder>> newConnectionTokens;
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003464 std::vector<std::shared_ptr<Connection>> newConnections;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003465 for (const InputTarget& target : targets) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003466 if (target.flags.test(InputTarget::Flags::DISPATCH_AS_OUTSIDE)) {
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003467 continue; // Skip windows that receive ACTION_OUTSIDE
3468 }
3469
3470 sp<IBinder> token = target.inputChannel->getConnectionToken();
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003471 std::shared_ptr<Connection> connection = getConnectionLocked(token);
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003472 if (connection == nullptr) {
3473 continue;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003474 }
3475 newConnectionTokens.insert(std::move(token));
3476 newConnections.emplace_back(connection);
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003477 if (target.windowHandle) {
3478 interactionUids.emplace(target.windowHandle->getInfo()->ownerUid);
3479 }
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003480 }
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003481
3482 auto command = [this, deviceId, eventTime, uids = std::move(interactionUids)]()
3483 REQUIRES(mLock) {
3484 scoped_unlock unlock(mLock);
3485 mPolicy.notifyDeviceInteraction(deviceId, eventTime, uids);
3486 };
3487 postCommandLocked(std::move(command));
3488
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003489 if (newConnectionTokens == mInteractionConnectionTokens) {
3490 return; // no change
3491 }
3492 mInteractionConnectionTokens = newConnectionTokens;
3493
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003494 std::string targetList;
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003495 for (const std::shared_ptr<Connection>& connection : newConnections) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003496 targetList += connection->getWindowName() + ", ";
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003497 }
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003498 std::string message = "Interaction with: " + targetList;
3499 if (targetList.empty()) {
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003500 message += "<none>";
3501 }
3502 android_log_event_list(LOGTAG_INPUT_INTERACTION) << message << LOG_ID_EVENTS;
3503}
3504
chaviwfd6d3512019-03-25 13:23:49 -07003505void InputDispatcher::dispatchPointerDownOutsideFocus(uint32_t source, int32_t action,
Vishnu Nairad321cd2020-08-20 16:40:21 -07003506 const sp<IBinder>& token) {
chaviw8c9cf542019-03-25 13:02:48 -07003507 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
chaviwfd6d3512019-03-25 13:23:49 -07003508 uint32_t maskedSource = source & AINPUT_SOURCE_CLASS_MASK;
3509 if (maskedSource != AINPUT_SOURCE_CLASS_POINTER || maskedAction != AMOTION_EVENT_ACTION_DOWN) {
chaviw8c9cf542019-03-25 13:02:48 -07003510 return;
3511 }
3512
Vishnu Nairc519ff72021-01-21 08:23:08 -08003513 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07003514 if (focusedToken == token) {
3515 // ignore since token is focused
chaviw8c9cf542019-03-25 13:02:48 -07003516 return;
3517 }
3518
Prabir Pradhancef936d2021-07-21 16:17:52 +00003519 auto command = [this, token]() REQUIRES(mLock) {
3520 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00003521 mPolicy.onPointerDownOutsideFocus(token);
Prabir Pradhancef936d2021-07-21 16:17:52 +00003522 };
3523 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003524}
3525
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003526status_t InputDispatcher::publishMotionEvent(Connection& connection,
3527 DispatchEntry& dispatchEntry) const {
3528 const EventEntry& eventEntry = *(dispatchEntry.eventEntry);
3529 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
3530
3531 PointerCoords scaledCoords[MAX_POINTERS];
3532 const PointerCoords* usingCoords = motionEntry.pointerCoords;
3533
3534 // Set the X and Y offset and X and Y scale depending on the input source.
3535 if ((motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) &&
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003536 !(dispatchEntry.targetFlags.test(InputTarget::Flags::ZERO_COORDS))) {
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003537 float globalScaleFactor = dispatchEntry.globalScaleFactor;
3538 if (globalScaleFactor != 1.0f) {
3539 for (uint32_t i = 0; i < motionEntry.pointerCount; i++) {
3540 scaledCoords[i] = motionEntry.pointerCoords[i];
3541 // Don't apply window scale here since we don't want scale to affect raw
3542 // coordinates. The scale will be sent back to the client and applied
3543 // later when requesting relative coordinates.
Harry Cutts33476232023-01-30 19:57:29 +00003544 scaledCoords[i].scale(globalScaleFactor, /*windowXScale=*/1, /*windowYScale=*/1);
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003545 }
3546 usingCoords = scaledCoords;
3547 }
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003548 } else if (dispatchEntry.targetFlags.test(InputTarget::Flags::ZERO_COORDS)) {
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003549 // We don't want the dispatch target to know the coordinates
3550 for (uint32_t i = 0; i < motionEntry.pointerCount; i++) {
3551 scaledCoords[i].clear();
3552 }
3553 usingCoords = scaledCoords;
3554 }
3555
3556 std::array<uint8_t, 32> hmac = getSignature(motionEntry, dispatchEntry);
3557
3558 // Publish the motion event.
3559 return connection.inputPublisher
3560 .publishMotionEvent(dispatchEntry.seq, dispatchEntry.resolvedEventId,
3561 motionEntry.deviceId, motionEntry.source, motionEntry.displayId,
3562 std::move(hmac), dispatchEntry.resolvedAction,
3563 motionEntry.actionButton, dispatchEntry.resolvedFlags,
3564 motionEntry.edgeFlags, motionEntry.metaState,
3565 motionEntry.buttonState, motionEntry.classification,
3566 dispatchEntry.transform, motionEntry.xPrecision,
3567 motionEntry.yPrecision, motionEntry.xCursorPosition,
3568 motionEntry.yCursorPosition, dispatchEntry.rawTransform,
3569 motionEntry.downTime, motionEntry.eventTime,
3570 motionEntry.pointerCount, motionEntry.pointerProperties,
3571 usingCoords);
3572}
3573
Michael Wrightd02c5b62014-02-10 15:10:22 -08003574void InputDispatcher::startDispatchCycleLocked(nsecs_t currentTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003575 const std::shared_ptr<Connection>& connection) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003576 if (ATRACE_ENABLED()) {
3577 std::string message = StringPrintf("startDispatchCycleLocked(inputChannel=%s)",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003578 connection->getInputChannelName().c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00003579 ATRACE_NAME(message.c_str());
3580 }
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003581 if (DEBUG_DISPATCH_CYCLE) {
3582 ALOGD("channel '%s' ~ startDispatchCycle", connection->getInputChannelName().c_str());
3583 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003584
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003585 while (connection->status == Connection::Status::NORMAL && !connection->outboundQueue.empty()) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003586 DispatchEntry* dispatchEntry = connection->outboundQueue.front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003587 dispatchEntry->deliveryTime = currentTime;
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003588 const std::chrono::nanoseconds timeout = getDispatchingTimeoutLocked(connection);
Siarhei Vishniakou70622952020-07-30 11:17:23 -05003589 dispatchEntry->timeoutTime = currentTime + timeout.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003590
3591 // Publish the event.
3592 status_t status;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003593 const EventEntry& eventEntry = *(dispatchEntry->eventEntry);
3594 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003595 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003596 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
3597 std::array<uint8_t, 32> hmac = getSignature(keyEntry, *dispatchEntry);
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08003598 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
3599 LOG(DEBUG) << "Publishing " << *dispatchEntry << " to "
3600 << connection->getInputChannelName();
3601 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003602
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003603 // Publish the key event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003604 status = connection->inputPublisher
3605 .publishKeyEvent(dispatchEntry->seq,
3606 dispatchEntry->resolvedEventId, keyEntry.deviceId,
3607 keyEntry.source, keyEntry.displayId,
3608 std::move(hmac), dispatchEntry->resolvedAction,
3609 dispatchEntry->resolvedFlags, keyEntry.keyCode,
3610 keyEntry.scanCode, keyEntry.metaState,
3611 keyEntry.repeatCount, keyEntry.downTime,
3612 keyEntry.eventTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003613 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003614 }
3615
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003616 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08003617 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
3618 LOG(DEBUG) << "Publishing " << *dispatchEntry << " to "
3619 << connection->getInputChannelName();
3620 }
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003621 status = publishMotionEvent(*connection, *dispatchEntry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003622 break;
3623 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003624
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003625 case EventEntry::Type::FOCUS: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003626 const FocusEntry& focusEntry = static_cast<const FocusEntry&>(eventEntry);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003627 status = connection->inputPublisher.publishFocusEvent(dispatchEntry->seq,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003628 focusEntry.id,
Antonio Kantek3cfec7b2021-11-05 18:26:17 -07003629 focusEntry.hasFocus);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003630 break;
3631 }
3632
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003633 case EventEntry::Type::TOUCH_MODE_CHANGED: {
3634 const TouchModeEntry& touchModeEntry =
3635 static_cast<const TouchModeEntry&>(eventEntry);
3636 status = connection->inputPublisher
3637 .publishTouchModeEvent(dispatchEntry->seq, touchModeEntry.id,
3638 touchModeEntry.inTouchMode);
3639
3640 break;
3641 }
3642
Prabir Pradhan99987712020-11-10 18:43:05 -08003643 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
3644 const auto& captureEntry =
3645 static_cast<const PointerCaptureChangedEntry&>(eventEntry);
3646 status = connection->inputPublisher
3647 .publishCaptureEvent(dispatchEntry->seq, captureEntry.id,
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00003648 captureEntry.pointerCaptureRequest.enable);
Prabir Pradhan99987712020-11-10 18:43:05 -08003649 break;
3650 }
3651
arthurhungb89ccb02020-12-30 16:19:01 +08003652 case EventEntry::Type::DRAG: {
3653 const DragEntry& dragEntry = static_cast<const DragEntry&>(eventEntry);
3654 status = connection->inputPublisher.publishDragEvent(dispatchEntry->seq,
3655 dragEntry.id, dragEntry.x,
3656 dragEntry.y,
3657 dragEntry.isExiting);
3658 break;
3659 }
3660
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003661 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07003662 case EventEntry::Type::DEVICE_RESET:
3663 case EventEntry::Type::SENSOR: {
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003664 LOG_ALWAYS_FATAL("Should never start dispatch cycles for %s events",
Dominik Laskowski75788452021-02-09 18:51:25 -08003665 ftl::enum_string(eventEntry.type).c_str());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003666 return;
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003667 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003668 }
3669
3670 // Check the result.
3671 if (status) {
3672 if (status == WOULD_BLOCK) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003673 if (connection->waitQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003674 ALOGE("channel '%s' ~ Could not publish event because the pipe is full. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003675 "This is unexpected because the wait queue is empty, so the pipe "
3676 "should be empty and we shouldn't have any problems writing an "
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +00003677 "event to it, 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 } else {
3682 // Pipe is full and we are waiting for the app to finish process some events
3683 // before sending more events to it.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003684 if (DEBUG_DISPATCH_CYCLE) {
3685 ALOGD("channel '%s' ~ Could not publish event because the pipe is full, "
3686 "waiting for the application to catch up",
3687 connection->getInputChannelName().c_str());
3688 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003689 }
3690 } else {
3691 ALOGE("channel '%s' ~ Could not publish event due to an unexpected error, "
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +00003692 "status=%s(%d)",
3693 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3694 status);
Harry Cutts33476232023-01-30 19:57:29 +00003695 abortBrokenDispatchCycleLocked(currentTime, connection, /*notify=*/true);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003696 }
3697 return;
3698 }
3699
3700 // Re-enqueue the event on the wait queue.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003701 connection->outboundQueue.erase(std::remove(connection->outboundQueue.begin(),
3702 connection->outboundQueue.end(),
3703 dispatchEntry));
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003704 traceOutboundQueueLength(*connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003705 connection->waitQueue.push_back(dispatchEntry);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003706 if (connection->responsive) {
3707 mAnrTracker.insert(dispatchEntry->timeoutTime,
3708 connection->inputChannel->getConnectionToken());
3709 }
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003710 traceWaitQueueLength(*connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003711 }
3712}
3713
chaviw09c8d2d2020-08-24 15:48:26 -07003714std::array<uint8_t, 32> InputDispatcher::sign(const VerifiedInputEvent& event) const {
3715 size_t size;
3716 switch (event.type) {
3717 case VerifiedInputEvent::Type::KEY: {
3718 size = sizeof(VerifiedKeyEvent);
3719 break;
3720 }
3721 case VerifiedInputEvent::Type::MOTION: {
3722 size = sizeof(VerifiedMotionEvent);
3723 break;
3724 }
3725 }
3726 const uint8_t* start = reinterpret_cast<const uint8_t*>(&event);
3727 return mHmacKeyManager.sign(start, size);
3728}
3729
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003730const std::array<uint8_t, 32> InputDispatcher::getSignature(
3731 const MotionEntry& motionEntry, const DispatchEntry& dispatchEntry) const {
Siarhei Vishniakoubf880522023-05-01 11:03:22 -07003732 const int32_t actionMasked = MotionEvent::getActionMasked(dispatchEntry.resolvedAction);
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003733 if (actionMasked != AMOTION_EVENT_ACTION_UP && actionMasked != AMOTION_EVENT_ACTION_DOWN) {
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003734 // Only sign events up and down events as the purely move events
3735 // are tied to their up/down counterparts so signing would be redundant.
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003736 return INVALID_HMAC;
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003737 }
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003738
3739 VerifiedMotionEvent verifiedEvent =
3740 verifiedMotionEventFromMotionEntry(motionEntry, dispatchEntry.rawTransform);
3741 verifiedEvent.actionMasked = actionMasked;
3742 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_MOTION_EVENT_FLAGS;
3743 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003744}
3745
3746const std::array<uint8_t, 32> InputDispatcher::getSignature(
3747 const KeyEntry& keyEntry, const DispatchEntry& dispatchEntry) const {
3748 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEntry(keyEntry);
3749 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_KEY_EVENT_FLAGS;
3750 verifiedEvent.action = dispatchEntry.resolvedAction;
chaviw09c8d2d2020-08-24 15:48:26 -07003751 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003752}
3753
Michael Wrightd02c5b62014-02-10 15:10:22 -08003754void InputDispatcher::finishDispatchCycleLocked(nsecs_t currentTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003755 const std::shared_ptr<Connection>& connection,
3756 uint32_t seq, bool handled, nsecs_t consumeTime) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003757 if (DEBUG_DISPATCH_CYCLE) {
3758 ALOGD("channel '%s' ~ finishDispatchCycle - seq=%u, handled=%s",
3759 connection->getInputChannelName().c_str(), seq, toString(handled));
3760 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003761
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003762 if (connection->status == Connection::Status::BROKEN ||
3763 connection->status == Connection::Status::ZOMBIE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003764 return;
3765 }
3766
3767 // Notify other system components and prepare to start the next dispatch cycle.
Prabir Pradhancef936d2021-07-21 16:17:52 +00003768 auto command = [this, currentTime, connection, seq, handled, consumeTime]() REQUIRES(mLock) {
3769 doDispatchCycleFinishedCommand(currentTime, connection, seq, handled, consumeTime);
3770 };
3771 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003772}
3773
3774void InputDispatcher::abortBrokenDispatchCycleLocked(nsecs_t currentTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003775 const std::shared_ptr<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003776 bool notify) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003777 if (DEBUG_DISPATCH_CYCLE) {
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07003778 LOG(DEBUG) << "channel '" << connection->getInputChannelName() << "'~ " << __func__
3779 << " - notify=" << toString(notify);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003780 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003781
3782 // Clear the dispatch queues.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003783 drainDispatchQueue(connection->outboundQueue);
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003784 traceOutboundQueueLength(*connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003785 drainDispatchQueue(connection->waitQueue);
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003786 traceWaitQueueLength(*connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003787
3788 // The connection appears to be unrecoverably broken.
3789 // Ignore already broken or zombie connections.
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003790 if (connection->status == Connection::Status::NORMAL) {
3791 connection->status = Connection::Status::BROKEN;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003792
3793 if (notify) {
3794 // Notify other system components.
Prabir Pradhancef936d2021-07-21 16:17:52 +00003795 ALOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
3796 connection->getInputChannelName().c_str());
3797
3798 auto command = [this, connection]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00003799 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00003800 mPolicy.notifyInputChannelBroken(connection->inputChannel->getConnectionToken());
Prabir Pradhancef936d2021-07-21 16:17:52 +00003801 };
3802 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003803 }
3804 }
3805}
3806
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003807void InputDispatcher::drainDispatchQueue(std::deque<DispatchEntry*>& queue) {
3808 while (!queue.empty()) {
3809 DispatchEntry* dispatchEntry = queue.front();
3810 queue.pop_front();
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003811 releaseDispatchEntry(dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003812 }
3813}
3814
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003815void InputDispatcher::releaseDispatchEntry(DispatchEntry* dispatchEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003816 if (dispatchEntry->hasForegroundTarget()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003817 decrementPendingForegroundDispatches(*(dispatchEntry->eventEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003818 }
3819 delete dispatchEntry;
3820}
3821
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003822int InputDispatcher::handleReceiveCallback(int events, sp<IBinder> connectionToken) {
3823 std::scoped_lock _l(mLock);
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003824 std::shared_ptr<Connection> connection = getConnectionLocked(connectionToken);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003825 if (connection == nullptr) {
3826 ALOGW("Received looper callback for unknown input channel token %p. events=0x%x",
3827 connectionToken.get(), events);
3828 return 0; // remove the callback
3829 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003830
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003831 bool notify;
3832 if (!(events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP))) {
3833 if (!(events & ALOOPER_EVENT_INPUT)) {
3834 ALOGW("channel '%s' ~ Received spurious callback for unhandled poll event. "
3835 "events=0x%x",
3836 connection->getInputChannelName().c_str(), events);
3837 return 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003838 }
3839
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003840 nsecs_t currentTime = now();
3841 bool gotOne = false;
3842 status_t status = OK;
3843 for (;;) {
3844 Result<InputPublisher::ConsumerResponse> result =
3845 connection->inputPublisher.receiveConsumerResponse();
3846 if (!result.ok()) {
3847 status = result.error().code();
3848 break;
3849 }
3850
3851 if (std::holds_alternative<InputPublisher::Finished>(*result)) {
3852 const InputPublisher::Finished& finish =
3853 std::get<InputPublisher::Finished>(*result);
3854 finishDispatchCycleLocked(currentTime, connection, finish.seq, finish.handled,
3855 finish.consumeTime);
3856 } else if (std::holds_alternative<InputPublisher::Timeline>(*result)) {
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00003857 if (shouldReportMetricsForConnection(*connection)) {
3858 const InputPublisher::Timeline& timeline =
3859 std::get<InputPublisher::Timeline>(*result);
3860 mLatencyTracker
3861 .trackGraphicsLatency(timeline.inputEventId,
3862 connection->inputChannel->getConnectionToken(),
3863 std::move(timeline.graphicsTimeline));
3864 }
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003865 }
3866 gotOne = true;
3867 }
3868 if (gotOne) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00003869 runCommandsLockedInterruptable();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003870 if (status == WOULD_BLOCK) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003871 return 1;
3872 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003873 }
3874
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003875 notify = status != DEAD_OBJECT || !connection->monitor;
3876 if (notify) {
3877 ALOGE("channel '%s' ~ Failed to receive finished signal. status=%s(%d)",
3878 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3879 status);
3880 }
3881 } else {
3882 // Monitor channels are never explicitly unregistered.
3883 // We do it automatically when the remote endpoint is closed so don't warn about them.
3884 const bool stillHaveWindowHandle =
3885 getWindowHandleLocked(connection->inputChannel->getConnectionToken()) != nullptr;
3886 notify = !connection->monitor && stillHaveWindowHandle;
3887 if (notify) {
3888 ALOGW("channel '%s' ~ Consumer closed input channel or an error occurred. events=0x%x",
3889 connection->getInputChannelName().c_str(), events);
3890 }
3891 }
3892
3893 // Remove the channel.
3894 removeInputChannelLocked(connection->inputChannel->getConnectionToken(), notify);
3895 return 0; // remove the callback
Michael Wrightd02c5b62014-02-10 15:10:22 -08003896}
3897
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003898void InputDispatcher::synthesizeCancelationEventsForAllConnectionsLocked(
Michael Wrightd02c5b62014-02-10 15:10:22 -08003899 const CancelationOptions& options) {
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003900 for (const auto& [token, connection] : mConnectionsByToken) {
Siarhei Vishniakou2e2ea992020-12-15 02:57:19 +00003901 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003902 }
3903}
3904
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003905void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
Michael Wrightfa13dcf2015-06-12 13:25:11 +01003906 const CancelationOptions& options) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08003907 for (const auto& [_, monitors] : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003908 for (const Monitor& monitor : monitors) {
3909 synthesizeCancelationEventsForInputChannelLocked(monitor.inputChannel, options);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003910 }
Michael Wrightfa13dcf2015-06-12 13:25:11 +01003911 }
3912}
3913
Michael Wrightd02c5b62014-02-10 15:10:22 -08003914void InputDispatcher::synthesizeCancelationEventsForInputChannelLocked(
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05003915 const std::shared_ptr<InputChannel>& channel, const CancelationOptions& options) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003916 std::shared_ptr<Connection> connection = getConnectionLocked(channel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003917 if (connection == nullptr) {
3918 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003919 }
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003920
3921 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003922}
3923
3924void InputDispatcher::synthesizeCancelationEventsForConnectionLocked(
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003925 const std::shared_ptr<Connection>& connection, const CancelationOptions& options) {
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003926 if (connection->status == Connection::Status::BROKEN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003927 return;
3928 }
3929
3930 nsecs_t currentTime = now();
3931
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003932 std::vector<std::unique_ptr<EventEntry>> cancelationEvents =
Siarhei Vishniakou00fca7c2019-10-29 13:05:57 -07003933 connection->inputState.synthesizeCancelationEvents(currentTime, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003934
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003935 if (cancelationEvents.empty()) {
3936 return;
3937 }
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003938 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
3939 ALOGD("channel '%s' ~ Synthesized %zu cancelation events to bring channel back in sync "
Siarhei Vishniakou2e3e4432023-02-09 18:34:11 -08003940 "with reality: %s, mode=%s.",
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003941 connection->getInputChannelName().c_str(), cancelationEvents.size(), options.reason,
Siarhei Vishniakou2e3e4432023-02-09 18:34:11 -08003942 ftl::enum_string(options.mode).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003943 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08003944
Arthur Hungb3307ee2021-10-14 10:57:37 +00003945 std::string reason = std::string("reason=").append(options.reason);
3946 android_log_event_list(LOGTAG_INPUT_CANCEL)
3947 << connection->getInputChannelName().c_str() << reason << LOG_ID_EVENTS;
3948
Svet Ganov5d3bc372020-01-26 23:11:07 -08003949 InputTarget target;
chaviw98318de2021-05-19 16:45:23 -05003950 sp<WindowInfoHandle> windowHandle =
Svet Ganov5d3bc372020-01-26 23:11:07 -08003951 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
3952 if (windowHandle != nullptr) {
chaviw98318de2021-05-19 16:45:23 -05003953 const WindowInfo* windowInfo = windowHandle->getInfo();
chaviw1ff3d1e2020-07-01 15:53:47 -07003954 target.setDefaultPointerTransform(windowInfo->transform);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003955 target.globalScaleFactor = windowInfo->globalScaleFactor;
3956 }
3957 target.inputChannel = connection->inputChannel;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003958 target.flags = InputTarget::Flags::DISPATCH_AS_IS;
Svet Ganov5d3bc372020-01-26 23:11:07 -08003959
hongzuo liu95785e22022-09-06 02:51:35 +00003960 const bool wasEmpty = connection->outboundQueue.empty();
3961
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003962 for (size_t i = 0; i < cancelationEvents.size(); i++) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003963 std::unique_ptr<EventEntry> cancelationEventEntry = std::move(cancelationEvents[i]);
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003964 switch (cancelationEventEntry->type) {
3965 case EventEntry::Type::KEY: {
3966 logOutboundKeyDetails("cancel - ",
3967 static_cast<const KeyEntry&>(*cancelationEventEntry));
3968 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003969 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003970 case EventEntry::Type::MOTION: {
3971 logOutboundMotionDetails("cancel - ",
3972 static_cast<const MotionEntry&>(*cancelationEventEntry));
3973 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003974 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003975 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003976 case EventEntry::Type::TOUCH_MODE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08003977 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
3978 case EventEntry::Type::DRAG: {
Prabir Pradhan99987712020-11-10 18:43:05 -08003979 LOG_ALWAYS_FATAL("Canceling %s events is not supported",
Dominik Laskowski75788452021-02-09 18:51:25 -08003980 ftl::enum_string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003981 break;
3982 }
3983 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07003984 case EventEntry::Type::DEVICE_RESET:
3985 case EventEntry::Type::SENSOR: {
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003986 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Dominik Laskowski75788452021-02-09 18:51:25 -08003987 ftl::enum_string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003988 break;
3989 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003990 }
3991
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003992 enqueueDispatchEntryLocked(connection, std::move(cancelationEventEntry), target,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003993 InputTarget::Flags::DISPATCH_AS_IS);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003994 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003995
hongzuo liu95785e22022-09-06 02:51:35 +00003996 // If the outbound queue was previously empty, start the dispatch cycle going.
3997 if (wasEmpty && !connection->outboundQueue.empty()) {
3998 startDispatchCycleLocked(currentTime, connection);
3999 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004000}
4001
Svet Ganov5d3bc372020-01-26 23:11:07 -08004002void InputDispatcher::synthesizePointerDownEventsForConnectionLocked(
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07004003 const nsecs_t downTime, const std::shared_ptr<Connection>& connection,
Arthur Hungc539dbb2022-12-08 07:45:36 +00004004 ftl::Flags<InputTarget::Flags> targetFlags) {
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08004005 if (connection->status == Connection::Status::BROKEN) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08004006 return;
4007 }
4008
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004009 std::vector<std::unique_ptr<EventEntry>> downEvents =
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00004010 connection->inputState.synthesizePointerDownEvents(downTime);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004011
4012 if (downEvents.empty()) {
4013 return;
4014 }
4015
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004016 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08004017 ALOGD("channel '%s' ~ Synthesized %zu down events to ensure consistent event stream.",
4018 connection->getInputChannelName().c_str(), downEvents.size());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004019 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08004020
4021 InputTarget target;
chaviw98318de2021-05-19 16:45:23 -05004022 sp<WindowInfoHandle> windowHandle =
Svet Ganov5d3bc372020-01-26 23:11:07 -08004023 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
4024 if (windowHandle != nullptr) {
chaviw98318de2021-05-19 16:45:23 -05004025 const WindowInfo* windowInfo = windowHandle->getInfo();
chaviw1ff3d1e2020-07-01 15:53:47 -07004026 target.setDefaultPointerTransform(windowInfo->transform);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004027 target.globalScaleFactor = windowInfo->globalScaleFactor;
4028 }
4029 target.inputChannel = connection->inputChannel;
Arthur Hungc539dbb2022-12-08 07:45:36 +00004030 target.flags = targetFlags;
Svet Ganov5d3bc372020-01-26 23:11:07 -08004031
hongzuo liu95785e22022-09-06 02:51:35 +00004032 const bool wasEmpty = connection->outboundQueue.empty();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004033 for (std::unique_ptr<EventEntry>& downEventEntry : downEvents) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08004034 switch (downEventEntry->type) {
4035 case EventEntry::Type::MOTION: {
4036 logOutboundMotionDetails("down - ",
4037 static_cast<const MotionEntry&>(*downEventEntry));
4038 break;
4039 }
4040
4041 case EventEntry::Type::KEY:
4042 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07004043 case EventEntry::Type::TOUCH_MODE_CHANGED:
Svet Ganov5d3bc372020-01-26 23:11:07 -08004044 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08004045 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07004046 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08004047 case EventEntry::Type::SENSOR:
4048 case EventEntry::Type::DRAG: {
Svet Ganov5d3bc372020-01-26 23:11:07 -08004049 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Dominik Laskowski75788452021-02-09 18:51:25 -08004050 ftl::enum_string(downEventEntry->type).c_str());
Svet Ganov5d3bc372020-01-26 23:11:07 -08004051 break;
4052 }
4053 }
4054
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004055 enqueueDispatchEntryLocked(connection, std::move(downEventEntry), target,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08004056 InputTarget::Flags::DISPATCH_AS_IS);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004057 }
4058
hongzuo liu95785e22022-09-06 02:51:35 +00004059 // If the outbound queue was previously empty, start the dispatch cycle going.
4060 if (wasEmpty && !connection->outboundQueue.empty()) {
4061 startDispatchCycleLocked(downTime, connection);
4062 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08004063}
4064
Arthur Hungc539dbb2022-12-08 07:45:36 +00004065void InputDispatcher::synthesizeCancelationEventsForWindowLocked(
4066 const sp<WindowInfoHandle>& windowHandle, const CancelationOptions& options) {
4067 if (windowHandle != nullptr) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07004068 std::shared_ptr<Connection> wallpaperConnection =
4069 getConnectionLocked(windowHandle->getToken());
Arthur Hungc539dbb2022-12-08 07:45:36 +00004070 if (wallpaperConnection != nullptr) {
4071 synthesizeCancelationEventsForConnectionLocked(wallpaperConnection, options);
4072 }
4073 }
4074}
4075
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004076std::unique_ptr<MotionEntry> InputDispatcher::splitMotionEvent(
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08004077 const MotionEntry& originalMotionEntry, std::bitset<MAX_POINTER_ID + 1> pointerIds,
4078 nsecs_t splitDownTime) {
4079 ALOG_ASSERT(pointerIds.any());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004080
4081 uint32_t splitPointerIndexMap[MAX_POINTERS];
4082 PointerProperties splitPointerProperties[MAX_POINTERS];
4083 PointerCoords splitPointerCoords[MAX_POINTERS];
4084
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07004085 uint32_t originalPointerCount = originalMotionEntry.pointerCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004086 uint32_t splitPointerCount = 0;
4087
4088 for (uint32_t originalPointerIndex = 0; originalPointerIndex < originalPointerCount;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004089 originalPointerIndex++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004090 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07004091 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08004092 uint32_t pointerId = uint32_t(pointerProperties.id);
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08004093 if (pointerIds.test(pointerId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004094 splitPointerIndexMap[splitPointerCount] = originalPointerIndex;
4095 splitPointerProperties[splitPointerCount].copyFrom(pointerProperties);
4096 splitPointerCoords[splitPointerCount].copyFrom(
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07004097 originalMotionEntry.pointerCoords[originalPointerIndex]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004098 splitPointerCount += 1;
4099 }
4100 }
4101
4102 if (splitPointerCount != pointerIds.count()) {
4103 // This is bad. We are missing some of the pointers that we expected to deliver.
4104 // Most likely this indicates that we received an ACTION_MOVE events that has
4105 // different pointer ids than we expected based on the previous ACTION_DOWN
4106 // or ACTION_POINTER_DOWN events that caused us to decide to split the pointers
4107 // in this way.
4108 ALOGW("Dropping split motion event because the pointer count is %d but "
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08004109 "we expected there to be %zu pointers. This probably means we received "
Siarhei Vishniakou16e4fa02023-02-16 17:48:56 -08004110 "a broken sequence of pointer ids from the input device: %s",
4111 splitPointerCount, pointerIds.count(), originalMotionEntry.getDescription().c_str());
Yi Kong9b14ac62018-07-17 13:48:38 -07004112 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004113 }
4114
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07004115 int32_t action = originalMotionEntry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004116 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004117 if (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN ||
4118 maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004119 int32_t originalPointerIndex = getMotionEventActionPointerIndex(action);
4120 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07004121 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08004122 uint32_t pointerId = uint32_t(pointerProperties.id);
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08004123 if (pointerIds.test(pointerId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004124 if (pointerIds.count() == 1) {
4125 // The first/last pointer went down/up.
4126 action = maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004127 ? AMOTION_EVENT_ACTION_DOWN
arthurhungea3f4fc2020-12-21 23:18:53 +08004128 : (originalMotionEntry.flags & AMOTION_EVENT_FLAG_CANCELED) != 0
4129 ? AMOTION_EVENT_ACTION_CANCEL
4130 : AMOTION_EVENT_ACTION_UP;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004131 } else {
4132 // A secondary pointer went down/up.
4133 uint32_t splitPointerIndex = 0;
4134 while (pointerId != uint32_t(splitPointerProperties[splitPointerIndex].id)) {
4135 splitPointerIndex += 1;
4136 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004137 action = maskedAction |
4138 (splitPointerIndex << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004139 }
4140 } else {
4141 // An unrelated pointer changed.
4142 action = AMOTION_EVENT_ACTION_MOVE;
4143 }
4144 }
4145
Siarhei Vishniakou59e302b2023-06-05 08:04:53 -07004146 if (action == AMOTION_EVENT_ACTION_DOWN && splitDownTime != originalMotionEntry.eventTime) {
4147 logDispatchStateLocked();
4148 LOG_ALWAYS_FATAL("Split motion event has mismatching downTime and eventTime for "
4149 "ACTION_DOWN, motionEntry=%s, splitDownTime=%" PRId64,
4150 originalMotionEntry.getDescription().c_str(), splitDownTime);
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00004151 }
4152
Garfield Tanff1f1bb2020-01-28 13:24:04 -08004153 int32_t newId = mIdGenerator.nextId();
4154 if (ATRACE_ENABLED()) {
4155 std::string message = StringPrintf("Split MotionEvent(id=0x%" PRIx32
4156 ") to MotionEvent(id=0x%" PRIx32 ").",
4157 originalMotionEntry.id, newId);
4158 ATRACE_NAME(message.c_str());
4159 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004160 std::unique_ptr<MotionEntry> splitMotionEntry =
4161 std::make_unique<MotionEntry>(newId, originalMotionEntry.eventTime,
4162 originalMotionEntry.deviceId, originalMotionEntry.source,
4163 originalMotionEntry.displayId,
4164 originalMotionEntry.policyFlags, action,
4165 originalMotionEntry.actionButton,
4166 originalMotionEntry.flags, originalMotionEntry.metaState,
4167 originalMotionEntry.buttonState,
4168 originalMotionEntry.classification,
4169 originalMotionEntry.edgeFlags,
4170 originalMotionEntry.xPrecision,
4171 originalMotionEntry.yPrecision,
4172 originalMotionEntry.xCursorPosition,
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00004173 originalMotionEntry.yCursorPosition, splitDownTime,
4174 splitPointerCount, splitPointerProperties,
4175 splitPointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004176
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07004177 if (originalMotionEntry.injectionState) {
4178 splitMotionEntry->injectionState = originalMotionEntry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004179 splitMotionEntry->injectionState->refCount += 1;
4180 }
4181
4182 return splitMotionEntry;
4183}
4184
Prabir Pradhan678438e2023-04-13 19:32:51 +00004185void InputDispatcher::notifyConfigurationChanged(const NotifyConfigurationChangedArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004186 if (debugInboundEventDetails()) {
Prabir Pradhan678438e2023-04-13 19:32:51 +00004187 ALOGD("notifyConfigurationChanged - eventTime=%" PRId64, args.eventTime);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004188 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004189
Antonio Kantekf16f2832021-09-28 04:39:20 +00004190 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004191 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004192 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004193
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004194 std::unique_ptr<ConfigurationChangedEntry> newEntry =
Prabir Pradhan678438e2023-04-13 19:32:51 +00004195 std::make_unique<ConfigurationChangedEntry>(args.id, args.eventTime);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004196 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004197 } // release lock
4198
4199 if (needWake) {
4200 mLooper->wake();
4201 }
4202}
4203
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05004204/**
4205 * If one of the meta shortcuts is detected, process them here:
Vaibhav Devmurari34cd5b02023-02-23 14:51:18 +00004206 * Meta + Backspace; Meta + Grave; Meta + Left arrow -> generate BACK
4207 * Most System shortcuts are handled in PhoneWindowManager.java except 'Back' shortcuts. Unlike
4208 * Back, other shortcuts DO NOT need to be sent to applications and are fully handled by the system.
4209 * But for Back key and Back shortcuts, we need to send KEYCODE_BACK to applications which can
4210 * potentially handle the back key presses.
4211 * Note: We don't send any Meta based KeyEvents to applications, so we need to convert to a KeyEvent
4212 * where meta modifier is off before sending. Currently only use case is 'Back'.
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05004213 */
4214void InputDispatcher::accelerateMetaShortcuts(const int32_t deviceId, const int32_t action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004215 int32_t& keyCode, int32_t& metaState) {
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05004216 if (metaState & AMETA_META_ON && action == AKEY_EVENT_ACTION_DOWN) {
4217 int32_t newKeyCode = AKEYCODE_UNKNOWN;
Vaibhav Devmurari34cd5b02023-02-23 14:51:18 +00004218 if (keyCode == AKEYCODE_DEL || keyCode == AKEYCODE_GRAVE || keyCode == AKEYCODE_DPAD_LEFT) {
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05004219 newKeyCode = AKEYCODE_BACK;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05004220 }
4221 if (newKeyCode != AKEYCODE_UNKNOWN) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004222 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05004223 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004224 mReplacedKeys[replacement] = newKeyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05004225 keyCode = newKeyCode;
4226 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
4227 }
4228 } else if (action == AKEY_EVENT_ACTION_UP) {
4229 // In order to maintain a consistent stream of up and down events, check to see if the key
4230 // going up is one we've replaced in a down event and haven't yet replaced in an up event,
4231 // even if the modifier was released between the down and the up events.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004232 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05004233 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004234 auto replacementIt = mReplacedKeys.find(replacement);
4235 if (replacementIt != mReplacedKeys.end()) {
4236 keyCode = replacementIt->second;
4237 mReplacedKeys.erase(replacementIt);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05004238 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
4239 }
4240 }
4241}
4242
Prabir Pradhan678438e2023-04-13 19:32:51 +00004243void InputDispatcher::notifyKey(const NotifyKeyArgs& args) {
Prabir Pradhan96282b02023-02-24 22:36:17 +00004244 ALOGD_IF(debugInboundEventDetails(),
4245 "notifyKey - id=%" PRIx32 ", eventTime=%" PRId64
4246 ", deviceId=%d, source=%s, displayId=%" PRId32
4247 "policyFlags=0x%x, action=%s, flags=0x%x, keyCode=%s, scanCode=0x%x, metaState=0x%x, "
4248 "downTime=%" PRId64,
Prabir Pradhan678438e2023-04-13 19:32:51 +00004249 args.id, args.eventTime, args.deviceId, inputEventSourceToString(args.source).c_str(),
4250 args.displayId, args.policyFlags, KeyEvent::actionToString(args.action), args.flags,
4251 KeyEvent::getLabel(args.keyCode), args.scanCode, args.metaState, args.downTime);
Siarhei Vishniakou6773db62023-04-21 11:30:20 -07004252 Result<void> keyCheck = validateKeyEvent(args.action);
4253 if (!keyCheck.ok()) {
4254 LOG(ERROR) << "invalid key event: " << keyCheck.error();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004255 return;
4256 }
4257
Prabir Pradhan678438e2023-04-13 19:32:51 +00004258 uint32_t policyFlags = args.policyFlags;
4259 int32_t flags = args.flags;
4260 int32_t metaState = args.metaState;
Siarhei Vishniakou622bd322018-10-29 18:02:27 -07004261 // InputDispatcher tracks and generates key repeats on behalf of
4262 // whatever notifies it, so repeatCount should always be set to 0
4263 constexpr int32_t repeatCount = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004264 if ((policyFlags & POLICY_FLAG_VIRTUAL) || (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY)) {
4265 policyFlags |= POLICY_FLAG_VIRTUAL;
4266 flags |= AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
4267 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004268 if (policyFlags & POLICY_FLAG_FUNCTION) {
4269 metaState |= AMETA_FUNCTION_ON;
4270 }
4271
4272 policyFlags |= POLICY_FLAG_TRUSTED;
4273
Prabir Pradhan678438e2023-04-13 19:32:51 +00004274 int32_t keyCode = args.keyCode;
4275 accelerateMetaShortcuts(args.deviceId, args.action, keyCode, metaState);
Michael Wright78f24442014-08-06 15:55:28 -07004276
Michael Wrightd02c5b62014-02-10 15:10:22 -08004277 KeyEvent event;
Prabir Pradhan678438e2023-04-13 19:32:51 +00004278 event.initialize(args.id, args.deviceId, args.source, args.displayId, INVALID_HMAC, args.action,
4279 flags, keyCode, args.scanCode, metaState, repeatCount, args.downTime,
4280 args.eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004281
Michael Wright2b3c3302018-03-02 17:19:13 +00004282 android::base::Timer t;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004283 mPolicy.interceptKeyBeforeQueueing(event, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00004284 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4285 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004286 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00004287 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004288
Antonio Kantekf16f2832021-09-28 04:39:20 +00004289 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004290 { // acquire lock
4291 mLock.lock();
4292
4293 if (shouldSendKeyToInputFilterLocked(args)) {
4294 mLock.unlock();
4295
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004296 policyFlags |= POLICY_FLAG_FILTERED;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004297 if (!mPolicy.filterInputEvent(event, policyFlags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004298 return; // event was consumed by the filter
4299 }
4300
4301 mLock.lock();
4302 }
4303
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004304 std::unique_ptr<KeyEntry> newEntry =
Prabir Pradhan678438e2023-04-13 19:32:51 +00004305 std::make_unique<KeyEntry>(args.id, args.eventTime, args.deviceId, args.source,
4306 args.displayId, policyFlags, args.action, flags, keyCode,
4307 args.scanCode, metaState, repeatCount, args.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004308
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004309 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004310 mLock.unlock();
4311 } // release lock
4312
4313 if (needWake) {
4314 mLooper->wake();
4315 }
4316}
4317
Prabir Pradhan678438e2023-04-13 19:32:51 +00004318bool InputDispatcher::shouldSendKeyToInputFilterLocked(const NotifyKeyArgs& args) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004319 return mInputFilterEnabled;
4320}
4321
Prabir Pradhan678438e2023-04-13 19:32:51 +00004322void InputDispatcher::notifyMotion(const NotifyMotionArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004323 if (debugInboundEventDetails()) {
Prabir Pradhan96282b02023-02-24 22:36:17 +00004324 ALOGD("notifyMotion - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=%s, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004325 "displayId=%" PRId32 ", policyFlags=0x%x, "
Siarhei Vishniakou6ebd0692022-10-20 15:05:45 -07004326 "action=%s, actionButton=0x%x, flags=0x%x, metaState=0x%x, buttonState=0x%x, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004327 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, xCursorPosition=%f, "
4328 "yCursorPosition=%f, downTime=%" PRId64,
Prabir Pradhan678438e2023-04-13 19:32:51 +00004329 args.id, args.eventTime, args.deviceId, inputEventSourceToString(args.source).c_str(),
4330 args.displayId, args.policyFlags, MotionEvent::actionToString(args.action).c_str(),
4331 args.actionButton, args.flags, args.metaState, args.buttonState, args.edgeFlags,
4332 args.xPrecision, args.yPrecision, args.xCursorPosition, args.yCursorPosition,
4333 args.downTime);
4334 for (uint32_t i = 0; i < args.pointerCount; i++) {
Prabir Pradhan96282b02023-02-24 22:36:17 +00004335 ALOGD(" Pointer %d: id=%d, toolType=%s, x=%f, y=%f, pressure=%f, size=%f, "
4336 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, orientation=%f",
Prabir Pradhan678438e2023-04-13 19:32:51 +00004337 i, args.pointerProperties[i].id,
4338 ftl::enum_string(args.pointerProperties[i].toolType).c_str(),
4339 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
4340 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
4341 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
4342 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
4343 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
4344 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
4345 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
4346 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
4347 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004348 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004349 }
Siarhei Vishniakou4ca97272023-03-01 11:31:35 -08004350
Siarhei Vishniakou6773db62023-04-21 11:30:20 -07004351 Result<void> motionCheck = validateMotionEvent(args.action, args.actionButton,
4352 args.pointerCount, args.pointerProperties);
4353 if (!motionCheck.ok()) {
4354 LOG(ERROR) << "Invalid event: " << args.dump() << "; reason: " << motionCheck.error();
Siarhei Vishniakou4ca97272023-03-01 11:31:35 -08004355 return;
4356 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004357
Prabir Pradhan678438e2023-04-13 19:32:51 +00004358 uint32_t policyFlags = args.policyFlags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004359 policyFlags |= POLICY_FLAG_TRUSTED;
Michael Wright2b3c3302018-03-02 17:19:13 +00004360
4361 android::base::Timer t;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004362 mPolicy.interceptMotionBeforeQueueing(args.displayId, args.eventTime, policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00004363 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4364 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004365 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00004366 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004367
Antonio Kantekf16f2832021-09-28 04:39:20 +00004368 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004369 { // acquire lock
4370 mLock.lock();
Siarhei Vishniakou5bf25d92023-02-08 15:43:38 -08004371 if (!(policyFlags & POLICY_FLAG_PASS_TO_USER)) {
4372 // Set the flag anyway if we already have an ongoing gesture. That would allow us to
4373 // complete the processing of the current stroke.
Prabir Pradhan678438e2023-04-13 19:32:51 +00004374 const auto touchStateIt = mTouchStatesByDisplay.find(args.displayId);
Siarhei Vishniakou5bf25d92023-02-08 15:43:38 -08004375 if (touchStateIt != mTouchStatesByDisplay.end()) {
4376 const TouchState& touchState = touchStateIt->second;
Prabir Pradhan678438e2023-04-13 19:32:51 +00004377 if (touchState.deviceId == args.deviceId && touchState.isDown()) {
Siarhei Vishniakou5bf25d92023-02-08 15:43:38 -08004378 policyFlags |= POLICY_FLAG_PASS_TO_USER;
4379 }
4380 }
4381 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004382
4383 if (shouldSendMotionToInputFilterLocked(args)) {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004384 ui::Transform displayTransform;
Prabir Pradhan678438e2023-04-13 19:32:51 +00004385 if (const auto it = mDisplayInfos.find(args.displayId); it != mDisplayInfos.end()) {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004386 displayTransform = it->second.transform;
4387 }
4388
Michael Wrightd02c5b62014-02-10 15:10:22 -08004389 mLock.unlock();
4390
4391 MotionEvent event;
Prabir Pradhan678438e2023-04-13 19:32:51 +00004392 event.initialize(args.id, args.deviceId, args.source, args.displayId, INVALID_HMAC,
4393 args.action, args.actionButton, args.flags, args.edgeFlags,
4394 args.metaState, args.buttonState, args.classification,
4395 displayTransform, args.xPrecision, args.yPrecision,
4396 args.xCursorPosition, args.yCursorPosition, displayTransform,
4397 args.downTime, args.eventTime, args.pointerCount,
4398 args.pointerProperties, args.pointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004399
4400 policyFlags |= POLICY_FLAG_FILTERED;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004401 if (!mPolicy.filterInputEvent(event, policyFlags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004402 return; // event was consumed by the filter
4403 }
4404
4405 mLock.lock();
4406 }
4407
4408 // Just enqueue a new motion event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004409 std::unique_ptr<MotionEntry> newEntry =
Prabir Pradhan678438e2023-04-13 19:32:51 +00004410 std::make_unique<MotionEntry>(args.id, args.eventTime, args.deviceId, args.source,
4411 args.displayId, policyFlags, args.action,
4412 args.actionButton, args.flags, args.metaState,
4413 args.buttonState, args.classification, args.edgeFlags,
4414 args.xPrecision, args.yPrecision,
4415 args.xCursorPosition, args.yCursorPosition,
4416 args.downTime, args.pointerCount,
4417 args.pointerProperties, args.pointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004418
Prabir Pradhan678438e2023-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 Pradhan678438e2023-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 Pradhan678438e2023-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 Pradhan678438e2023-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 Pradhan678438e2023-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 Pradhan678438e2023-04-13 19:32:51 +00004462void InputDispatcher::notifyVibratorState(const NotifyVibratorStateArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004463 if (debugInboundEventDetails()) {
Prabir Pradhan678438e2023-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 Pradhan678438e2023-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 Pradhan678438e2023-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 Pradhan678438e2023-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 Pradhan678438e2023-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 Pradhan678438e2023-04-13 19:32:51 +00004486void InputDispatcher::notifyDeviceReset(const NotifyDeviceResetArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004487 if (debugInboundEventDetails()) {
Prabir Pradhan678438e2023-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 Pradhan678438e2023-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));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004499 } // release lock
4500
4501 if (needWake) {
4502 mLooper->wake();
4503 }
4504}
4505
Prabir Pradhan678438e2023-04-13 19:32:51 +00004506void InputDispatcher::notifyPointerCaptureChanged(const NotifyPointerCaptureChangedArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004507 if (debugInboundEventDetails()) {
Prabir Pradhan678438e2023-04-13 19:32:51 +00004508 ALOGD("notifyPointerCaptureChanged - eventTime=%" PRId64 ", enabled=%s", args.eventTime,
4509 args.request.enable ? "true" : "false");
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004510 }
Prabir Pradhan7e186182020-11-10 13:56:45 -08004511
Antonio Kantekf16f2832021-09-28 04:39:20 +00004512 bool needWake = false;
Prabir Pradhan99987712020-11-10 18:43:05 -08004513 { // acquire lock
4514 std::scoped_lock _l(mLock);
Prabir Pradhan678438e2023-04-13 19:32:51 +00004515 auto entry =
4516 std::make_unique<PointerCaptureChangedEntry>(args.id, args.eventTime, args.request);
Prabir Pradhan99987712020-11-10 18:43:05 -08004517 needWake = enqueueInboundEventLocked(std::move(entry));
4518 } // release lock
4519
4520 if (needWake) {
4521 mLooper->wake();
4522 }
Prabir Pradhan7e186182020-11-10 13:56:45 -08004523}
4524
Prabir Pradhan5735a322022-04-11 17:23:34 +00004525InputEventInjectionResult InputDispatcher::injectInputEvent(const InputEvent* event,
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00004526 std::optional<gui::Uid> targetUid,
Prabir Pradhan5735a322022-04-11 17:23:34 +00004527 InputEventInjectionSync syncMode,
4528 std::chrono::milliseconds timeout,
4529 uint32_t policyFlags) {
Siarhei Vishniakou6773db62023-04-21 11:30:20 -07004530 Result<void> eventValidation = validateInputEvent(*event);
4531 if (!eventValidation.ok()) {
4532 LOG(INFO) << "Injection failed: invalid event: " << eventValidation.error();
4533 return InputEventInjectionResult::FAILED;
4534 }
4535
Prabir Pradhan65613802023-02-22 23:36:58 +00004536 if (debugInboundEventDetails()) {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00004537 LOG(DEBUG) << __func__ << ": targetUid=" << toString(targetUid, &uidString)
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004538 << ", syncMode=" << ftl::enum_string(syncMode) << ", timeout=" << timeout.count()
4539 << "ms, policyFlags=0x" << std::hex << policyFlags << std::dec
4540 << ", event=" << *event;
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004541 }
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07004542 nsecs_t endTime = now() + std::chrono::duration_cast<std::chrono::nanoseconds>(timeout).count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004543
Prabir Pradhan5735a322022-04-11 17:23:34 +00004544 policyFlags |= POLICY_FLAG_INJECTED | POLICY_FLAG_TRUSTED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004545
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004546 // For all injected events, set device id = VIRTUAL_KEYBOARD_ID. The only exception is events
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004547 // that have gone through the InputFilter. If the event passed through the InputFilter, assign
4548 // the provided device id. If the InputFilter is accessibility, and it modifies or synthesizes
4549 // the injected event, it is responsible for setting POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY.
4550 // For those events, we will set FLAG_IS_ACCESSIBILITY_EVENT to allow apps to distinguish them
4551 // from events that originate from actual hardware.
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004552 int32_t resolvedDeviceId = VIRTUAL_KEYBOARD_ID;
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004553 if (policyFlags & POLICY_FLAG_FILTERED) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004554 resolvedDeviceId = event->getDeviceId();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004555 }
4556
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004557 std::queue<std::unique_ptr<EventEntry>> injectedEntries;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004558 switch (event->getType()) {
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004559 case InputEventType::KEY: {
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004560 const KeyEvent& incomingKey = static_cast<const KeyEvent&>(*event);
Siarhei Vishniakou6773db62023-04-21 11:30:20 -07004561 const int32_t action = incomingKey.getAction();
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004562 int32_t flags = incomingKey.getFlags();
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004563 if (policyFlags & POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY) {
4564 flags |= AKEY_EVENT_FLAG_IS_ACCESSIBILITY_EVENT;
4565 }
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004566 int32_t keyCode = incomingKey.getKeyCode();
4567 int32_t metaState = incomingKey.getMetaState();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004568 accelerateMetaShortcuts(resolvedDeviceId, action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004569 /*byref*/ keyCode, /*byref*/ metaState);
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004570 KeyEvent keyEvent;
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004571 keyEvent.initialize(incomingKey.getId(), resolvedDeviceId, incomingKey.getSource(),
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004572 incomingKey.getDisplayId(), INVALID_HMAC, action, flags, keyCode,
4573 incomingKey.getScanCode(), metaState, incomingKey.getRepeatCount(),
4574 incomingKey.getDownTime(), incomingKey.getEventTime());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004575
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004576 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
4577 policyFlags |= POLICY_FLAG_VIRTUAL;
Michael Wright2b3c3302018-03-02 17:19:13 +00004578 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004579
4580 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
4581 android::base::Timer t;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004582 mPolicy.interceptKeyBeforeQueueing(keyEvent, /*byref*/ policyFlags);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004583 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4584 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
4585 std::to_string(t.duration().count()).c_str());
4586 }
4587 }
4588
4589 mLock.lock();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004590 std::unique_ptr<KeyEntry> injectedEntry =
4591 std::make_unique<KeyEntry>(incomingKey.getId(), incomingKey.getEventTime(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004592 resolvedDeviceId, incomingKey.getSource(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004593 incomingKey.getDisplayId(), policyFlags, action,
4594 flags, keyCode, incomingKey.getScanCode(), metaState,
4595 incomingKey.getRepeatCount(),
4596 incomingKey.getDownTime());
4597 injectedEntries.push(std::move(injectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004598 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004599 }
4600
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004601 case InputEventType::MOTION: {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004602 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(*event);
Prabir Pradhanaa561d12021-09-24 06:57:33 -07004603 const bool isPointerEvent =
4604 isFromSource(event->getSource(), AINPUT_SOURCE_CLASS_POINTER);
4605 // If a pointer event has no displayId specified, inject it to the default display.
4606 const uint32_t displayId = isPointerEvent && (event->getDisplayId() == ADISPLAY_ID_NONE)
4607 ? ADISPLAY_ID_DEFAULT
4608 : event->getDisplayId();
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004609 int32_t flags = motionEvent.getFlags();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004610
4611 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004612 nsecs_t eventTime = motionEvent.getEventTime();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004613 android::base::Timer t;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004614 mPolicy.interceptMotionBeforeQueueing(displayId, eventTime, /*byref*/ policyFlags);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004615 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4616 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
4617 std::to_string(t.duration().count()).c_str());
4618 }
4619 }
4620
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004621 if (policyFlags & POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY) {
4622 flags |= AMOTION_EVENT_FLAG_IS_ACCESSIBILITY_EVENT;
4623 }
4624
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004625 mLock.lock();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004626 const nsecs_t* sampleEventTimes = motionEvent.getSampleEventTimes();
4627 const PointerCoords* samplePointerCoords = motionEvent.getSamplePointerCoords();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004628 std::unique_ptr<MotionEntry> injectedEntry =
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004629 std::make_unique<MotionEntry>(motionEvent.getId(), *sampleEventTimes,
4630 resolvedDeviceId, motionEvent.getSource(),
Siarhei Vishniakou6773db62023-04-21 11:30:20 -07004631 displayId, policyFlags, motionEvent.getAction(),
4632 motionEvent.getActionButton(), flags,
4633 motionEvent.getMetaState(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004634 motionEvent.getButtonState(),
4635 motionEvent.getClassification(),
4636 motionEvent.getEdgeFlags(),
4637 motionEvent.getXPrecision(),
4638 motionEvent.getYPrecision(),
4639 motionEvent.getRawXCursorPosition(),
4640 motionEvent.getRawYCursorPosition(),
Siarhei Vishniakou6773db62023-04-21 11:30:20 -07004641 motionEvent.getDownTime(),
4642 motionEvent.getPointerCount(),
4643 motionEvent.getPointerProperties(),
4644 samplePointerCoords);
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004645 transformMotionEntryForInjectionLocked(*injectedEntry, motionEvent.getTransform());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004646 injectedEntries.push(std::move(injectedEntry));
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004647 for (size_t i = motionEvent.getHistorySize(); i > 0; i--) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004648 sampleEventTimes += 1;
Siarhei Vishniakou6773db62023-04-21 11:30:20 -07004649 samplePointerCoords += motionEvent.getPointerCount();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004650 std::unique_ptr<MotionEntry> nextInjectedEntry =
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004651 std::make_unique<MotionEntry>(motionEvent.getId(), *sampleEventTimes,
4652 resolvedDeviceId, motionEvent.getSource(),
Siarhei Vishniakou6773db62023-04-21 11:30:20 -07004653 displayId, policyFlags,
4654 motionEvent.getAction(),
4655 motionEvent.getActionButton(), flags,
4656 motionEvent.getMetaState(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004657 motionEvent.getButtonState(),
4658 motionEvent.getClassification(),
4659 motionEvent.getEdgeFlags(),
4660 motionEvent.getXPrecision(),
4661 motionEvent.getYPrecision(),
4662 motionEvent.getRawXCursorPosition(),
4663 motionEvent.getRawYCursorPosition(),
4664 motionEvent.getDownTime(),
Siarhei Vishniakou6773db62023-04-21 11:30:20 -07004665 motionEvent.getPointerCount(),
4666 motionEvent.getPointerProperties(),
Prabir Pradhan5beda762021-12-10 09:30:08 +00004667 samplePointerCoords);
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004668 transformMotionEntryForInjectionLocked(*nextInjectedEntry,
4669 motionEvent.getTransform());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004670 injectedEntries.push(std::move(nextInjectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004671 }
4672 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004673 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004674
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004675 default:
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004676 LOG(WARNING) << "Cannot inject " << ftl::enum_string(event->getType()) << " events";
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004677 return InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004678 }
4679
Prabir Pradhan5735a322022-04-11 17:23:34 +00004680 InjectionState* injectionState = new InjectionState(targetUid);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004681 if (syncMode == InputEventInjectionSync::NONE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004682 injectionState->injectionIsAsync = true;
4683 }
4684
4685 injectionState->refCount += 1;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004686 injectedEntries.back()->injectionState = injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004687
4688 bool needWake = false;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004689 while (!injectedEntries.empty()) {
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08004690 if (DEBUG_INJECTION) {
4691 LOG(DEBUG) << "Injecting " << injectedEntries.front()->getDescription();
4692 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004693 needWake |= enqueueInboundEventLocked(std::move(injectedEntries.front()));
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004694 injectedEntries.pop();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004695 }
4696
4697 mLock.unlock();
4698
4699 if (needWake) {
4700 mLooper->wake();
4701 }
4702
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004703 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004704 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004705 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004706
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004707 if (syncMode == InputEventInjectionSync::NONE) {
4708 injectionResult = InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004709 } else {
4710 for (;;) {
4711 injectionResult = injectionState->injectionResult;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004712 if (injectionResult != InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004713 break;
4714 }
4715
4716 nsecs_t remainingTimeout = endTime - now();
4717 if (remainingTimeout <= 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004718 if (DEBUG_INJECTION) {
4719 ALOGD("injectInputEvent - Timed out waiting for injection result "
4720 "to become available.");
4721 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004722 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004723 break;
4724 }
4725
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004726 mInjectionResultAvailable.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004727 }
4728
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004729 if (injectionResult == InputEventInjectionResult::SUCCEEDED &&
4730 syncMode == InputEventInjectionSync::WAIT_FOR_FINISHED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004731 while (injectionState->pendingForegroundDispatches != 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004732 if (DEBUG_INJECTION) {
4733 ALOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
4734 injectionState->pendingForegroundDispatches);
4735 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004736 nsecs_t remainingTimeout = endTime - now();
4737 if (remainingTimeout <= 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004738 if (DEBUG_INJECTION) {
4739 ALOGD("injectInputEvent - Timed out waiting for pending foreground "
4740 "dispatches to finish.");
4741 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004742 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004743 break;
4744 }
4745
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004746 mInjectionSyncFinished.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004747 }
4748 }
4749 }
4750
4751 injectionState->release();
4752 } // release lock
4753
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004754 if (DEBUG_INJECTION) {
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08004755 LOG(DEBUG) << "injectInputEvent - Finished with result "
4756 << ftl::enum_string(injectionResult);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004757 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004758
4759 return injectionResult;
4760}
4761
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004762std::unique_ptr<VerifiedInputEvent> InputDispatcher::verifyInputEvent(const InputEvent& event) {
Gang Wange9087892020-01-07 12:17:14 -05004763 std::array<uint8_t, 32> calculatedHmac;
4764 std::unique_ptr<VerifiedInputEvent> result;
4765 switch (event.getType()) {
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004766 case InputEventType::KEY: {
Gang Wange9087892020-01-07 12:17:14 -05004767 const KeyEvent& keyEvent = static_cast<const KeyEvent&>(event);
4768 VerifiedKeyEvent verifiedKeyEvent = verifiedKeyEventFromKeyEvent(keyEvent);
4769 result = std::make_unique<VerifiedKeyEvent>(verifiedKeyEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004770 calculatedHmac = sign(verifiedKeyEvent);
Gang Wange9087892020-01-07 12:17:14 -05004771 break;
4772 }
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004773 case InputEventType::MOTION: {
Gang Wange9087892020-01-07 12:17:14 -05004774 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(event);
4775 VerifiedMotionEvent verifiedMotionEvent =
4776 verifiedMotionEventFromMotionEvent(motionEvent);
4777 result = std::make_unique<VerifiedMotionEvent>(verifiedMotionEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004778 calculatedHmac = sign(verifiedMotionEvent);
Gang Wange9087892020-01-07 12:17:14 -05004779 break;
4780 }
4781 default: {
4782 ALOGE("Cannot verify events of type %" PRId32, event.getType());
4783 return nullptr;
4784 }
4785 }
4786 if (calculatedHmac == INVALID_HMAC) {
4787 return nullptr;
4788 }
tyiu1573a672023-02-21 22:38:32 +00004789 if (0 != CRYPTO_memcmp(calculatedHmac.data(), event.getHmac().data(), calculatedHmac.size())) {
Gang Wange9087892020-01-07 12:17:14 -05004790 return nullptr;
4791 }
4792 return result;
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004793}
4794
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004795void InputDispatcher::setInjectionResult(EventEntry& entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004796 InputEventInjectionResult injectionResult) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004797 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004798 if (injectionState) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004799 if (DEBUG_INJECTION) {
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08004800 LOG(DEBUG) << "Setting input event injection result to "
4801 << ftl::enum_string(injectionResult);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004802 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004803
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004804 if (injectionState->injectionIsAsync && !(entry.policyFlags & POLICY_FLAG_FILTERED)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004805 // Log the outcome since the injector did not wait for the injection result.
4806 switch (injectionResult) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004807 case InputEventInjectionResult::SUCCEEDED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004808 ALOGV("Asynchronous input event injection succeeded.");
4809 break;
Prabir Pradhan5735a322022-04-11 17:23:34 +00004810 case InputEventInjectionResult::TARGET_MISMATCH:
4811 ALOGV("Asynchronous input event injection target mismatch.");
4812 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004813 case InputEventInjectionResult::FAILED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004814 ALOGW("Asynchronous input event injection failed.");
4815 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004816 case InputEventInjectionResult::TIMED_OUT:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004817 ALOGW("Asynchronous input event injection timed out.");
4818 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004819 case InputEventInjectionResult::PENDING:
4820 ALOGE("Setting result to 'PENDING' for asynchronous injection");
4821 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004822 }
4823 }
4824
4825 injectionState->injectionResult = injectionResult;
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004826 mInjectionResultAvailable.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004827 }
4828}
4829
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004830void InputDispatcher::transformMotionEntryForInjectionLocked(
4831 MotionEntry& entry, const ui::Transform& injectedTransform) const {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004832 // Input injection works in the logical display coordinate space, but the input pipeline works
4833 // display space, so we need to transform the injected events accordingly.
4834 const auto it = mDisplayInfos.find(entry.displayId);
4835 if (it == mDisplayInfos.end()) return;
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004836 const auto& transformToDisplay = it->second.transform.inverse() * injectedTransform;
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004837
Prabir Pradhand9a2ebe2022-07-20 19:25:13 +00004838 if (entry.xCursorPosition != AMOTION_EVENT_INVALID_CURSOR_POSITION &&
4839 entry.yCursorPosition != AMOTION_EVENT_INVALID_CURSOR_POSITION) {
4840 const vec2 cursor =
4841 MotionEvent::calculateTransformedXY(entry.source, transformToDisplay,
4842 {entry.xCursorPosition, entry.yCursorPosition});
4843 entry.xCursorPosition = cursor.x;
4844 entry.yCursorPosition = cursor.y;
4845 }
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004846 for (uint32_t i = 0; i < entry.pointerCount; i++) {
Prabir Pradhan8e6ce222022-02-24 09:08:54 -08004847 entry.pointerCoords[i] =
4848 MotionEvent::calculateTransformedCoords(entry.source, transformToDisplay,
4849 entry.pointerCoords[i]);
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004850 }
4851}
4852
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004853void InputDispatcher::incrementPendingForegroundDispatches(EventEntry& entry) {
4854 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004855 if (injectionState) {
4856 injectionState->pendingForegroundDispatches += 1;
4857 }
4858}
4859
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004860void InputDispatcher::decrementPendingForegroundDispatches(EventEntry& entry) {
4861 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004862 if (injectionState) {
4863 injectionState->pendingForegroundDispatches -= 1;
4864
4865 if (injectionState->pendingForegroundDispatches == 0) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004866 mInjectionSyncFinished.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004867 }
4868 }
4869}
4870
chaviw98318de2021-05-19 16:45:23 -05004871const std::vector<sp<WindowInfoHandle>>& InputDispatcher::getWindowHandlesLocked(
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004872 int32_t displayId) const {
chaviw98318de2021-05-19 16:45:23 -05004873 static const std::vector<sp<WindowInfoHandle>> EMPTY_WINDOW_HANDLES;
Vishnu Nairad321cd2020-08-20 16:40:21 -07004874 auto it = mWindowHandlesByDisplay.find(displayId);
4875 return it != mWindowHandlesByDisplay.end() ? it->second : EMPTY_WINDOW_HANDLES;
Arthur Hungb92218b2018-08-14 12:00:21 +08004876}
4877
chaviw98318de2021-05-19 16:45:23 -05004878sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(
chaviwfbe5d9c2018-12-26 12:23:37 -08004879 const sp<IBinder>& windowHandleToken) const {
arthurhungbe737672020-06-24 12:29:21 +08004880 if (windowHandleToken == nullptr) {
4881 return nullptr;
4882 }
4883
Arthur Hungb92218b2018-08-14 12:00:21 +08004884 for (auto& it : mWindowHandlesByDisplay) {
chaviw98318de2021-05-19 16:45:23 -05004885 const std::vector<sp<WindowInfoHandle>>& windowHandles = it.second;
4886 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
chaviwfbe5d9c2018-12-26 12:23:37 -08004887 if (windowHandle->getToken() == windowHandleToken) {
Arthur Hungb92218b2018-08-14 12:00:21 +08004888 return windowHandle;
4889 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004890 }
4891 }
Yi Kong9b14ac62018-07-17 13:48:38 -07004892 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004893}
4894
chaviw98318de2021-05-19 16:45:23 -05004895sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(const sp<IBinder>& windowHandleToken,
4896 int displayId) const {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004897 if (windowHandleToken == nullptr) {
4898 return nullptr;
4899 }
4900
chaviw98318de2021-05-19 16:45:23 -05004901 for (const sp<WindowInfoHandle>& windowHandle : getWindowHandlesLocked(displayId)) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004902 if (windowHandle->getToken() == windowHandleToken) {
4903 return windowHandle;
4904 }
4905 }
4906 return nullptr;
4907}
4908
chaviw98318de2021-05-19 16:45:23 -05004909sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(
4910 const sp<WindowInfoHandle>& windowHandle) const {
Mady Mellor017bcd12020-06-23 19:12:00 +00004911 for (auto& it : mWindowHandlesByDisplay) {
chaviw98318de2021-05-19 16:45:23 -05004912 const std::vector<sp<WindowInfoHandle>>& windowHandles = it.second;
4913 for (const sp<WindowInfoHandle>& handle : windowHandles) {
arthurhungbe737672020-06-24 12:29:21 +08004914 if (handle->getId() == windowHandle->getId() &&
4915 handle->getToken() == windowHandle->getToken()) {
Mady Mellor017bcd12020-06-23 19:12:00 +00004916 if (windowHandle->getInfo()->displayId != it.first) {
4917 ALOGE("Found window %s in display %" PRId32
4918 ", but it should belong to display %" PRId32,
4919 windowHandle->getName().c_str(), it.first,
4920 windowHandle->getInfo()->displayId);
4921 }
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004922 return handle;
Arthur Hungb92218b2018-08-14 12:00:21 +08004923 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004924 }
4925 }
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004926 return nullptr;
4927}
4928
chaviw98318de2021-05-19 16:45:23 -05004929sp<WindowInfoHandle> InputDispatcher::getFocusedWindowHandleLocked(int displayId) const {
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004930 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(displayId);
4931 return getWindowHandleLocked(focusedToken, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004932}
4933
Prabir Pradhan33e3baa2022-12-06 20:30:22 +00004934ui::Transform InputDispatcher::getTransformLocked(int32_t displayId) const {
4935 auto displayInfoIt = mDisplayInfos.find(displayId);
4936 return displayInfoIt != mDisplayInfos.end() ? displayInfoIt->second.transform
4937 : kIdentityTransform;
4938}
4939
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004940bool InputDispatcher::canWindowReceiveMotionLocked(const sp<WindowInfoHandle>& window,
4941 const MotionEntry& motionEntry) const {
4942 const WindowInfo& info = *window->getInfo();
4943
4944 // Skip spy window targets that are not valid for targeted injection.
4945 if (const auto err = verifyTargetedInjection(window, motionEntry); err) {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004946 return false;
4947 }
4948
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004949 if (info.inputConfig.test(WindowInfo::InputConfig::PAUSE_DISPATCHING)) {
4950 ALOGI("Not sending touch event to %s because it is paused", window->getName().c_str());
4951 return false;
4952 }
4953
4954 if (info.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL)) {
4955 ALOGW("Not sending touch gesture to %s because it has config NO_INPUT_CHANNEL",
4956 window->getName().c_str());
4957 return false;
4958 }
4959
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07004960 std::shared_ptr<Connection> connection = getConnectionLocked(window->getToken());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004961 if (connection == nullptr) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004962 ALOGW("Not sending touch to %s because there's no corresponding connection",
4963 window->getName().c_str());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004964 return false;
4965 }
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004966
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004967 if (!connection->responsive) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004968 ALOGW("Not sending touch to %s because it is not responsive", window->getName().c_str());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004969 return false;
4970 }
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004971
4972 // Drop events that can't be trusted due to occlusion
4973 const auto [x, y] = resolveTouchedPosition(motionEntry);
4974 TouchOcclusionInfo occlusionInfo = computeTouchOcclusionInfoLocked(window, x, y);
4975 if (!isTouchTrustedLocked(occlusionInfo)) {
4976 if (DEBUG_TOUCH_OCCLUSION) {
Prabir Pradhan82e081e2022-12-06 09:50:09 +00004977 ALOGD("Stack of obscuring windows during untrusted touch (%.1f, %.1f):", x, y);
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004978 for (const auto& log : occlusionInfo.debugInfo) {
4979 ALOGD("%s", log.c_str());
4980 }
4981 }
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00004982 ALOGW("Dropping untrusted touch event due to %s/%s", occlusionInfo.obscuringPackage.c_str(),
4983 occlusionInfo.obscuringUid.toString().c_str());
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004984 return false;
4985 }
4986
4987 // Drop touch events if requested by input feature
4988 if (shouldDropInput(motionEntry, window)) {
4989 return false;
4990 }
4991
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004992 return true;
4993}
4994
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004995std::shared_ptr<InputChannel> InputDispatcher::getInputChannelLocked(
4996 const sp<IBinder>& token) const {
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00004997 auto connectionIt = mConnectionsByToken.find(token);
4998 if (connectionIt == mConnectionsByToken.end()) {
Robert Carr5c8a0262018-10-03 16:30:44 -07004999 return nullptr;
5000 }
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005001 return connectionIt->second->inputChannel;
Robert Carr5c8a0262018-10-03 16:30:44 -07005002}
5003
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005004void InputDispatcher::updateWindowHandlesForDisplayLocked(
chaviw98318de2021-05-19 16:45:23 -05005005 const std::vector<sp<WindowInfoHandle>>& windowInfoHandles, int32_t displayId) {
5006 if (windowInfoHandles.empty()) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005007 // Remove all handles on a display if there are no windows left.
5008 mWindowHandlesByDisplay.erase(displayId);
5009 return;
5010 }
5011
5012 // Since we compare the pointer of input window handles across window updates, we need
5013 // to make sure the handle object for the same window stays unchanged across updates.
chaviw98318de2021-05-19 16:45:23 -05005014 const std::vector<sp<WindowInfoHandle>>& oldHandles = getWindowHandlesLocked(displayId);
5015 std::unordered_map<int32_t /*id*/, sp<WindowInfoHandle>> oldHandlesById;
5016 for (const sp<WindowInfoHandle>& handle : oldHandles) {
chaviwaf87b3e2019-10-01 16:59:28 -07005017 oldHandlesById[handle->getId()] = handle;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005018 }
5019
chaviw98318de2021-05-19 16:45:23 -05005020 std::vector<sp<WindowInfoHandle>> newHandles;
5021 for (const sp<WindowInfoHandle>& handle : windowInfoHandles) {
chaviw98318de2021-05-19 16:45:23 -05005022 const WindowInfo* info = handle->getInfo();
Siarhei Vishniakou64452932020-11-06 17:51:32 -06005023 if (getInputChannelLocked(handle->getToken()) == nullptr) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005024 const bool noInputChannel =
Prabir Pradhan51e7db02022-02-07 06:02:57 -08005025 info->inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005026 const bool canReceiveInput =
5027 !info->inputConfig.test(WindowInfo::InputConfig::NOT_TOUCHABLE) ||
5028 !info->inputConfig.test(WindowInfo::InputConfig::NOT_FOCUSABLE);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005029 if (canReceiveInput && !noInputChannel) {
John Recke0710582019-09-26 13:46:12 -07005030 ALOGV("Window handle %s has no registered input channel",
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005031 handle->getName().c_str());
Robert Carr2984b7a2020-04-13 17:06:45 -07005032 continue;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005033 }
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005034 }
5035
5036 if (info->displayId != displayId) {
5037 ALOGE("Window %s updated by wrong display %d, should belong to display %d",
5038 handle->getName().c_str(), displayId, info->displayId);
5039 continue;
5040 }
5041
Robert Carredd13602020-04-13 17:24:34 -07005042 if ((oldHandlesById.find(handle->getId()) != oldHandlesById.end()) &&
5043 (oldHandlesById.at(handle->getId())->getToken() == handle->getToken())) {
chaviw98318de2021-05-19 16:45:23 -05005044 const sp<WindowInfoHandle>& oldHandle = oldHandlesById.at(handle->getId());
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005045 oldHandle->updateFrom(handle);
5046 newHandles.push_back(oldHandle);
5047 } else {
5048 newHandles.push_back(handle);
5049 }
5050 }
5051
5052 // Insert or replace
5053 mWindowHandlesByDisplay[displayId] = newHandles;
5054}
5055
Arthur Hung72d8dc32020-03-28 00:48:39 +00005056void InputDispatcher::setInputWindows(
chaviw98318de2021-05-19 16:45:23 -05005057 const std::unordered_map<int32_t, std::vector<sp<WindowInfoHandle>>>& handlesPerDisplay) {
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005058 // TODO(b/198444055): Remove setInputWindows from InputDispatcher.
Arthur Hung72d8dc32020-03-28 00:48:39 +00005059 { // acquire lock
5060 std::scoped_lock _l(mLock);
Siarhei Vishniakou2508b872020-12-03 16:33:53 -10005061 for (const auto& [displayId, handles] : handlesPerDisplay) {
5062 setInputWindowsLocked(handles, displayId);
Arthur Hung72d8dc32020-03-28 00:48:39 +00005063 }
5064 }
5065 // Wake up poll loop since it may need to make new input dispatching choices.
5066 mLooper->wake();
5067}
5068
Arthur Hungb92218b2018-08-14 12:00:21 +08005069/**
5070 * Called from InputManagerService, update window handle list by displayId that can receive input.
5071 * A window handle contains information about InputChannel, Touch Region, Types, Focused,...
5072 * If set an empty list, remove all handles from the specific display.
5073 * For focused handle, check if need to change and send a cancel event to previous one.
5074 * For removed handle, check if need to send a cancel event if already in touch.
5075 */
Arthur Hung72d8dc32020-03-28 00:48:39 +00005076void InputDispatcher::setInputWindowsLocked(
chaviw98318de2021-05-19 16:45:23 -05005077 const std::vector<sp<WindowInfoHandle>>& windowInfoHandles, int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005078 if (DEBUG_FOCUS) {
5079 std::string windowList;
chaviw98318de2021-05-19 16:45:23 -05005080 for (const sp<WindowInfoHandle>& iwh : windowInfoHandles) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005081 windowList += iwh->getName() + " ";
5082 }
5083 ALOGD("setInputWindows displayId=%" PRId32 " %s", displayId, windowList.c_str());
5084 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005085
Prabir Pradhand65552b2021-10-07 11:23:50 -07005086 // Check preconditions for new input windows
chaviw98318de2021-05-19 16:45:23 -05005087 for (const sp<WindowInfoHandle>& window : windowInfoHandles) {
Prabir Pradhand65552b2021-10-07 11:23:50 -07005088 const WindowInfo& info = *window->getInfo();
5089
5090 // Ensure all tokens are null if the window has feature NO_INPUT_CHANNEL
Prabir Pradhan51e7db02022-02-07 06:02:57 -08005091 const bool noInputWindow = info.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005092 if (noInputWindow && window->getToken() != nullptr) {
5093 ALOGE("%s has feature NO_INPUT_WINDOW, but a non-null token. Clearing",
5094 window->getName().c_str());
5095 window->releaseChannel();
5096 }
Prabir Pradhand65552b2021-10-07 11:23:50 -07005097
Prabir Pradhan5c85e052021-12-22 02:27:12 -08005098 // Ensure all spy windows are trusted overlays
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005099 LOG_ALWAYS_FATAL_IF(info.isSpy() &&
5100 !info.inputConfig.test(
5101 WindowInfo::InputConfig::TRUSTED_OVERLAY),
Prabir Pradhan5c85e052021-12-22 02:27:12 -08005102 "%s has feature SPY, but is not a trusted overlay.",
5103 window->getName().c_str());
5104
Prabir Pradhand65552b2021-10-07 11:23:50 -07005105 // Ensure all stylus interceptors are trusted overlays
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005106 LOG_ALWAYS_FATAL_IF(info.interceptsStylus() &&
5107 !info.inputConfig.test(
5108 WindowInfo::InputConfig::TRUSTED_OVERLAY),
Prabir Pradhand65552b2021-10-07 11:23:50 -07005109 "%s has feature INTERCEPTS_STYLUS, but is not a trusted overlay.",
5110 window->getName().c_str());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005111 }
5112
Arthur Hung72d8dc32020-03-28 00:48:39 +00005113 // Copy old handles for release if they are no longer present.
chaviw98318de2021-05-19 16:45:23 -05005114 const std::vector<sp<WindowInfoHandle>> oldWindowHandles = getWindowHandlesLocked(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005115
Prabir Pradhan93a0f912021-04-21 13:47:42 -07005116 // Save the old windows' orientation by ID before it gets updated.
5117 std::unordered_map<int32_t, uint32_t> oldWindowOrientations;
chaviw98318de2021-05-19 16:45:23 -05005118 for (const sp<WindowInfoHandle>& handle : oldWindowHandles) {
Prabir Pradhan93a0f912021-04-21 13:47:42 -07005119 oldWindowOrientations.emplace(handle->getId(),
5120 handle->getInfo()->transform.getOrientation());
5121 }
5122
chaviw98318de2021-05-19 16:45:23 -05005123 updateWindowHandlesForDisplayLocked(windowInfoHandles, displayId);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005124
chaviw98318de2021-05-19 16:45:23 -05005125 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Arthur Hung72d8dc32020-03-28 00:48:39 +00005126
Vishnu Nairc519ff72021-01-21 08:23:08 -08005127 std::optional<FocusResolver::FocusChanges> changes =
5128 mFocusResolver.setInputWindows(displayId, windowHandles);
5129 if (changes) {
5130 onFocusChangedLocked(*changes);
Arthur Hung72d8dc32020-03-28 00:48:39 +00005131 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005132
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005133 std::unordered_map<int32_t, TouchState>::iterator stateIt =
5134 mTouchStatesByDisplay.find(displayId);
5135 if (stateIt != mTouchStatesByDisplay.end()) {
5136 TouchState& state = stateIt->second;
Arthur Hung72d8dc32020-03-28 00:48:39 +00005137 for (size_t i = 0; i < state.windows.size();) {
5138 TouchedWindow& touchedWindow = state.windows[i];
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07005139 if (getWindowHandleLocked(touchedWindow.windowHandle) == nullptr) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005140 if (DEBUG_FOCUS) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00005141 ALOGD("Touched window was removed: %s in display %" PRId32,
5142 touchedWindow.windowHandle->getName().c_str(), displayId);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005143 }
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005144 std::shared_ptr<InputChannel> touchedInputChannel =
Arthur Hung72d8dc32020-03-28 00:48:39 +00005145 getInputChannelLocked(touchedWindow.windowHandle->getToken());
5146 if (touchedInputChannel != nullptr) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00005147 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
Arthur Hung72d8dc32020-03-28 00:48:39 +00005148 "touched window was removed");
5149 synthesizeCancelationEventsForInputChannelLocked(touchedInputChannel, options);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00005150 // Since we are about to drop the touch, cancel the events for the wallpaper as
5151 // well.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005152 if (touchedWindow.targetFlags.test(InputTarget::Flags::FOREGROUND) &&
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005153 touchedWindow.windowHandle->getInfo()->inputConfig.test(
5154 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER)) {
Siarhei Vishniakouca205502021-07-16 21:31:58 +00005155 sp<WindowInfoHandle> wallpaper = state.getWallpaperWindow();
Arthur Hungc539dbb2022-12-08 07:45:36 +00005156 synthesizeCancelationEventsForWindowLocked(wallpaper, options);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00005157 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005158 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00005159 state.windows.erase(state.windows.begin() + i);
5160 } else {
5161 ++i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005162 }
5163 }
arthurhungb89ccb02020-12-30 16:19:01 +08005164
arthurhung6d4bed92021-03-17 11:59:33 +08005165 // If drag window is gone, it would receive a cancel event and broadcast the DRAG_END. We
arthurhungb89ccb02020-12-30 16:19:01 +08005166 // could just clear the state here.
Arthur Hung3915c1f2022-05-31 07:17:17 +00005167 if (mDragState && mDragState->dragWindow->getInfo()->displayId == displayId &&
arthurhung6d4bed92021-03-17 11:59:33 +08005168 std::find(windowHandles.begin(), windowHandles.end(), mDragState->dragWindow) ==
arthurhungb89ccb02020-12-30 16:19:01 +08005169 windowHandles.end()) {
Arthur Hung3915c1f2022-05-31 07:17:17 +00005170 ALOGI("Drag window went away: %s", mDragState->dragWindow->getName().c_str());
5171 sendDropWindowCommandLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08005172 mDragState.reset();
arthurhungb89ccb02020-12-30 16:19:01 +08005173 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00005174 }
Arthur Hung25e2af12020-03-26 12:58:37 +00005175
Prabir Pradhan8b89c2f2021-07-29 16:30:14 +00005176 // Determine if the orientation of any of the input windows have changed, and cancel all
5177 // pointer events if necessary.
5178 for (const sp<WindowInfoHandle>& oldWindowHandle : oldWindowHandles) {
5179 const sp<WindowInfoHandle> newWindowHandle = getWindowHandleLocked(oldWindowHandle);
5180 if (newWindowHandle != nullptr &&
5181 newWindowHandle->getInfo()->transform.getOrientation() !=
5182 oldWindowOrientations[oldWindowHandle->getId()]) {
5183 std::shared_ptr<InputChannel> inputChannel =
5184 getInputChannelLocked(newWindowHandle->getToken());
5185 if (inputChannel != nullptr) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00005186 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
Prabir Pradhan8b89c2f2021-07-29 16:30:14 +00005187 "touched window's orientation changed");
5188 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
Prabir Pradhan93a0f912021-04-21 13:47:42 -07005189 }
5190 }
5191 }
5192
Arthur Hung72d8dc32020-03-28 00:48:39 +00005193 // Release information for windows that are no longer present.
5194 // This ensures that unused input channels are released promptly.
5195 // Otherwise, they might stick around until the window handle is destroyed
5196 // which might not happen until the next GC.
chaviw98318de2021-05-19 16:45:23 -05005197 for (const sp<WindowInfoHandle>& oldWindowHandle : oldWindowHandles) {
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07005198 if (getWindowHandleLocked(oldWindowHandle) == nullptr) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00005199 if (DEBUG_FOCUS) {
5200 ALOGD("Window went away: %s", oldWindowHandle->getName().c_str());
Arthur Hung25e2af12020-03-26 12:58:37 +00005201 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00005202 oldWindowHandle->releaseChannel();
Arthur Hung25e2af12020-03-26 12:58:37 +00005203 }
chaviw291d88a2019-02-14 10:33:58 -08005204 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005205}
5206
5207void InputDispatcher::setFocusedApplication(
Chris Yea209fde2020-07-22 13:54:51 -07005208 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005209 if (DEBUG_FOCUS) {
5210 ALOGD("setFocusedApplication displayId=%" PRId32 " %s", displayId,
5211 inputApplicationHandle ? inputApplicationHandle->getName().c_str() : "<nullptr>");
5212 }
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05005213 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005214 std::scoped_lock _l(mLock);
Vishnu Nair599f1412021-06-21 10:39:58 -07005215 setFocusedApplicationLocked(displayId, inputApplicationHandle);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005216 } // release lock
5217
5218 // Wake up poll loop since it may need to make new input dispatching choices.
5219 mLooper->wake();
5220}
5221
Vishnu Nair599f1412021-06-21 10:39:58 -07005222void InputDispatcher::setFocusedApplicationLocked(
5223 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
5224 std::shared_ptr<InputApplicationHandle> oldFocusedApplicationHandle =
5225 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
5226
5227 if (sharedPointersEqual(oldFocusedApplicationHandle, inputApplicationHandle)) {
5228 return; // This application is already focused. No need to wake up or change anything.
5229 }
5230
5231 // Set the new application handle.
5232 if (inputApplicationHandle != nullptr) {
5233 mFocusedApplicationHandlesByDisplay[displayId] = inputApplicationHandle;
5234 } else {
5235 mFocusedApplicationHandlesByDisplay.erase(displayId);
5236 }
5237
5238 // No matter what the old focused application was, stop waiting on it because it is
5239 // no longer focused.
5240 resetNoFocusedWindowTimeoutLocked();
5241}
5242
Tiger Huang721e26f2018-07-24 22:26:19 +08005243/**
5244 * Sets the focused display, which is responsible for receiving focus-dispatched input events where
5245 * the display not specified.
5246 *
5247 * We track any unreleased events for each window. If a window loses the ability to receive the
5248 * released event, we will send a cancel event to it. So when the focused display is changed, we
5249 * cancel all the unreleased display-unspecified events for the focused window on the old focused
5250 * display. The display-specified events won't be affected.
5251 */
5252void InputDispatcher::setFocusedDisplay(int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005253 if (DEBUG_FOCUS) {
5254 ALOGD("setFocusedDisplay displayId=%" PRId32, displayId);
5255 }
Tiger Huang721e26f2018-07-24 22:26:19 +08005256 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005257 std::scoped_lock _l(mLock);
Tiger Huang721e26f2018-07-24 22:26:19 +08005258
5259 if (mFocusedDisplayId != displayId) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07005260 sp<IBinder> oldFocusedWindowToken =
Vishnu Nairc519ff72021-01-21 08:23:08 -08005261 mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07005262 if (oldFocusedWindowToken != nullptr) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005263 std::shared_ptr<InputChannel> inputChannel =
Vishnu Nairad321cd2020-08-20 16:40:21 -07005264 getInputChannelLocked(oldFocusedWindowToken);
Tiger Huang721e26f2018-07-24 22:26:19 +08005265 if (inputChannel != nullptr) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005266 CancelationOptions
Michael Wrightfb04fd52022-11-24 22:31:11 +00005267 options(CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005268 "The display which contains this window no longer has focus.");
Michael Wright3dd60e22019-03-27 22:06:44 +00005269 options.displayId = ADISPLAY_ID_NONE;
Tiger Huang721e26f2018-07-24 22:26:19 +08005270 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
5271 }
5272 }
5273 mFocusedDisplayId = displayId;
5274
Chris Ye3c2d6f52020-08-09 10:39:48 -07005275 // Find new focused window and validate
Vishnu Nairc519ff72021-01-21 08:23:08 -08005276 sp<IBinder> newFocusedWindowToken = mFocusResolver.getFocusedWindowToken(displayId);
Prabir Pradhancef936d2021-07-21 16:17:52 +00005277 sendFocusChangedCommandLocked(oldFocusedWindowToken, newFocusedWindowToken);
Robert Carrf759f162018-11-13 12:57:11 -08005278
Vishnu Nairad321cd2020-08-20 16:40:21 -07005279 if (newFocusedWindowToken == nullptr) {
Tiger Huang721e26f2018-07-24 22:26:19 +08005280 ALOGW("Focused display #%" PRId32 " does not have a focused window.", displayId);
Vishnu Nairc519ff72021-01-21 08:23:08 -08005281 if (mFocusResolver.hasFocusedWindowTokens()) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07005282 ALOGE("But another display has a focused window\n%s",
Vishnu Nairc519ff72021-01-21 08:23:08 -08005283 mFocusResolver.dumpFocusedWindows().c_str());
Tiger Huang721e26f2018-07-24 22:26:19 +08005284 }
5285 }
5286 }
Tiger Huang721e26f2018-07-24 22:26:19 +08005287 } // release lock
5288
5289 // Wake up poll loop since it may need to make new input dispatching choices.
5290 mLooper->wake();
5291}
5292
Michael Wrightd02c5b62014-02-10 15:10:22 -08005293void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005294 if (DEBUG_FOCUS) {
5295 ALOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
5296 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005297
5298 bool changed;
5299 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005300 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005301
5302 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
5303 if (mDispatchFrozen && !frozen) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005304 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005305 }
5306
5307 if (mDispatchEnabled && !enabled) {
5308 resetAndDropEverythingLocked("dispatcher is being disabled");
5309 }
5310
5311 mDispatchEnabled = enabled;
5312 mDispatchFrozen = frozen;
5313 changed = true;
5314 } else {
5315 changed = false;
5316 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005317 } // release lock
5318
5319 if (changed) {
5320 // Wake up poll loop since it may need to make new input dispatching choices.
5321 mLooper->wake();
5322 }
5323}
5324
5325void InputDispatcher::setInputFilterEnabled(bool enabled) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005326 if (DEBUG_FOCUS) {
5327 ALOGD("setInputFilterEnabled: enabled=%d", enabled);
5328 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005329
5330 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005331 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005332
5333 if (mInputFilterEnabled == enabled) {
5334 return;
5335 }
5336
5337 mInputFilterEnabled = enabled;
5338 resetAndDropEverythingLocked("input filter is being enabled or disabled");
5339 } // release lock
5340
5341 // Wake up poll loop since there might be work to do to drop everything.
5342 mLooper->wake();
5343}
5344
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00005345bool InputDispatcher::setInTouchMode(bool inTouchMode, int32_t pid, gui::Uid uid,
5346 bool hasPermission, int32_t displayId) {
Antonio Kantekf16f2832021-09-28 04:39:20 +00005347 bool needWake = false;
5348 {
5349 std::scoped_lock lock(mLock);
Antonio Kantek15beb512022-06-13 22:35:41 +00005350 ALOGD_IF(DEBUG_TOUCH_MODE,
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00005351 "Request to change touch mode to %s (calling pid=%d, uid=%s, "
Antonio Kantek15beb512022-06-13 22:35:41 +00005352 "hasPermission=%s, target displayId=%d, mTouchModePerDisplay[displayId]=%s)",
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00005353 toString(inTouchMode), pid, uid.toString().c_str(), toString(hasPermission),
5354 displayId,
Antonio Kantek15beb512022-06-13 22:35:41 +00005355 mTouchModePerDisplay.count(displayId) == 0
5356 ? "not set"
5357 : std::to_string(mTouchModePerDisplay[displayId]).c_str());
5358
Antonio Kantek15beb512022-06-13 22:35:41 +00005359 auto touchModeIt = mTouchModePerDisplay.find(displayId);
5360 if (touchModeIt != mTouchModePerDisplay.end() && touchModeIt->second == inTouchMode) {
Antonio Kantekea47acb2021-12-23 12:41:25 -08005361 return false;
Antonio Kantekf16f2832021-09-28 04:39:20 +00005362 }
Antonio Kantekea47acb2021-12-23 12:41:25 -08005363 if (!hasPermission) {
Antonio Kantek48710e42022-03-24 14:19:30 -07005364 if (!focusedWindowIsOwnedByLocked(pid, uid) &&
5365 !recentWindowsAreOwnedByLocked(pid, uid)) {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00005366 ALOGD("Touch mode switch rejected, caller (pid=%d, uid=%s) doesn't own the focused "
Antonio Kantek48710e42022-03-24 14:19:30 -07005367 "window nor none of the previously interacted window",
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00005368 pid, uid.toString().c_str());
Antonio Kantekea47acb2021-12-23 12:41:25 -08005369 return false;
5370 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00005371 }
Antonio Kantek15beb512022-06-13 22:35:41 +00005372 mTouchModePerDisplay[displayId] = inTouchMode;
5373 auto entry = std::make_unique<TouchModeEntry>(mIdGenerator.nextId(), now(), inTouchMode,
5374 displayId);
Antonio Kantekf16f2832021-09-28 04:39:20 +00005375 needWake = enqueueInboundEventLocked(std::move(entry));
5376 } // release lock
5377
5378 if (needWake) {
5379 mLooper->wake();
5380 }
Antonio Kantekea47acb2021-12-23 12:41:25 -08005381 return true;
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -08005382}
5383
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00005384bool InputDispatcher::focusedWindowIsOwnedByLocked(int32_t pid, gui::Uid uid) {
Antonio Kantek48710e42022-03-24 14:19:30 -07005385 const sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
5386 if (focusedToken == nullptr) {
5387 return false;
5388 }
5389 sp<WindowInfoHandle> windowHandle = getWindowHandleLocked(focusedToken);
5390 return isWindowOwnedBy(windowHandle, pid, uid);
5391}
5392
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00005393bool InputDispatcher::recentWindowsAreOwnedByLocked(int32_t pid, gui::Uid uid) {
Antonio Kantek48710e42022-03-24 14:19:30 -07005394 return std::find_if(mInteractionConnectionTokens.begin(), mInteractionConnectionTokens.end(),
5395 [&](const sp<IBinder>& connectionToken) REQUIRES(mLock) {
5396 const sp<WindowInfoHandle> windowHandle =
5397 getWindowHandleLocked(connectionToken);
5398 return isWindowOwnedBy(windowHandle, pid, uid);
5399 }) != mInteractionConnectionTokens.end();
5400}
5401
Bernardo Rufinoea97d182020-08-19 14:43:14 +01005402void InputDispatcher::setMaximumObscuringOpacityForTouch(float opacity) {
5403 if (opacity < 0 || opacity > 1) {
5404 LOG_ALWAYS_FATAL("Maximum obscuring opacity for touch should be >= 0 and <= 1");
5405 return;
5406 }
5407
5408 std::scoped_lock lock(mLock);
5409 mMaximumObscuringOpacityForTouch = opacity;
5410}
5411
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005412std::tuple<TouchState*, TouchedWindow*, int32_t /*displayId*/>
5413InputDispatcher::findTouchStateWindowAndDisplayLocked(const sp<IBinder>& token) {
Arthur Hungabbb9d82021-09-01 14:52:30 +00005414 for (auto& [displayId, state] : mTouchStatesByDisplay) {
5415 for (TouchedWindow& w : state.windows) {
5416 if (w.windowHandle->getToken() == token) {
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005417 return std::make_tuple(&state, &w, displayId);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005418 }
5419 }
5420 }
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005421 return std::make_tuple(nullptr, nullptr, ADISPLAY_ID_DEFAULT);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005422}
5423
arthurhungb89ccb02020-12-30 16:19:01 +08005424bool InputDispatcher::transferTouchFocus(const sp<IBinder>& fromToken, const sp<IBinder>& toToken,
5425 bool isDragDrop) {
chaviwfbe5d9c2018-12-26 12:23:37 -08005426 if (fromToken == toToken) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005427 if (DEBUG_FOCUS) {
5428 ALOGD("Trivial transfer to same window.");
5429 }
chaviwfbe5d9c2018-12-26 12:23:37 -08005430 return true;
5431 }
5432
Michael Wrightd02c5b62014-02-10 15:10:22 -08005433 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005434 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005435
Arthur Hungabbb9d82021-09-01 14:52:30 +00005436 // Find the target touch state and touched window by fromToken.
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005437 auto [state, touchedWindow, displayId] = findTouchStateWindowAndDisplayLocked(fromToken);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005438 if (state == nullptr || touchedWindow == nullptr) {
5439 ALOGD("Focus transfer failed because from window is not being touched.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005440 return false;
5441 }
Arthur Hungabbb9d82021-09-01 14:52:30 +00005442
Arthur Hungabbb9d82021-09-01 14:52:30 +00005443 sp<WindowInfoHandle> toWindowHandle = getWindowHandleLocked(toToken, displayId);
5444 if (toWindowHandle == nullptr) {
5445 ALOGW("Cannot transfer focus because to window not found.");
5446 return false;
5447 }
5448
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005449 if (DEBUG_FOCUS) {
5450 ALOGD("transferTouchFocus: fromWindowHandle=%s, toWindowHandle=%s",
Arthur Hungabbb9d82021-09-01 14:52:30 +00005451 touchedWindow->windowHandle->getName().c_str(),
5452 toWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005453 }
5454
Arthur Hungabbb9d82021-09-01 14:52:30 +00005455 // Erase old window.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005456 ftl::Flags<InputTarget::Flags> oldTargetFlags = touchedWindow->targetFlags;
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08005457 std::bitset<MAX_POINTER_ID + 1> pointerIds = touchedWindow->pointerIds;
Arthur Hungc539dbb2022-12-08 07:45:36 +00005458 sp<WindowInfoHandle> fromWindowHandle = touchedWindow->windowHandle;
Arthur Hungabbb9d82021-09-01 14:52:30 +00005459 state->removeWindowByToken(fromToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005460
Arthur Hungabbb9d82021-09-01 14:52:30 +00005461 // Add new window.
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00005462 nsecs_t downTimeInTarget = now();
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005463 ftl::Flags<InputTarget::Flags> newTargetFlags =
5464 oldTargetFlags & (InputTarget::Flags::SPLIT | InputTarget::Flags::DISPATCH_AS_IS);
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00005465 if (canReceiveForegroundTouches(*toWindowHandle->getInfo())) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005466 newTargetFlags |= InputTarget::Flags::FOREGROUND;
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00005467 }
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00005468 state->addOrUpdateWindow(toWindowHandle, newTargetFlags, pointerIds, downTimeInTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005469
Arthur Hungabbb9d82021-09-01 14:52:30 +00005470 // Store the dragging window.
5471 if (isDragDrop) {
Arthur Hungb75c2aa2022-07-15 09:35:36 +00005472 if (pointerIds.count() != 1) {
5473 ALOGW("The drag and drop cannot be started when there is no pointer or more than 1"
5474 " pointer on the window.");
Arthur Hung54745652022-04-20 07:17:41 +00005475 return false;
5476 }
Arthur Hungb75c2aa2022-07-15 09:35:36 +00005477 // Track the pointer id for drag window and generate the drag state.
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08005478 const size_t id = firstMarkedBit(pointerIds);
Arthur Hung54745652022-04-20 07:17:41 +00005479 mDragState = std::make_unique<DragState>(toWindowHandle, id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005480 }
5481
Arthur Hungabbb9d82021-09-01 14:52:30 +00005482 // Synthesize cancel for old window and down for new window.
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07005483 std::shared_ptr<Connection> fromConnection = getConnectionLocked(fromToken);
5484 std::shared_ptr<Connection> toConnection = getConnectionLocked(toToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005485 if (fromConnection != nullptr && toConnection != nullptr) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08005486 fromConnection->inputState.mergePointerStateTo(toConnection->inputState);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005487 CancelationOptions
Michael Wrightfb04fd52022-11-24 22:31:11 +00005488 options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005489 "transferring touch focus from this window to another window");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005490 synthesizeCancelationEventsForConnectionLocked(fromConnection, options);
Arthur Hungc539dbb2022-12-08 07:45:36 +00005491 synthesizePointerDownEventsForConnectionLocked(downTimeInTarget, toConnection,
5492 newTargetFlags);
5493
5494 // Check if the wallpaper window should deliver the corresponding event.
5495 transferWallpaperTouch(oldTargetFlags, newTargetFlags, fromWindowHandle, toWindowHandle,
5496 *state, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005497 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005498 } // release lock
5499
5500 // Wake up poll loop since it may need to make new input dispatching choices.
5501 mLooper->wake();
5502 return true;
5503}
5504
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005505/**
5506 * Get the touched foreground window on the given display.
5507 * Return null if there are no windows touched on that display, or if more than one foreground
5508 * window is being touched.
5509 */
5510sp<WindowInfoHandle> InputDispatcher::findTouchedForegroundWindowLocked(int32_t displayId) const {
5511 auto stateIt = mTouchStatesByDisplay.find(displayId);
5512 if (stateIt == mTouchStatesByDisplay.end()) {
5513 ALOGI("No touch state on display %" PRId32, displayId);
5514 return nullptr;
5515 }
5516
5517 const TouchState& state = stateIt->second;
5518 sp<WindowInfoHandle> touchedForegroundWindow;
5519 // If multiple foreground windows are touched, return nullptr
5520 for (const TouchedWindow& window : state.windows) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005521 if (window.targetFlags.test(InputTarget::Flags::FOREGROUND)) {
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005522 if (touchedForegroundWindow != nullptr) {
5523 ALOGI("Two or more foreground windows: %s and %s",
5524 touchedForegroundWindow->getName().c_str(),
5525 window.windowHandle->getName().c_str());
5526 return nullptr;
5527 }
5528 touchedForegroundWindow = window.windowHandle;
5529 }
5530 }
5531 return touchedForegroundWindow;
5532}
5533
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005534// Binder call
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005535bool InputDispatcher::transferTouch(const sp<IBinder>& destChannelToken, int32_t displayId) {
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005536 sp<IBinder> fromToken;
5537 { // acquire lock
5538 std::scoped_lock _l(mLock);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005539 sp<WindowInfoHandle> toWindowHandle = getWindowHandleLocked(destChannelToken, displayId);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005540 if (toWindowHandle == nullptr) {
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005541 ALOGW("Could not find window associated with token=%p on display %" PRId32,
5542 destChannelToken.get(), displayId);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005543 return false;
5544 }
5545
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005546 sp<WindowInfoHandle> from = findTouchedForegroundWindowLocked(displayId);
5547 if (from == nullptr) {
5548 ALOGE("Could not find a source window in %s for %p", __func__, destChannelToken.get());
5549 return false;
5550 }
5551
5552 fromToken = from->getToken();
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005553 } // release lock
5554
5555 return transferTouchFocus(fromToken, destChannelToken);
5556}
5557
Michael Wrightd02c5b62014-02-10 15:10:22 -08005558void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005559 if (DEBUG_FOCUS) {
5560 ALOGD("Resetting and dropping all events (%s).", reason);
5561 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005562
Michael Wrightfb04fd52022-11-24 22:31:11 +00005563 CancelationOptions options(CancelationOptions::Mode::CANCEL_ALL_EVENTS, reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005564 synthesizeCancelationEventsForAllConnectionsLocked(options);
5565
5566 resetKeyRepeatLocked();
5567 releasePendingEventLocked();
5568 drainInboundQueueLocked();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005569 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005570
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005571 mAnrTracker.clear();
Jeff Brownf086ddb2014-02-11 14:28:48 -08005572 mTouchStatesByDisplay.clear();
Michael Wright78f24442014-08-06 15:55:28 -07005573 mReplacedKeys.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005574}
5575
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005576void InputDispatcher::logDispatchStateLocked() const {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005577 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005578 dumpDispatchStateLocked(dump);
5579
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005580 std::istringstream stream(dump);
5581 std::string line;
5582
5583 while (std::getline(stream, line, '\n')) {
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07005584 ALOGI("%s", line.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005585 }
5586}
5587
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005588std::string InputDispatcher::dumpPointerCaptureStateLocked() const {
Prabir Pradhan99987712020-11-10 18:43:05 -08005589 std::string dump;
5590
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005591 dump += StringPrintf(INDENT "Pointer Capture Requested: %s\n",
5592 toString(mCurrentPointerCaptureRequest.enable));
Prabir Pradhan99987712020-11-10 18:43:05 -08005593
5594 std::string windowName = "None";
5595 if (mWindowTokenWithPointerCapture) {
chaviw98318de2021-05-19 16:45:23 -05005596 const sp<WindowInfoHandle> captureWindowHandle =
Prabir Pradhan99987712020-11-10 18:43:05 -08005597 getWindowHandleLocked(mWindowTokenWithPointerCapture);
5598 windowName = captureWindowHandle ? captureWindowHandle->getName().c_str()
5599 : "token has capture without window";
5600 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005601 dump += StringPrintf(INDENT "Current Window with Pointer Capture: %s\n", windowName.c_str());
Prabir Pradhan99987712020-11-10 18:43:05 -08005602
5603 return dump;
5604}
5605
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005606void InputDispatcher::dumpDispatchStateLocked(std::string& dump) const {
Siarhei Vishniakou043a3ec2019-05-01 11:30:46 -07005607 dump += StringPrintf(INDENT "DispatchEnabled: %s\n", toString(mDispatchEnabled));
5608 dump += StringPrintf(INDENT "DispatchFrozen: %s\n", toString(mDispatchFrozen));
5609 dump += StringPrintf(INDENT "InputFilterEnabled: %s\n", toString(mInputFilterEnabled));
Tiger Huang721e26f2018-07-24 22:26:19 +08005610 dump += StringPrintf(INDENT "FocusedDisplayId: %" PRId32 "\n", mFocusedDisplayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005611
Tiger Huang721e26f2018-07-24 22:26:19 +08005612 if (!mFocusedApplicationHandlesByDisplay.empty()) {
5613 dump += StringPrintf(INDENT "FocusedApplications:\n");
5614 for (auto& it : mFocusedApplicationHandlesByDisplay) {
5615 const int32_t displayId = it.first;
Chris Yea209fde2020-07-22 13:54:51 -07005616 const std::shared_ptr<InputApplicationHandle>& applicationHandle = it.second;
Siarhei Vishniakou70622952020-07-30 11:17:23 -05005617 const std::chrono::duration timeout =
5618 applicationHandle->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005619 dump += StringPrintf(INDENT2 "displayId=%" PRId32
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005620 ", name='%s', dispatchingTimeout=%" PRId64 "ms\n",
Siarhei Vishniakou70622952020-07-30 11:17:23 -05005621 displayId, applicationHandle->getName().c_str(), millis(timeout));
Tiger Huang721e26f2018-07-24 22:26:19 +08005622 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005623 } else {
Tiger Huang721e26f2018-07-24 22:26:19 +08005624 dump += StringPrintf(INDENT "FocusedApplications: <none>\n");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005625 }
Tiger Huang721e26f2018-07-24 22:26:19 +08005626
Vishnu Nairc519ff72021-01-21 08:23:08 -08005627 dump += mFocusResolver.dump();
Prabir Pradhan99987712020-11-10 18:43:05 -08005628 dump += dumpPointerCaptureStateLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005629
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005630 if (!mTouchStatesByDisplay.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005631 dump += StringPrintf(INDENT "TouchStatesByDisplay:\n");
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005632 for (const auto& [displayId, state] : mTouchStatesByDisplay) {
Siarhei Vishniakou6e1e9872022-11-08 17:51:35 -08005633 std::string touchStateDump = addLinePrefix(state.dump(), INDENT2);
5634 dump += INDENT2 + std::to_string(displayId) + " : " + touchStateDump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005635 }
5636 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005637 dump += INDENT "TouchStates: <no displays touched>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005638 }
5639
arthurhung6d4bed92021-03-17 11:59:33 +08005640 if (mDragState) {
5641 dump += StringPrintf(INDENT "DragState:\n");
5642 mDragState->dump(dump, INDENT2);
5643 }
5644
Arthur Hungb92218b2018-08-14 12:00:21 +08005645 if (!mWindowHandlesByDisplay.empty()) {
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005646 for (const auto& [displayId, windowHandles] : mWindowHandlesByDisplay) {
5647 dump += StringPrintf(INDENT "Display: %" PRId32 "\n", displayId);
5648 if (const auto& it = mDisplayInfos.find(displayId); it != mDisplayInfos.end()) {
5649 const auto& displayInfo = it->second;
5650 dump += StringPrintf(INDENT2 "logicalSize=%dx%d\n", displayInfo.logicalWidth,
5651 displayInfo.logicalHeight);
5652 displayInfo.transform.dump(dump, "transform", INDENT4);
5653 } else {
5654 dump += INDENT2 "No DisplayInfo found!\n";
5655 }
5656
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08005657 if (!windowHandles.empty()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08005658 dump += INDENT2 "Windows:\n";
5659 for (size_t i = 0; i < windowHandles.size(); i++) {
chaviw98318de2021-05-19 16:45:23 -05005660 const sp<WindowInfoHandle>& windowHandle = windowHandles[i];
5661 const WindowInfo* windowInfo = windowHandle->getInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005662
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00005663 dump += StringPrintf(INDENT3 "%zu: name='%s', id=%" PRId32 ", displayId=%d, "
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005664 "inputConfig=%s, alpha=%.2f, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005665 "frame=[%d,%d][%d,%d], globalScale=%f, "
Bernardo Rufino49d99e42021-01-18 15:16:59 +00005666 "applicationInfo.name=%s, "
5667 "applicationInfo.token=%s, "
chaviw1ff3d1e2020-07-01 15:53:47 -07005668 "touchableRegion=",
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00005669 i, windowInfo->name.c_str(), windowInfo->id,
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005670 windowInfo->displayId,
5671 windowInfo->inputConfig.string().c_str(),
5672 windowInfo->alpha, windowInfo->frameLeft,
5673 windowInfo->frameTop, windowInfo->frameRight,
5674 windowInfo->frameBottom, windowInfo->globalScaleFactor,
Bernardo Rufino49d99e42021-01-18 15:16:59 +00005675 windowInfo->applicationInfo.name.c_str(),
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07005676 binderToString(windowInfo->applicationInfo.token).c_str());
Bernardo Rufino53fc31e2020-11-03 11:01:07 +00005677 dump += dumpRegion(windowInfo->touchableRegion);
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00005678 dump += StringPrintf(", ownerPid=%d, ownerUid=%s, dispatchingTimeout=%" PRId64
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005679 "ms, hasToken=%s, "
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005680 "touchOcclusionMode=%s\n",
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00005681 windowInfo->ownerPid,
5682 windowInfo->ownerUid.toString().c_str(),
Bernardo Rufinoc2f1fad2020-11-04 17:30:57 +00005683 millis(windowInfo->dispatchingTimeout),
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07005684 binderToString(windowInfo->token).c_str(),
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005685 toString(windowInfo->touchOcclusionMode).c_str());
chaviw85b44202020-07-24 11:46:21 -07005686 windowInfo->transform.dump(dump, "transform", INDENT4);
Arthur Hungb92218b2018-08-14 12:00:21 +08005687 }
5688 } else {
5689 dump += INDENT2 "Windows: <none>\n";
5690 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005691 }
5692 } else {
Arthur Hungb92218b2018-08-14 12:00:21 +08005693 dump += INDENT "Displays: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005694 }
5695
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005696 if (!mGlobalMonitorsByDisplay.empty()) {
5697 for (const auto& [displayId, monitors] : mGlobalMonitorsByDisplay) {
5698 dump += StringPrintf(INDENT "Global monitors on display %d:\n", displayId);
Michael Wright3dd60e22019-03-27 22:06:44 +00005699 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005700 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005701 } else {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005702 dump += INDENT "Global Monitors: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005703 }
5704
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005705 const nsecs_t currentTime = now();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005706
5707 // Dump recently dispatched or dropped events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005708 if (!mRecentQueue.empty()) {
5709 dump += StringPrintf(INDENT "RecentQueue: length=%zu\n", mRecentQueue.size());
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005710 for (const std::shared_ptr<EventEntry>& entry : mRecentQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005711 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005712 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005713 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005714 }
5715 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005716 dump += INDENT "RecentQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005717 }
5718
5719 // Dump event currently being dispatched.
5720 if (mPendingEvent) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005721 dump += INDENT "PendingEvent:\n";
5722 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005723 dump += mPendingEvent->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005724 dump += StringPrintf(", age=%" PRId64 "ms\n",
5725 ns2ms(currentTime - mPendingEvent->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005726 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005727 dump += INDENT "PendingEvent: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005728 }
5729
5730 // Dump inbound events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005731 if (!mInboundQueue.empty()) {
5732 dump += StringPrintf(INDENT "InboundQueue: length=%zu\n", mInboundQueue.size());
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005733 for (const std::shared_ptr<EventEntry>& entry : mInboundQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005734 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005735 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005736 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005737 }
5738 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005739 dump += INDENT "InboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005740 }
5741
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005742 if (!mReplacedKeys.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005743 dump += INDENT "ReplacedKeys:\n";
Michael Wright3cec4462022-11-24 22:05:46 +00005744 for (const auto& [replacement, newKeyCode] : mReplacedKeys) {
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005745 dump += StringPrintf(INDENT2 "originalKeyCode=%d, deviceId=%d -> newKeyCode=%d\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005746 replacement.keyCode, replacement.deviceId, newKeyCode);
Michael Wright78f24442014-08-06 15:55:28 -07005747 }
5748 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005749 dump += INDENT "ReplacedKeys: <empty>\n";
Michael Wright78f24442014-08-06 15:55:28 -07005750 }
5751
Prabir Pradhancef936d2021-07-21 16:17:52 +00005752 if (!mCommandQueue.empty()) {
5753 dump += StringPrintf(INDENT "CommandQueue: size=%zu\n", mCommandQueue.size());
5754 } else {
5755 dump += INDENT "CommandQueue: <empty>\n";
5756 }
5757
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005758 if (!mConnectionsByToken.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005759 dump += INDENT "Connections:\n";
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005760 for (const auto& [token, connection] : mConnectionsByToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005761 dump += StringPrintf(INDENT2 "%i: channelName='%s', windowName='%s', "
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005762 "status=%s, monitor=%s, responsive=%s\n",
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005763 connection->inputChannel->getFd().get(),
5764 connection->getInputChannelName().c_str(),
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08005765 connection->getWindowName().c_str(),
5766 ftl::enum_string(connection->status).c_str(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005767 toString(connection->monitor), toString(connection->responsive));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005768
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005769 if (!connection->outboundQueue.empty()) {
5770 dump += StringPrintf(INDENT3 "OutboundQueue: length=%zu\n",
5771 connection->outboundQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005772 dump += dumpQueue(connection->outboundQueue, currentTime);
5773
Michael Wrightd02c5b62014-02-10 15:10:22 -08005774 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005775 dump += INDENT3 "OutboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005776 }
5777
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005778 if (!connection->waitQueue.empty()) {
5779 dump += StringPrintf(INDENT3 "WaitQueue: length=%zu\n",
5780 connection->waitQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005781 dump += dumpQueue(connection->waitQueue, currentTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005782 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005783 dump += INDENT3 "WaitQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005784 }
5785 }
5786 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005787 dump += INDENT "Connections: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005788 }
5789
5790 if (isAppSwitchPendingLocked()) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005791 dump += StringPrintf(INDENT "AppSwitch: pending, due in %" PRId64 "ms\n",
5792 ns2ms(mAppSwitchDueTime - now()));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005793 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005794 dump += INDENT "AppSwitch: not pending\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005795 }
5796
Antonio Kantek15beb512022-06-13 22:35:41 +00005797 if (!mTouchModePerDisplay.empty()) {
5798 dump += INDENT "TouchModePerDisplay:\n";
5799 for (const auto& [displayId, touchMode] : mTouchModePerDisplay) {
5800 dump += StringPrintf(INDENT2 "Display: %" PRId32 " TouchMode: %s\n", displayId,
5801 std::to_string(touchMode).c_str());
5802 }
5803 } else {
5804 dump += INDENT "TouchModePerDisplay: <none>\n";
5805 }
5806
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005807 dump += INDENT "Configuration:\n";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005808 dump += StringPrintf(INDENT2 "KeyRepeatDelay: %" PRId64 "ms\n", ns2ms(mConfig.keyRepeatDelay));
5809 dump += StringPrintf(INDENT2 "KeyRepeatTimeout: %" PRId64 "ms\n",
5810 ns2ms(mConfig.keyRepeatTimeout));
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00005811 dump += mLatencyTracker.dump(INDENT2);
Siarhei Vishniakoua04181f2021-03-26 05:56:49 +00005812 dump += mLatencyAggregator.dump(INDENT2);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005813}
5814
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005815void InputDispatcher::dumpMonitors(std::string& dump, const std::vector<Monitor>& monitors) const {
Michael Wright3dd60e22019-03-27 22:06:44 +00005816 const size_t numMonitors = monitors.size();
5817 for (size_t i = 0; i < numMonitors; i++) {
5818 const Monitor& monitor = monitors[i];
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005819 const std::shared_ptr<InputChannel>& channel = monitor.inputChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005820 dump += StringPrintf(INDENT2 "%zu: '%s', ", i, channel->getName().c_str());
5821 dump += "\n";
5822 }
5823}
5824
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005825class LooperEventCallback : public LooperCallback {
5826public:
5827 LooperEventCallback(std::function<int(int events)> callback) : mCallback(callback) {}
5828 int handleEvent(int /*fd*/, int events, void* /*data*/) override { return mCallback(events); }
5829
5830private:
5831 std::function<int(int events)> mCallback;
5832};
5833
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005834Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputChannel(const std::string& name) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00005835 if (DEBUG_CHANNEL_CREATION) {
5836 ALOGD("channel '%s' ~ createInputChannel", name.c_str());
5837 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005838
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005839 std::unique_ptr<InputChannel> serverChannel;
Garfield Tan15601662020-09-22 15:32:38 -07005840 std::unique_ptr<InputChannel> clientChannel;
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005841 status_t result = InputChannel::openInputChannelPair(name, serverChannel, clientChannel);
Garfield Tan15601662020-09-22 15:32:38 -07005842
5843 if (result) {
5844 return base::Error(result) << "Failed to open input channel pair with name " << name;
5845 }
5846
Michael Wrightd02c5b62014-02-10 15:10:22 -08005847 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005848 std::scoped_lock _l(mLock);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005849 const sp<IBinder>& token = serverChannel->getConnectionToken();
Garfield Tan15601662020-09-22 15:32:38 -07005850 int fd = serverChannel->getFd();
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07005851 std::shared_ptr<Connection> connection =
5852 std::make_shared<Connection>(std::move(serverChannel), /*monitor=*/false,
5853 mIdGenerator);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005854
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005855 if (mConnectionsByToken.find(token) != mConnectionsByToken.end()) {
5856 ALOGE("Created a new connection, but the token %p is already known", token.get());
5857 }
5858 mConnectionsByToken.emplace(token, connection);
5859
5860 std::function<int(int events)> callback = std::bind(&InputDispatcher::handleReceiveCallback,
5861 this, std::placeholders::_1, token);
5862
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005863 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, sp<LooperEventCallback>::make(callback),
5864 nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005865 } // release lock
5866
5867 // Wake the looper because some connections have changed.
5868 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07005869 return clientChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005870}
5871
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005872Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputMonitor(int32_t displayId,
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005873 const std::string& name,
5874 int32_t pid) {
Garfield Tan15601662020-09-22 15:32:38 -07005875 std::shared_ptr<InputChannel> serverChannel;
5876 std::unique_ptr<InputChannel> clientChannel;
5877 status_t result = openInputChannelPair(name, serverChannel, clientChannel);
5878 if (result) {
5879 return base::Error(result) << "Failed to open input channel pair with name " << name;
5880 }
5881
Michael Wright3dd60e22019-03-27 22:06:44 +00005882 { // acquire lock
5883 std::scoped_lock _l(mLock);
5884
5885 if (displayId < 0) {
Garfield Tan15601662020-09-22 15:32:38 -07005886 return base::Error(BAD_VALUE) << "Attempted to create input monitor with name " << name
5887 << " without a specified display.";
Michael Wright3dd60e22019-03-27 22:06:44 +00005888 }
5889
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07005890 std::shared_ptr<Connection> connection =
5891 std::make_shared<Connection>(serverChannel, /*monitor=*/true, mIdGenerator);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005892 const sp<IBinder>& token = serverChannel->getConnectionToken();
Garfield Tan15601662020-09-22 15:32:38 -07005893 const int fd = serverChannel->getFd();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005894
5895 if (mConnectionsByToken.find(token) != mConnectionsByToken.end()) {
5896 ALOGE("Created a new connection, but the token %p is already known", token.get());
5897 }
5898 mConnectionsByToken.emplace(token, connection);
5899 std::function<int(int events)> callback = std::bind(&InputDispatcher::handleReceiveCallback,
5900 this, std::placeholders::_1, token);
Michael Wright3dd60e22019-03-27 22:06:44 +00005901
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005902 mGlobalMonitorsByDisplay[displayId].emplace_back(serverChannel, pid);
Michael Wright3dd60e22019-03-27 22:06:44 +00005903
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005904 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, sp<LooperEventCallback>::make(callback),
5905 nullptr);
Michael Wright3dd60e22019-03-27 22:06:44 +00005906 }
Garfield Tan15601662020-09-22 15:32:38 -07005907
Michael Wright3dd60e22019-03-27 22:06:44 +00005908 // Wake the looper because some connections have changed.
5909 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07005910 return clientChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005911}
5912
Garfield Tan15601662020-09-22 15:32:38 -07005913status_t InputDispatcher::removeInputChannel(const sp<IBinder>& connectionToken) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005914 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005915 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005916
Harry Cutts33476232023-01-30 19:57:29 +00005917 status_t status = removeInputChannelLocked(connectionToken, /*notify=*/false);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005918 if (status) {
5919 return status;
5920 }
5921 } // release lock
5922
5923 // Wake the poll loop because removing the connection may have changed the current
5924 // synchronization state.
5925 mLooper->wake();
5926 return OK;
5927}
5928
Garfield Tan15601662020-09-22 15:32:38 -07005929status_t InputDispatcher::removeInputChannelLocked(const sp<IBinder>& connectionToken,
5930 bool notify) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07005931 std::shared_ptr<Connection> connection = getConnectionLocked(connectionToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005932 if (connection == nullptr) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005933 // Connection can be removed via socket hang up or an explicit call to 'removeInputChannel'
Michael Wrightd02c5b62014-02-10 15:10:22 -08005934 return BAD_VALUE;
5935 }
5936
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005937 removeConnectionLocked(connection);
Robert Carr5c8a0262018-10-03 16:30:44 -07005938
Michael Wrightd02c5b62014-02-10 15:10:22 -08005939 if (connection->monitor) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005940 removeMonitorChannelLocked(connectionToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005941 }
5942
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005943 mLooper->removeFd(connection->inputChannel->getFd());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005944
5945 nsecs_t currentTime = now();
5946 abortBrokenDispatchCycleLocked(currentTime, connection, notify);
5947
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08005948 connection->status = Connection::Status::ZOMBIE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005949 return OK;
5950}
5951
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005952void InputDispatcher::removeMonitorChannelLocked(const sp<IBinder>& connectionToken) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005953 for (auto it = mGlobalMonitorsByDisplay.begin(); it != mGlobalMonitorsByDisplay.end();) {
5954 auto& [displayId, monitors] = *it;
5955 std::erase_if(monitors, [connectionToken](const Monitor& monitor) {
5956 return monitor.inputChannel->getConnectionToken() == connectionToken;
5957 });
Michael Wright3dd60e22019-03-27 22:06:44 +00005958
Michael Wright3dd60e22019-03-27 22:06:44 +00005959 if (monitors.empty()) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005960 it = mGlobalMonitorsByDisplay.erase(it);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005961 } else {
5962 ++it;
5963 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005964 }
5965}
5966
Michael Wright3dd60e22019-03-27 22:06:44 +00005967status_t InputDispatcher::pilferPointers(const sp<IBinder>& token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005968 std::scoped_lock _l(mLock);
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00005969 return pilferPointersLocked(token);
5970}
Michael Wright3dd60e22019-03-27 22:06:44 +00005971
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00005972status_t InputDispatcher::pilferPointersLocked(const sp<IBinder>& token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005973 const std::shared_ptr<InputChannel> requestingChannel = getInputChannelLocked(token);
5974 if (!requestingChannel) {
5975 ALOGW("Attempted to pilfer pointers from an un-registered channel or invalid token");
5976 return BAD_VALUE;
Michael Wright3dd60e22019-03-27 22:06:44 +00005977 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005978
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005979 auto [statePtr, windowPtr, displayId] = findTouchStateWindowAndDisplayLocked(token);
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08005980 if (statePtr == nullptr || windowPtr == nullptr || windowPtr->pointerIds.none()) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005981 ALOGW("Attempted to pilfer points from a channel without any on-going pointer streams."
5982 " Ignoring.");
5983 return BAD_VALUE;
5984 }
5985
5986 TouchState& state = *statePtr;
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00005987 TouchedWindow& window = *windowPtr;
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005988 // Send cancel events to all the input channels we're stealing from.
Michael Wrightfb04fd52022-11-24 22:31:11 +00005989 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005990 "input channel stole pointer stream");
5991 options.deviceId = state.deviceId;
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005992 options.displayId = displayId;
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07005993 options.pointerIds = window.pointerIds;
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005994 std::string canceledWindows;
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00005995 for (const TouchedWindow& w : state.windows) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005996 const std::shared_ptr<InputChannel> channel =
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00005997 getInputChannelLocked(w.windowHandle->getToken());
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005998 if (channel != nullptr && channel->getConnectionToken() != token) {
5999 synthesizeCancelationEventsForInputChannelLocked(channel, options);
6000 canceledWindows += canceledWindows.empty() ? "[" : ", ";
6001 canceledWindows += channel->getName();
6002 }
6003 }
6004 canceledWindows += canceledWindows.empty() ? "[]" : "]";
6005 ALOGI("Channel %s is stealing touch from %s", requestingChannel->getName().c_str(),
6006 canceledWindows.c_str());
6007
Prabir Pradhane680f9b2022-02-04 04:24:00 -08006008 // Prevent the gesture from being sent to any other windows.
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00006009 // This only blocks relevant pointers to be sent to other windows
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08006010 window.pilferedPointerIds |= window.pointerIds;
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00006011
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07006012 state.cancelPointersForWindowsExcept(window.pointerIds, token);
Michael Wright3dd60e22019-03-27 22:06:44 +00006013 return OK;
6014}
6015
Prabir Pradhan99987712020-11-10 18:43:05 -08006016void InputDispatcher::requestPointerCapture(const sp<IBinder>& windowToken, bool enabled) {
6017 { // acquire lock
6018 std::scoped_lock _l(mLock);
6019 if (DEBUG_FOCUS) {
chaviw98318de2021-05-19 16:45:23 -05006020 const sp<WindowInfoHandle> windowHandle = getWindowHandleLocked(windowToken);
Prabir Pradhan99987712020-11-10 18:43:05 -08006021 ALOGI("Request to %s Pointer Capture from: %s.", enabled ? "enable" : "disable",
6022 windowHandle != nullptr ? windowHandle->getName().c_str()
6023 : "token without window");
6024 }
6025
Vishnu Nairc519ff72021-01-21 08:23:08 -08006026 const sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Prabir Pradhan99987712020-11-10 18:43:05 -08006027 if (focusedToken != windowToken) {
6028 ALOGW("Ignoring request to %s Pointer Capture: window does not have focus.",
6029 enabled ? "enable" : "disable");
6030 return;
6031 }
6032
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006033 if (enabled == mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006034 ALOGW("Ignoring request to %s Pointer Capture: "
6035 "window has %s requested pointer capture.",
6036 enabled ? "enable" : "disable", enabled ? "already" : "not");
6037 return;
6038 }
6039
Christine Franksb768bb42021-11-29 12:11:31 -08006040 if (enabled) {
6041 if (std::find(mIneligibleDisplaysForPointerCapture.begin(),
6042 mIneligibleDisplaysForPointerCapture.end(),
6043 mFocusedDisplayId) != mIneligibleDisplaysForPointerCapture.end()) {
6044 ALOGW("Ignoring request to enable Pointer Capture: display is not eligible");
6045 return;
6046 }
6047 }
6048
Prabir Pradhan99987712020-11-10 18:43:05 -08006049 setPointerCaptureLocked(enabled);
6050 } // release lock
6051
6052 // Wake the thread to process command entries.
6053 mLooper->wake();
6054}
6055
Christine Franksb768bb42021-11-29 12:11:31 -08006056void InputDispatcher::setDisplayEligibilityForPointerCapture(int32_t displayId, bool isEligible) {
6057 { // acquire lock
6058 std::scoped_lock _l(mLock);
6059 std::erase(mIneligibleDisplaysForPointerCapture, displayId);
6060 if (!isEligible) {
6061 mIneligibleDisplaysForPointerCapture.push_back(displayId);
6062 }
6063 } // release lock
6064}
6065
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006066std::optional<int32_t> InputDispatcher::findMonitorPidByTokenLocked(const sp<IBinder>& token) {
6067 for (const auto& [_, monitors] : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00006068 for (const Monitor& monitor : monitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07006069 if (monitor.inputChannel->getConnectionToken() == token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006070 return monitor.pid;
Michael Wright3dd60e22019-03-27 22:06:44 +00006071 }
6072 }
6073 }
6074 return std::nullopt;
6075}
6076
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006077std::shared_ptr<Connection> InputDispatcher::getConnectionLocked(
6078 const sp<IBinder>& inputConnectionToken) const {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07006079 if (inputConnectionToken == nullptr) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07006080 return nullptr;
Arthur Hung3b413f22018-10-26 18:05:34 +08006081 }
6082
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00006083 for (const auto& [token, connection] : mConnectionsByToken) {
6084 if (token == inputConnectionToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07006085 return connection;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006086 }
6087 }
Robert Carr4e670e52018-08-15 13:26:12 -07006088
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07006089 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006090}
6091
Siarhei Vishniakouad991402020-10-28 11:40:09 -05006092std::string InputDispatcher::getConnectionNameLocked(const sp<IBinder>& connectionToken) const {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006093 std::shared_ptr<Connection> connection = getConnectionLocked(connectionToken);
Siarhei Vishniakouad991402020-10-28 11:40:09 -05006094 if (connection == nullptr) {
6095 return "<nullptr>";
6096 }
6097 return connection->getInputChannelName();
6098}
6099
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006100void InputDispatcher::removeConnectionLocked(const std::shared_ptr<Connection>& connection) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006101 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00006102 mConnectionsByToken.erase(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07006103}
6104
Prabir Pradhancef936d2021-07-21 16:17:52 +00006105void InputDispatcher::doDispatchCycleFinishedCommand(nsecs_t finishTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006106 const std::shared_ptr<Connection>& connection,
6107 uint32_t seq, bool handled,
6108 nsecs_t consumeTime) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006109 // Handle post-event policy actions.
6110 std::deque<DispatchEntry*>::iterator dispatchEntryIt = connection->findWaitQueueEntry(seq);
6111 if (dispatchEntryIt == connection->waitQueue.end()) {
6112 return;
6113 }
6114 DispatchEntry* dispatchEntry = *dispatchEntryIt;
6115 const nsecs_t eventDuration = finishTime - dispatchEntry->deliveryTime;
6116 if (eventDuration > SLOW_EVENT_PROCESSING_WARNING_TIMEOUT) {
6117 ALOGI("%s spent %" PRId64 "ms processing %s", connection->getWindowName().c_str(),
6118 ns2ms(eventDuration), dispatchEntry->eventEntry->getDescription().c_str());
6119 }
6120 if (shouldReportFinishedEvent(*dispatchEntry, *connection)) {
6121 mLatencyTracker.trackFinishedEvent(dispatchEntry->eventEntry->id,
6122 connection->inputChannel->getConnectionToken(),
6123 dispatchEntry->deliveryTime, consumeTime, finishTime);
6124 }
6125
6126 bool restartEvent;
6127 if (dispatchEntry->eventEntry->type == EventEntry::Type::KEY) {
6128 KeyEntry& keyEntry = static_cast<KeyEntry&>(*(dispatchEntry->eventEntry));
6129 restartEvent =
6130 afterKeyEventLockedInterruptable(connection, dispatchEntry, keyEntry, handled);
6131 } else if (dispatchEntry->eventEntry->type == EventEntry::Type::MOTION) {
6132 MotionEntry& motionEntry = static_cast<MotionEntry&>(*(dispatchEntry->eventEntry));
6133 restartEvent = afterMotionEventLockedInterruptable(connection, dispatchEntry, motionEntry,
6134 handled);
6135 } else {
6136 restartEvent = false;
6137 }
6138
6139 // Dequeue the event and start the next cycle.
6140 // Because the lock might have been released, it is possible that the
6141 // contents of the wait queue to have been drained, so we need to double-check
6142 // a few things.
6143 dispatchEntryIt = connection->findWaitQueueEntry(seq);
6144 if (dispatchEntryIt != connection->waitQueue.end()) {
6145 dispatchEntry = *dispatchEntryIt;
6146 connection->waitQueue.erase(dispatchEntryIt);
6147 const sp<IBinder>& connectionToken = connection->inputChannel->getConnectionToken();
6148 mAnrTracker.erase(dispatchEntry->timeoutTime, connectionToken);
6149 if (!connection->responsive) {
6150 connection->responsive = isConnectionResponsive(*connection);
6151 if (connection->responsive) {
6152 // The connection was unresponsive, and now it's responsive.
6153 processConnectionResponsiveLocked(*connection);
6154 }
6155 }
6156 traceWaitQueueLength(*connection);
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08006157 if (restartEvent && connection->status == Connection::Status::NORMAL) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006158 connection->outboundQueue.push_front(dispatchEntry);
6159 traceOutboundQueueLength(*connection);
6160 } else {
6161 releaseDispatchEntry(dispatchEntry);
6162 }
6163 }
6164
6165 // Start the next dispatch cycle for this connection.
6166 startDispatchCycleLocked(now(), connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006167}
6168
Prabir Pradhancef936d2021-07-21 16:17:52 +00006169void InputDispatcher::sendFocusChangedCommandLocked(const sp<IBinder>& oldToken,
6170 const sp<IBinder>& newToken) {
6171 auto command = [this, oldToken, newToken]() REQUIRES(mLock) {
6172 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00006173 mPolicy.notifyFocusChanged(oldToken, newToken);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006174 };
6175 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08006176}
6177
Prabir Pradhancef936d2021-07-21 16:17:52 +00006178void InputDispatcher::sendDropWindowCommandLocked(const sp<IBinder>& token, float x, float y) {
6179 auto command = [this, token, x, y]() REQUIRES(mLock) {
6180 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00006181 mPolicy.notifyDropWindow(token, x, y);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006182 };
6183 postCommandLocked(std::move(command));
Robert Carrf759f162018-11-13 12:57:11 -08006184}
6185
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006186void InputDispatcher::onAnrLocked(const std::shared_ptr<Connection>& connection) {
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006187 if (connection == nullptr) {
6188 LOG_ALWAYS_FATAL("Caller must check for nullness");
6189 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006190 // Since we are allowing the policy to extend the timeout, maybe the waitQueue
6191 // is already healthy again. Don't raise ANR in this situation
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006192 if (connection->waitQueue.empty()) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006193 ALOGI("Not raising ANR because the connection %s has recovered",
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006194 connection->inputChannel->getName().c_str());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006195 return;
6196 }
6197 /**
6198 * The "oldestEntry" is the entry that was first sent to the application. That entry, however,
6199 * may not be the one that caused the timeout to occur. One possibility is that window timeout
6200 * has changed. This could cause newer entries to time out before the already dispatched
6201 * entries. In that situation, the newest entries caused ANR. But in all likelihood, the app
6202 * processes the events linearly. So providing information about the oldest entry seems to be
6203 * most useful.
6204 */
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006205 DispatchEntry* oldestEntry = *connection->waitQueue.begin();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006206 const nsecs_t currentWait = now() - oldestEntry->deliveryTime;
6207 std::string reason =
6208 android::base::StringPrintf("%s is not responding. Waited %" PRId64 "ms for %s",
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006209 connection->inputChannel->getName().c_str(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006210 ns2ms(currentWait),
6211 oldestEntry->eventEntry->getDescription().c_str());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006212 sp<IBinder> connectionToken = connection->inputChannel->getConnectionToken();
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -06006213 updateLastAnrStateLocked(getWindowHandleLocked(connectionToken), reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006214
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006215 processConnectionUnresponsiveLocked(*connection, std::move(reason));
6216
6217 // Stop waking up for events on this connection, it is already unresponsive
6218 cancelEventsForAnrLocked(connection);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006219}
6220
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05006221void InputDispatcher::onAnrLocked(std::shared_ptr<InputApplicationHandle> application) {
6222 std::string reason =
6223 StringPrintf("%s does not have a focused window", application->getName().c_str());
6224 updateLastAnrStateLocked(*application, reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006225
Prabir Pradhancef936d2021-07-21 16:17:52 +00006226 auto command = [this, application = std::move(application)]() REQUIRES(mLock) {
6227 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00006228 mPolicy.notifyNoFocusedWindowAnr(application);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006229 };
6230 postCommandLocked(std::move(command));
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00006231}
6232
chaviw98318de2021-05-19 16:45:23 -05006233void InputDispatcher::updateLastAnrStateLocked(const sp<WindowInfoHandle>& window,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006234 const std::string& reason) {
6235 const std::string windowLabel = getApplicationWindowLabel(nullptr, window);
6236 updateLastAnrStateLocked(windowLabel, reason);
6237}
6238
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05006239void InputDispatcher::updateLastAnrStateLocked(const InputApplicationHandle& application,
6240 const std::string& reason) {
6241 const std::string windowLabel = getApplicationWindowLabel(&application, nullptr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006242 updateLastAnrStateLocked(windowLabel, reason);
6243}
6244
6245void InputDispatcher::updateLastAnrStateLocked(const std::string& windowLabel,
6246 const std::string& reason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006247 // Capture a record of the InputDispatcher state at the time of the ANR.
Yi Kong9b14ac62018-07-17 13:48:38 -07006248 time_t t = time(nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006249 struct tm tm;
6250 localtime_r(&t, &tm);
6251 char timestr[64];
6252 strftime(timestr, sizeof(timestr), "%F %T", &tm);
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006253 mLastAnrState.clear();
6254 mLastAnrState += INDENT "ANR:\n";
6255 mLastAnrState += StringPrintf(INDENT2 "Time: %s\n", timestr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006256 mLastAnrState += StringPrintf(INDENT2 "Reason: %s\n", reason.c_str());
6257 mLastAnrState += StringPrintf(INDENT2 "Window: %s\n", windowLabel.c_str());
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006258 dumpDispatchStateLocked(mLastAnrState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006259}
6260
Prabir Pradhancef936d2021-07-21 16:17:52 +00006261void InputDispatcher::doInterceptKeyBeforeDispatchingCommand(const sp<IBinder>& focusedWindowToken,
6262 KeyEntry& entry) {
6263 const KeyEvent event = createKeyEvent(entry);
6264 nsecs_t delay = 0;
6265 { // release lock
6266 scoped_unlock unlock(mLock);
6267 android::base::Timer t;
Prabir Pradhana41d2442023-04-20 21:30:40 +00006268 delay = mPolicy.interceptKeyBeforeDispatching(focusedWindowToken, event, entry.policyFlags);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006269 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
6270 ALOGW("Excessive delay in interceptKeyBeforeDispatching; took %s ms",
6271 std::to_string(t.duration().count()).c_str());
6272 }
6273 } // acquire lock
Michael Wrightd02c5b62014-02-10 15:10:22 -08006274
6275 if (delay < 0) {
Michael Wright5caf55a2022-11-24 22:31:42 +00006276 entry.interceptKeyResult = KeyEntry::InterceptKeyResult::SKIP;
Prabir Pradhancef936d2021-07-21 16:17:52 +00006277 } else if (delay == 0) {
Michael Wright5caf55a2022-11-24 22:31:42 +00006278 entry.interceptKeyResult = KeyEntry::InterceptKeyResult::CONTINUE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006279 } else {
Michael Wright5caf55a2022-11-24 22:31:42 +00006280 entry.interceptKeyResult = KeyEntry::InterceptKeyResult::TRY_AGAIN_LATER;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006281 entry.interceptKeyWakeupTime = now() + delay;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006282 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006283}
6284
Prabir Pradhancef936d2021-07-21 16:17:52 +00006285void InputDispatcher::sendWindowUnresponsiveCommandLocked(const sp<IBinder>& token,
Prabir Pradhanedd96402022-02-15 01:46:16 -08006286 std::optional<int32_t> pid,
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006287 std::string reason) {
Prabir Pradhanedd96402022-02-15 01:46:16 -08006288 auto command = [this, token, pid, reason = std::move(reason)]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006289 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00006290 mPolicy.notifyWindowUnresponsive(token, pid, reason);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006291 };
6292 postCommandLocked(std::move(command));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006293}
6294
Prabir Pradhanedd96402022-02-15 01:46:16 -08006295void InputDispatcher::sendWindowResponsiveCommandLocked(const sp<IBinder>& token,
6296 std::optional<int32_t> pid) {
6297 auto command = [this, token, pid]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006298 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00006299 mPolicy.notifyWindowResponsive(token, pid);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006300 };
6301 postCommandLocked(std::move(command));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006302}
6303
6304/**
6305 * Tell the policy that a connection has become unresponsive so that it can start ANR.
6306 * Check whether the connection of interest is a monitor or a window, and add the corresponding
6307 * command entry to the command queue.
6308 */
6309void InputDispatcher::processConnectionUnresponsiveLocked(const Connection& connection,
6310 std::string reason) {
6311 const sp<IBinder>& connectionToken = connection.inputChannel->getConnectionToken();
Prabir Pradhanedd96402022-02-15 01:46:16 -08006312 std::optional<int32_t> pid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006313 if (connection.monitor) {
6314 ALOGW("Monitor %s is unresponsive: %s", connection.inputChannel->getName().c_str(),
6315 reason.c_str());
Prabir Pradhanedd96402022-02-15 01:46:16 -08006316 pid = findMonitorPidByTokenLocked(connectionToken);
6317 } else {
6318 // The connection is a window
6319 ALOGW("Window %s is unresponsive: %s", connection.inputChannel->getName().c_str(),
6320 reason.c_str());
6321 const sp<WindowInfoHandle> handle = getWindowHandleLocked(connectionToken);
6322 if (handle != nullptr) {
6323 pid = handle->getInfo()->ownerPid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006324 }
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006325 }
Prabir Pradhanedd96402022-02-15 01:46:16 -08006326 sendWindowUnresponsiveCommandLocked(connectionToken, pid, std::move(reason));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006327}
6328
6329/**
6330 * Tell the policy that a connection has become responsive so that it can stop ANR.
6331 */
6332void InputDispatcher::processConnectionResponsiveLocked(const Connection& connection) {
6333 const sp<IBinder>& connectionToken = connection.inputChannel->getConnectionToken();
Prabir Pradhanedd96402022-02-15 01:46:16 -08006334 std::optional<int32_t> pid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006335 if (connection.monitor) {
Prabir Pradhanedd96402022-02-15 01:46:16 -08006336 pid = findMonitorPidByTokenLocked(connectionToken);
6337 } else {
6338 // The connection is a window
6339 const sp<WindowInfoHandle> handle = getWindowHandleLocked(connectionToken);
6340 if (handle != nullptr) {
6341 pid = handle->getInfo()->ownerPid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006342 }
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006343 }
Prabir Pradhanedd96402022-02-15 01:46:16 -08006344 sendWindowResponsiveCommandLocked(connectionToken, pid);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006345}
6346
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006347bool InputDispatcher::afterKeyEventLockedInterruptable(
6348 const std::shared_ptr<Connection>& connection, DispatchEntry* dispatchEntry,
6349 KeyEntry& keyEntry, bool handled) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006350 if (keyEntry.flags & AKEY_EVENT_FLAG_FALLBACK) {
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006351 if (!handled) {
6352 // Report the key as unhandled, since the fallback was not handled.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006353 mReporter->reportUnhandledKey(keyEntry.id);
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006354 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006355 return false;
6356 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006357
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006358 // Get the fallback key state.
6359 // Clear it out after dispatching the UP.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006360 int32_t originalKeyCode = keyEntry.keyCode;
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006361 std::optional<int32_t> fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006362 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006363 connection->inputState.removeFallbackKey(originalKeyCode);
6364 }
6365
6366 if (handled || !dispatchEntry->hasForegroundTarget()) {
6367 // If the application handles the original key for which we previously
6368 // generated a fallback or if the window is not a foreground window,
6369 // then cancel the associated fallback key, if any.
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006370 if (fallbackKeyCode) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006371 // Dispatch the unhandled key to the policy with the cancel flag.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006372 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6373 ALOGD("Unhandled key event: Asking policy to cancel fallback action. "
6374 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6375 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount,
6376 keyEntry.policyFlags);
6377 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006378 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006379 event.setFlags(event.getFlags() | AKEY_EVENT_FLAG_CANCELED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006380
6381 mLock.unlock();
6382
Prabir Pradhana41d2442023-04-20 21:30:40 +00006383 if (const auto unhandledKeyFallback =
6384 mPolicy.dispatchUnhandledKey(connection->inputChannel->getConnectionToken(),
6385 event, keyEntry.policyFlags);
6386 unhandledKeyFallback) {
6387 event = *unhandledKeyFallback;
6388 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006389
6390 mLock.lock();
6391
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006392 // Cancel the fallback key.
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006393 if (*fallbackKeyCode != AKEYCODE_UNKNOWN) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00006394 CancelationOptions options(CancelationOptions::Mode::CANCEL_FALLBACK_EVENTS,
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006395 "application handled the original non-fallback key "
6396 "or is no longer a foreground target, "
6397 "canceling previously dispatched fallback key");
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006398 options.keyCode = *fallbackKeyCode;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006399 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006400 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006401 connection->inputState.removeFallbackKey(originalKeyCode);
6402 }
6403 } else {
6404 // If the application did not handle a non-fallback key, first check
6405 // that we are in a good state to perform unhandled key event processing
6406 // Then ask the policy what to do with it.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006407 bool initialDown = keyEntry.action == AKEY_EVENT_ACTION_DOWN && keyEntry.repeatCount == 0;
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006408 if (!fallbackKeyCode && !initialDown) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006409 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6410 ALOGD("Unhandled key event: Skipping unhandled key event processing "
6411 "since this is not an initial down. "
6412 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6413 originalKeyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
6414 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006415 return false;
6416 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006417
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006418 // Dispatch the unhandled key to the policy.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006419 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6420 ALOGD("Unhandled key event: Asking policy to perform fallback action. "
6421 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6422 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
6423 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006424 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006425
6426 mLock.unlock();
6427
Prabir Pradhana41d2442023-04-20 21:30:40 +00006428 bool fallback = false;
6429 if (auto fb = mPolicy.dispatchUnhandledKey(connection->inputChannel->getConnectionToken(),
6430 event, keyEntry.policyFlags);
6431 fb) {
6432 fallback = true;
6433 event = *fb;
6434 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006435
6436 mLock.lock();
6437
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08006438 if (connection->status != Connection::Status::NORMAL) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006439 connection->inputState.removeFallbackKey(originalKeyCode);
6440 return false;
6441 }
6442
6443 // Latch the fallback keycode for this key on an initial down.
6444 // The fallback keycode cannot change at any other point in the lifecycle.
6445 if (initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006446 if (fallback) {
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006447 *fallbackKeyCode = event.getKeyCode();
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006448 } else {
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006449 *fallbackKeyCode = AKEYCODE_UNKNOWN;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006450 }
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006451 connection->inputState.setFallbackKey(originalKeyCode, *fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006452 }
6453
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006454 ALOG_ASSERT(fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006455
6456 // Cancel the fallback key if the policy decides not to send it anymore.
6457 // We will continue to dispatch the key to the policy but we will no
6458 // longer dispatch a fallback key to the application.
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006459 if (*fallbackKeyCode != AKEYCODE_UNKNOWN &&
6460 (!fallback || *fallbackKeyCode != event.getKeyCode())) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006461 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6462 if (fallback) {
6463 ALOGD("Unhandled key event: Policy requested to send key %d"
6464 "as a fallback for %d, but on the DOWN it had requested "
6465 "to send %d instead. Fallback canceled.",
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006466 event.getKeyCode(), originalKeyCode, *fallbackKeyCode);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006467 } else {
6468 ALOGD("Unhandled key event: Policy did not request fallback for %d, "
6469 "but on the DOWN it had requested to send %d. "
6470 "Fallback canceled.",
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006471 originalKeyCode, *fallbackKeyCode);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006472 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006473 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006474
Michael Wrightfb04fd52022-11-24 22:31:11 +00006475 CancelationOptions options(CancelationOptions::Mode::CANCEL_FALLBACK_EVENTS,
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006476 "canceling fallback, policy no longer desires it");
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006477 options.keyCode = *fallbackKeyCode;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006478 synthesizeCancelationEventsForConnectionLocked(connection, options);
6479
6480 fallback = false;
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006481 *fallbackKeyCode = AKEYCODE_UNKNOWN;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006482 if (keyEntry.action != AKEY_EVENT_ACTION_UP) {
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006483 connection->inputState.setFallbackKey(originalKeyCode, *fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006484 }
6485 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006486
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006487 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6488 {
6489 std::string msg;
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006490 const std::map<int32_t, int32_t>& fallbackKeys =
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006491 connection->inputState.getFallbackKeys();
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006492 for (const auto& [key, value] : fallbackKeys) {
6493 msg += StringPrintf(", %d->%d", key, value);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006494 }
6495 ALOGD("Unhandled key event: %zu currently tracked fallback keys%s.",
6496 fallbackKeys.size(), msg.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006497 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006498 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006499
6500 if (fallback) {
6501 // Restart the dispatch cycle using the fallback key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006502 keyEntry.eventTime = event.getEventTime();
6503 keyEntry.deviceId = event.getDeviceId();
6504 keyEntry.source = event.getSource();
6505 keyEntry.displayId = event.getDisplayId();
6506 keyEntry.flags = event.getFlags() | AKEY_EVENT_FLAG_FALLBACK;
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006507 keyEntry.keyCode = *fallbackKeyCode;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006508 keyEntry.scanCode = event.getScanCode();
6509 keyEntry.metaState = event.getMetaState();
6510 keyEntry.repeatCount = event.getRepeatCount();
6511 keyEntry.downTime = event.getDownTime();
6512 keyEntry.syntheticRepeat = false;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006513
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006514 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6515 ALOGD("Unhandled key event: Dispatching fallback key. "
6516 "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006517 originalKeyCode, *fallbackKeyCode, keyEntry.metaState);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006518 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006519 return true; // restart the event
6520 } else {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006521 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6522 ALOGD("Unhandled key event: No fallback key.");
6523 }
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006524
6525 // Report the key as unhandled, since there is no fallback key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006526 mReporter->reportUnhandledKey(keyEntry.id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006527 }
6528 }
6529 return false;
6530}
6531
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006532bool InputDispatcher::afterMotionEventLockedInterruptable(
6533 const std::shared_ptr<Connection>& connection, DispatchEntry* dispatchEntry,
6534 MotionEntry& motionEntry, bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006535 return false;
6536}
6537
Michael Wrightd02c5b62014-02-10 15:10:22 -08006538void InputDispatcher::traceInboundQueueLengthLocked() {
6539 if (ATRACE_ENABLED()) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07006540 ATRACE_INT("iq", mInboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006541 }
6542}
6543
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006544void InputDispatcher::traceOutboundQueueLength(const Connection& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006545 if (ATRACE_ENABLED()) {
6546 char counterName[40];
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006547 snprintf(counterName, sizeof(counterName), "oq:%s", connection.getWindowName().c_str());
6548 ATRACE_INT(counterName, connection.outboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006549 }
6550}
6551
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006552void InputDispatcher::traceWaitQueueLength(const Connection& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006553 if (ATRACE_ENABLED()) {
6554 char counterName[40];
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006555 snprintf(counterName, sizeof(counterName), "wq:%s", connection.getWindowName().c_str());
6556 ATRACE_INT(counterName, connection.waitQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006557 }
6558}
6559
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006560void InputDispatcher::dump(std::string& dump) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006561 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006562
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006563 dump += "Input Dispatcher State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08006564 dumpDispatchStateLocked(dump);
6565
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006566 if (!mLastAnrState.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006567 dump += "\nInput Dispatcher State at time of last ANR:\n";
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006568 dump += mLastAnrState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006569 }
6570}
6571
6572void InputDispatcher::monitor() {
6573 // Acquire and release the lock to ensure that the dispatcher has not deadlocked.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006574 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006575 mLooper->wake();
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006576 mDispatcherIsAlive.wait(_l);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006577}
6578
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08006579/**
6580 * Wake up the dispatcher and wait until it processes all events and commands.
6581 * The notification of mDispatcherEnteredIdle is guaranteed to happen after wake(), so
6582 * this method can be safely called from any thread, as long as you've ensured that
6583 * the work you are interested in completing has already been queued.
6584 */
6585bool InputDispatcher::waitForIdle() {
6586 /**
6587 * Timeout should represent the longest possible time that a device might spend processing
6588 * events and commands.
6589 */
6590 constexpr std::chrono::duration TIMEOUT = 100ms;
6591 std::unique_lock lock(mLock);
6592 mLooper->wake();
6593 std::cv_status result = mDispatcherEnteredIdle.wait_for(lock, TIMEOUT);
6594 return result == std::cv_status::no_timeout;
6595}
6596
Vishnu Naire798b472020-07-23 13:52:21 -07006597/**
6598 * Sets focus to the window identified by the token. This must be called
6599 * after updating any input window handles.
6600 *
6601 * Params:
6602 * request.token - input channel token used to identify the window that should gain focus.
6603 * request.focusedToken - the token that the caller expects currently to be focused. If the
6604 * specified token does not match the currently focused window, this request will be dropped.
6605 * If the specified focused token matches the currently focused window, the call will succeed.
6606 * Set this to "null" if this call should succeed no matter what the currently focused token is.
6607 * request.timestamp - SYSTEM_TIME_MONOTONIC timestamp in nanos set by the client (wm)
6608 * when requesting the focus change. This determines which request gets
6609 * precedence if there is a focus change request from another source such as pointer down.
6610 */
Vishnu Nair958da932020-08-21 17:12:37 -07006611void InputDispatcher::setFocusedWindow(const FocusRequest& request) {
6612 { // acquire lock
6613 std::scoped_lock _l(mLock);
Vishnu Nairc519ff72021-01-21 08:23:08 -08006614 std::optional<FocusResolver::FocusChanges> changes =
6615 mFocusResolver.setFocusedWindow(request, getWindowHandlesLocked(request.displayId));
6616 if (changes) {
6617 onFocusChangedLocked(*changes);
Vishnu Nair958da932020-08-21 17:12:37 -07006618 }
6619 } // release lock
6620 // Wake up poll loop since it may need to make new input dispatching choices.
6621 mLooper->wake();
6622}
6623
Vishnu Nairc519ff72021-01-21 08:23:08 -08006624void InputDispatcher::onFocusChangedLocked(const FocusResolver::FocusChanges& changes) {
6625 if (changes.oldFocus) {
6626 std::shared_ptr<InputChannel> focusedInputChannel = getInputChannelLocked(changes.oldFocus);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006627 if (focusedInputChannel) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00006628 CancelationOptions options(CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS,
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006629 "focus left window");
6630 synthesizeCancelationEventsForInputChannelLocked(focusedInputChannel, options);
Harry Cutts33476232023-01-30 19:57:29 +00006631 enqueueFocusEventLocked(changes.oldFocus, /*hasFocus=*/false, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006632 }
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006633 }
Vishnu Nairc519ff72021-01-21 08:23:08 -08006634 if (changes.newFocus) {
Harry Cutts33476232023-01-30 19:57:29 +00006635 enqueueFocusEventLocked(changes.newFocus, /*hasFocus=*/true, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006636 }
6637
Prabir Pradhan99987712020-11-10 18:43:05 -08006638 // If a window has pointer capture, then it must have focus. We need to ensure that this
6639 // contract is upheld when pointer capture is being disabled due to a loss of window focus.
6640 // If the window loses focus before it loses pointer capture, then the window can be in a state
6641 // where it has pointer capture but not focus, violating the contract. Therefore we must
6642 // dispatch the pointer capture event before the focus event. Since focus events are added to
6643 // the front of the queue (above), we add the pointer capture event to the front of the queue
6644 // after the focus events are added. This ensures the pointer capture event ends up at the
6645 // front.
6646 disablePointerCaptureForcedLocked();
6647
Vishnu Nairc519ff72021-01-21 08:23:08 -08006648 if (mFocusedDisplayId == changes.displayId) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006649 sendFocusChangedCommandLocked(changes.oldFocus, changes.newFocus);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006650 }
6651}
Vishnu Nair958da932020-08-21 17:12:37 -07006652
Prabir Pradhan99987712020-11-10 18:43:05 -08006653void InputDispatcher::disablePointerCaptureForcedLocked() {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006654 if (!mCurrentPointerCaptureRequest.enable && !mWindowTokenWithPointerCapture) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006655 return;
6656 }
6657
6658 ALOGD_IF(DEBUG_FOCUS, "Disabling Pointer Capture because the window lost focus.");
6659
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006660 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006661 setPointerCaptureLocked(false);
6662 }
6663
6664 if (!mWindowTokenWithPointerCapture) {
6665 // No need to send capture changes because no window has capture.
6666 return;
6667 }
6668
6669 if (mPendingEvent != nullptr) {
6670 // Move the pending event to the front of the queue. This will give the chance
6671 // for the pending event to be dropped if it is a captured event.
6672 mInboundQueue.push_front(mPendingEvent);
6673 mPendingEvent = nullptr;
6674 }
6675
6676 auto entry = std::make_unique<PointerCaptureChangedEntry>(mIdGenerator.nextId(), now(),
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006677 mCurrentPointerCaptureRequest);
Prabir Pradhan99987712020-11-10 18:43:05 -08006678 mInboundQueue.push_front(std::move(entry));
6679}
6680
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006681void InputDispatcher::setPointerCaptureLocked(bool enable) {
6682 mCurrentPointerCaptureRequest.enable = enable;
6683 mCurrentPointerCaptureRequest.seq++;
6684 auto command = [this, request = mCurrentPointerCaptureRequest]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006685 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00006686 mPolicy.setPointerCapture(request);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006687 };
6688 postCommandLocked(std::move(command));
Prabir Pradhan99987712020-11-10 18:43:05 -08006689}
6690
Vishnu Nair599f1412021-06-21 10:39:58 -07006691void InputDispatcher::displayRemoved(int32_t displayId) {
6692 { // acquire lock
6693 std::scoped_lock _l(mLock);
6694 // Set an empty list to remove all handles from the specific display.
6695 setInputWindowsLocked(/* window handles */ {}, displayId);
6696 setFocusedApplicationLocked(displayId, nullptr);
6697 // Call focus resolver to clean up stale requests. This must be called after input windows
6698 // have been removed for the removed display.
6699 mFocusResolver.displayRemoved(displayId);
Christine Franksb768bb42021-11-29 12:11:31 -08006700 // Reset pointer capture eligibility, regardless of previous state.
6701 std::erase(mIneligibleDisplaysForPointerCapture, displayId);
Antonio Kantek15beb512022-06-13 22:35:41 +00006702 // Remove the associated touch mode state.
6703 mTouchModePerDisplay.erase(displayId);
Vishnu Nair599f1412021-06-21 10:39:58 -07006704 } // release lock
6705
6706 // Wake up poll loop since it may need to make new input dispatching choices.
6707 mLooper->wake();
6708}
6709
Patrick Williamsd828f302023-04-28 17:52:08 -05006710void InputDispatcher::onWindowInfosChanged(const gui::WindowInfosUpdate& update) {
chaviw15fab6f2021-06-07 14:15:52 -05006711 // The listener sends the windows as a flattened array. Separate the windows by display for
6712 // more convenient parsing.
6713 std::unordered_map<int32_t, std::vector<sp<WindowInfoHandle>>> handlesPerDisplay;
Patrick Williamsd828f302023-04-28 17:52:08 -05006714 for (const auto& info : update.windowInfos) {
chaviw15fab6f2021-06-07 14:15:52 -05006715 handlesPerDisplay.emplace(info.displayId, std::vector<sp<WindowInfoHandle>>());
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07006716 handlesPerDisplay[info.displayId].push_back(sp<WindowInfoHandle>::make(info));
chaviw15fab6f2021-06-07 14:15:52 -05006717 }
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006718
6719 { // acquire lock
6720 std::scoped_lock _l(mLock);
Prabir Pradhan814fe082022-07-22 20:22:18 +00006721
6722 // Ensure that we have an entry created for all existing displays so that if a displayId has
6723 // no windows, we can tell that the windows were removed from the display.
6724 for (const auto& [displayId, _] : mWindowHandlesByDisplay) {
6725 handlesPerDisplay[displayId];
6726 }
6727
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006728 mDisplayInfos.clear();
Patrick Williamsd828f302023-04-28 17:52:08 -05006729 for (const auto& displayInfo : update.displayInfos) {
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006730 mDisplayInfos.emplace(displayInfo.displayId, displayInfo);
6731 }
6732
6733 for (const auto& [displayId, handles] : handlesPerDisplay) {
6734 setInputWindowsLocked(handles, displayId);
6735 }
Patrick Williams9464b2c2023-05-23 11:22:04 -05006736
6737 if (update.vsyncId < mWindowInfosVsyncId) {
6738 ALOGE("Received out of order window infos update. Last update vsync id: %" PRId64
6739 ", current update vsync id: %" PRId64,
6740 mWindowInfosVsyncId, update.vsyncId);
6741 }
6742 mWindowInfosVsyncId = update.vsyncId;
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006743 }
6744 // Wake up poll loop since it may need to make new input dispatching choices.
6745 mLooper->wake();
chaviw15fab6f2021-06-07 14:15:52 -05006746}
6747
Vishnu Nair062a8672021-09-03 16:07:44 -07006748bool InputDispatcher::shouldDropInput(
6749 const EventEntry& entry, const sp<android::gui::WindowInfoHandle>& windowHandle) const {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006750 if (windowHandle->getInfo()->inputConfig.test(WindowInfo::InputConfig::DROP_INPUT) ||
6751 (windowHandle->getInfo()->inputConfig.test(
6752 WindowInfo::InputConfig::DROP_INPUT_IF_OBSCURED) &&
Vishnu Nair062a8672021-09-03 16:07:44 -07006753 isWindowObscuredLocked(windowHandle))) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006754 ALOGW("Dropping %s event targeting %s as requested by the input configuration {%s} on "
6755 "display %" PRId32 ".",
Vishnu Nair062a8672021-09-03 16:07:44 -07006756 ftl::enum_string(entry.type).c_str(), windowHandle->getName().c_str(),
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006757 windowHandle->getInfo()->inputConfig.string().c_str(),
Vishnu Nair062a8672021-09-03 16:07:44 -07006758 windowHandle->getInfo()->displayId);
6759 return true;
6760 }
6761 return false;
6762}
6763
Siarhei Vishniakou18050092021-09-01 13:32:49 -07006764void InputDispatcher::DispatcherWindowListener::onWindowInfosChanged(
Patrick Williamsd828f302023-04-28 17:52:08 -05006765 const gui::WindowInfosUpdate& update) {
6766 mDispatcher.onWindowInfosChanged(update);
Siarhei Vishniakou18050092021-09-01 13:32:49 -07006767}
6768
Arthur Hungdfd528e2021-12-08 13:23:04 +00006769void InputDispatcher::cancelCurrentTouch() {
6770 {
6771 std::scoped_lock _l(mLock);
6772 ALOGD("Canceling all ongoing pointer gestures on all displays.");
Michael Wrightfb04fd52022-11-24 22:31:11 +00006773 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
Arthur Hungdfd528e2021-12-08 13:23:04 +00006774 "cancel current touch");
6775 synthesizeCancelationEventsForAllConnectionsLocked(options);
6776
6777 mTouchStatesByDisplay.clear();
Arthur Hungdfd528e2021-12-08 13:23:04 +00006778 }
6779 // Wake up poll loop since there might be work to do.
6780 mLooper->wake();
6781}
6782
Prabir Pradhan87112a72023-04-20 19:13:39 +00006783void InputDispatcher::requestRefreshConfiguration() {
Prabir Pradhana41d2442023-04-20 21:30:40 +00006784 InputDispatcherConfiguration config = mPolicy.getDispatcherConfiguration();
Prabir Pradhan87112a72023-04-20 19:13:39 +00006785
6786 std::scoped_lock _l(mLock);
6787 mConfig = config;
6788}
6789
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006790void InputDispatcher::setMonitorDispatchingTimeoutForTest(std::chrono::nanoseconds timeout) {
6791 std::scoped_lock _l(mLock);
6792 mMonitorDispatchingTimeout = timeout;
6793}
6794
Arthur Hungc539dbb2022-12-08 07:45:36 +00006795void InputDispatcher::slipWallpaperTouch(ftl::Flags<InputTarget::Flags> targetFlags,
6796 const sp<WindowInfoHandle>& oldWindowHandle,
6797 const sp<WindowInfoHandle>& newWindowHandle,
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08006798 TouchState& state, int32_t pointerId,
Siarhei Vishniakoubf880522023-05-01 11:03:22 -07006799 std::vector<InputTarget>& targets) const {
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08006800 std::bitset<MAX_POINTER_ID + 1> pointerIds;
6801 pointerIds.set(pointerId);
Arthur Hungc539dbb2022-12-08 07:45:36 +00006802 const bool oldHasWallpaper = oldWindowHandle->getInfo()->inputConfig.test(
6803 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
6804 const bool newHasWallpaper = targetFlags.test(InputTarget::Flags::FOREGROUND) &&
6805 newWindowHandle->getInfo()->inputConfig.test(
6806 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
6807 const sp<WindowInfoHandle> oldWallpaper =
6808 oldHasWallpaper ? state.getWallpaperWindow() : nullptr;
6809 const sp<WindowInfoHandle> newWallpaper =
6810 newHasWallpaper ? findWallpaperWindowBelow(newWindowHandle) : nullptr;
6811 if (oldWallpaper == newWallpaper) {
6812 return;
6813 }
6814
6815 if (oldWallpaper != nullptr) {
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08006816 const TouchedWindow& oldTouchedWindow = state.getTouchedWindow(oldWallpaper);
6817 addWindowTargetLocked(oldWallpaper,
6818 oldTouchedWindow.targetFlags |
6819 InputTarget::Flags::DISPATCH_AS_SLIPPERY_EXIT,
6820 pointerIds, oldTouchedWindow.firstDownTimeInTarget, targets);
6821 state.removeTouchedPointerFromWindow(pointerId, oldWallpaper);
Arthur Hungc539dbb2022-12-08 07:45:36 +00006822 }
6823
6824 if (newWallpaper != nullptr) {
6825 state.addOrUpdateWindow(newWallpaper,
6826 InputTarget::Flags::DISPATCH_AS_SLIPPERY_ENTER |
6827 InputTarget::Flags::WINDOW_IS_OBSCURED |
6828 InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED,
6829 pointerIds);
6830 }
6831}
6832
6833void InputDispatcher::transferWallpaperTouch(ftl::Flags<InputTarget::Flags> oldTargetFlags,
6834 ftl::Flags<InputTarget::Flags> newTargetFlags,
6835 const sp<WindowInfoHandle> fromWindowHandle,
6836 const sp<WindowInfoHandle> toWindowHandle,
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08006837 TouchState& state,
6838 std::bitset<MAX_POINTER_ID + 1> pointerIds) {
Arthur Hungc539dbb2022-12-08 07:45:36 +00006839 const bool oldHasWallpaper = oldTargetFlags.test(InputTarget::Flags::FOREGROUND) &&
6840 fromWindowHandle->getInfo()->inputConfig.test(
6841 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
6842 const bool newHasWallpaper = newTargetFlags.test(InputTarget::Flags::FOREGROUND) &&
6843 toWindowHandle->getInfo()->inputConfig.test(
6844 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
6845
6846 const sp<WindowInfoHandle> oldWallpaper =
6847 oldHasWallpaper ? state.getWallpaperWindow() : nullptr;
6848 const sp<WindowInfoHandle> newWallpaper =
6849 newHasWallpaper ? findWallpaperWindowBelow(toWindowHandle) : nullptr;
6850 if (oldWallpaper == newWallpaper) {
6851 return;
6852 }
6853
6854 if (oldWallpaper != nullptr) {
6855 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
6856 "transferring touch focus to another window");
6857 state.removeWindowByToken(oldWallpaper->getToken());
6858 synthesizeCancelationEventsForWindowLocked(oldWallpaper, options);
6859 }
6860
6861 if (newWallpaper != nullptr) {
6862 nsecs_t downTimeInTarget = now();
6863 ftl::Flags<InputTarget::Flags> wallpaperFlags =
6864 oldTargetFlags & (InputTarget::Flags::SPLIT | InputTarget::Flags::DISPATCH_AS_IS);
6865 wallpaperFlags |= InputTarget::Flags::WINDOW_IS_OBSCURED |
6866 InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED;
6867 state.addOrUpdateWindow(newWallpaper, wallpaperFlags, pointerIds, downTimeInTarget);
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006868 std::shared_ptr<Connection> wallpaperConnection =
6869 getConnectionLocked(newWallpaper->getToken());
Arthur Hungc539dbb2022-12-08 07:45:36 +00006870 if (wallpaperConnection != nullptr) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006871 std::shared_ptr<Connection> toConnection =
6872 getConnectionLocked(toWindowHandle->getToken());
Arthur Hungc539dbb2022-12-08 07:45:36 +00006873 toConnection->inputState.mergePointerStateTo(wallpaperConnection->inputState);
6874 synthesizePointerDownEventsForConnectionLocked(downTimeInTarget, wallpaperConnection,
6875 wallpaperFlags);
6876 }
6877 }
6878}
6879
6880sp<WindowInfoHandle> InputDispatcher::findWallpaperWindowBelow(
6881 const sp<WindowInfoHandle>& windowHandle) const {
6882 const std::vector<sp<WindowInfoHandle>>& windowHandles =
6883 getWindowHandlesLocked(windowHandle->getInfo()->displayId);
6884 bool foundWindow = false;
6885 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
6886 if (!foundWindow && otherHandle != windowHandle) {
6887 continue;
6888 }
6889 if (windowHandle == otherHandle) {
6890 foundWindow = true;
6891 continue;
6892 }
6893
6894 if (otherHandle->getInfo()->inputConfig.test(WindowInfo::InputConfig::IS_WALLPAPER)) {
6895 return otherHandle;
6896 }
6897 }
6898 return nullptr;
6899}
6900
Garfield Tane84e6f92019-08-29 17:28:41 -07006901} // namespace android::inputdispatcher