blob: 2923a3cfa7011d89b85b0871ab342d2610744c2e [file] [log] [blame]
Michael Wrightd02c5b62014-02-10 15:10:22 -08001/*
2 * Copyright (C) 2010 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#define LOG_TAG "InputDispatcher"
18#define ATRACE_TAG ATRACE_TAG_INPUT
19
John Recke0710582019-09-26 13:46:12 -070020#define LOG_NDEBUG 1
Michael Wrightd02c5b62014-02-10 15:10:22 -080021
Michael Wright2b3c3302018-03-02 17:19:13 +000022#include <android-base/chrono_utils.h>
Siarhei Vishniakoud010b012023-01-18 15:00:53 -080023#include <android-base/logging.h>
Peter Collingbourneb04b9b82021-02-08 12:09:47 -080024#include <android-base/properties.h>
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080025#include <android-base/stringprintf.h>
Siarhei Vishniakou70622952020-07-30 11:17:23 -050026#include <android/os/IInputConstants.h>
Robert Carr4e670e52018-08-15 13:26:12 -070027#include <binder/Binder.h>
Dominik Laskowski75788452021-02-09 18:51:25 -080028#include <ftl/enum.h>
Siarhei Vishniakou5c02a712023-05-15 15:45:02 -070029#include <log/log_event_list.h>
Siarhei Vishniakou31977182022-09-30 08:51:23 -070030#if defined(__ANDROID__)
chaviw15fab6f2021-06-07 14:15:52 -050031#include <gui/SurfaceComposerClient.h>
Siarhei Vishniakou31977182022-09-30 08:51:23 -070032#endif
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -080033#include <input/InputDevice.h>
Siarhei Vishniakou6e1e9872022-11-08 17:51:35 -080034#include <input/PrintTools.h>
tyiu1573a672023-02-21 22:38:32 +000035#include <openssl/mem.h>
Garfield Tan0fc2fa72019-08-29 17:22:15 -070036#include <powermanager/PowerManager.h>
Michael Wright44753b12020-07-08 13:48:11 +010037#include <unistd.h>
Garfield Tan0fc2fa72019-08-29 17:22:15 -070038#include <utils/Trace.h>
Michael Wrightd02c5b62014-02-10 15:10:22 -080039
Michael Wright44753b12020-07-08 13:48:11 +010040#include <cerrno>
41#include <cinttypes>
42#include <climits>
43#include <cstddef>
44#include <ctime>
45#include <queue>
46#include <sstream>
47
48#include "Connection.h"
Arthur Hung1a1007b2022-05-11 07:15:01 +000049#include "DebugConfig.h"
Chris Yef59a2f42020-10-16 12:55:26 -070050#include "InputDispatcher.h"
Michael Wright44753b12020-07-08 13:48:11 +010051
Michael Wrightd02c5b62014-02-10 15:10:22 -080052#define INDENT " "
53#define INDENT2 " "
54#define INDENT3 " "
55#define INDENT4 " "
56
Siarhei Vishniakou253f4642022-11-09 13:42:06 -080057using namespace android::ftl::flag_operators;
Siarhei Vishniakou23740b92023-04-21 11:30:20 -070058using android::base::Error;
Peter Collingbourneb04b9b82021-02-08 12:09:47 -080059using android::base::HwTimeoutMultiplier;
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +000060using android::base::Result;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080061using android::base::StringPrintf;
Prabir Pradhan48f8cb92021-08-26 14:05:36 -070062using android::gui::DisplayInfo;
chaviw98318de2021-05-19 16:45:23 -050063using android::gui::FocusRequest;
64using android::gui::TouchOcclusionMode;
65using android::gui::WindowInfo;
66using android::gui::WindowInfoHandle;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -080067using android::os::InputEventInjectionResult;
68using android::os::InputEventInjectionSync;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080069
Garfield Tane84e6f92019-08-29 17:28:41 -070070namespace android::inputdispatcher {
Michael Wrightd02c5b62014-02-10 15:10:22 -080071
Prabir Pradhancef936d2021-07-21 16:17:52 +000072namespace {
Prabir Pradhancef936d2021-07-21 16:17:52 +000073// Temporarily releases a held mutex for the lifetime of the instance.
74// Named to match std::scoped_lock
75class scoped_unlock {
76public:
77 explicit scoped_unlock(std::mutex& mutex) : mMutex(mutex) { mMutex.unlock(); }
78 ~scoped_unlock() { mMutex.lock(); }
79
80private:
81 std::mutex& mMutex;
82};
83
Michael Wrightd02c5b62014-02-10 15:10:22 -080084// Default input dispatching timeout if there is no focused application or paused window
85// from which to determine an appropriate dispatching timeout.
Peter Collingbourneb04b9b82021-02-08 12:09:47 -080086const std::chrono::duration DEFAULT_INPUT_DISPATCHING_TIMEOUT = std::chrono::milliseconds(
87 android::os::IInputConstants::UNMULTIPLIED_DEFAULT_DISPATCHING_TIMEOUT_MILLIS *
88 HwTimeoutMultiplier());
Michael Wrightd02c5b62014-02-10 15:10:22 -080089
90// Amount of time to allow for all pending events to be processed when an app switch
91// key is on the way. This is used to preempt input dispatch and drop input events
92// when an application takes too long to respond and the user has pressed an app switch key.
Michael Wright2b3c3302018-03-02 17:19:13 +000093constexpr nsecs_t APP_SWITCH_TIMEOUT = 500 * 1000000LL; // 0.5sec
Michael Wrightd02c5b62014-02-10 15:10:22 -080094
Siarhei Vishniakou289e9242022-02-15 14:50:16 -080095const std::chrono::duration STALE_EVENT_TIMEOUT = std::chrono::seconds(10) * HwTimeoutMultiplier();
Michael Wrightd02c5b62014-02-10 15:10:22 -080096
Michael Wrightd02c5b62014-02-10 15:10:22 -080097// Log a warning when an event takes longer than this to process, even if an ANR does not occur.
Michael Wright2b3c3302018-03-02 17:19:13 +000098constexpr nsecs_t SLOW_EVENT_PROCESSING_WARNING_TIMEOUT = 2000 * 1000000LL; // 2sec
99
100// Log a warning when an interception call takes longer than this to process.
101constexpr std::chrono::milliseconds SLOW_INTERCEPTION_THRESHOLD = 50ms;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800102
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700103// Additional key latency in case a connection is still processing some motion events.
104// This will help with the case when a user touched a button that opens a new window,
105// and gives us the chance to dispatch the key to this new window.
106constexpr std::chrono::nanoseconds KEY_WAITING_FOR_EVENTS_TIMEOUT = 500ms;
107
Michael Wrightd02c5b62014-02-10 15:10:22 -0800108// Number of recent events to keep for debugging purposes.
Michael Wright2b3c3302018-03-02 17:19:13 +0000109constexpr size_t RECENT_QUEUE_MAX_SIZE = 10;
110
Antonio Kantekea47acb2021-12-23 12:41:25 -0800111// Event log tags. See EventLogTags.logtags for reference.
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +0000112constexpr int LOGTAG_INPUT_INTERACTION = 62000;
113constexpr int LOGTAG_INPUT_FOCUS = 62001;
Arthur Hungb3307ee2021-10-14 10:57:37 +0000114constexpr int LOGTAG_INPUT_CANCEL = 62003;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +0000115
Prabir Pradhan33e3baa2022-12-06 20:30:22 +0000116const ui::Transform kIdentityTransform;
117
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000118inline nsecs_t now() {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800119 return systemTime(SYSTEM_TIME_MONOTONIC);
120}
121
Siarhei Vishniakoud38a1e02023-07-18 11:55:17 -0700122bool isEmpty(const std::stringstream& ss) {
123 return ss.rdbuf()->in_avail() == 0;
124}
125
Siarhei Vishniakou63b63612023-04-12 11:00:23 -0700126inline const std::string binderToString(const sp<IBinder>& binder) {
Bernardo Rufino49d99e42021-01-18 15:16:59 +0000127 if (binder == nullptr) {
128 return "<null>";
129 }
130 return StringPrintf("%p", binder.get());
131}
132
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +0000133static std::string uidString(const gui::Uid& uid) {
134 return uid.toString();
135}
136
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700137Result<void> checkKeyAction(int32_t action) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800138 switch (action) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700139 case AKEY_EVENT_ACTION_DOWN:
140 case AKEY_EVENT_ACTION_UP:
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700141 return {};
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700142 default:
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700143 return Error() << "Key event has invalid action code " << action;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800144 }
145}
146
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700147Result<void> validateKeyEvent(int32_t action) {
148 return checkKeyAction(action);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800149}
150
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700151Result<void> checkMotionAction(int32_t action, int32_t actionButton, int32_t pointerCount) {
Siarhei Vishniakou2f61bdc2022-12-02 08:55:51 -0800152 switch (MotionEvent::getActionMasked(action)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700153 case AMOTION_EVENT_ACTION_DOWN:
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700154 case AMOTION_EVENT_ACTION_UP: {
155 if (pointerCount != 1) {
156 return Error() << "invalid pointer count " << pointerCount;
157 }
158 return {};
159 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700160 case AMOTION_EVENT_ACTION_MOVE:
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700161 case AMOTION_EVENT_ACTION_HOVER_ENTER:
162 case AMOTION_EVENT_ACTION_HOVER_MOVE:
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700163 case AMOTION_EVENT_ACTION_HOVER_EXIT: {
164 if (pointerCount < 1) {
165 return Error() << "invalid pointer count " << pointerCount;
166 }
167 return {};
168 }
Siarhei Vishniakou2f61bdc2022-12-02 08:55:51 -0800169 case AMOTION_EVENT_ACTION_CANCEL:
170 case AMOTION_EVENT_ACTION_OUTSIDE:
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700171 case AMOTION_EVENT_ACTION_SCROLL:
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700172 return {};
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700173 case AMOTION_EVENT_ACTION_POINTER_DOWN:
174 case AMOTION_EVENT_ACTION_POINTER_UP: {
Siarhei Vishniakou2f61bdc2022-12-02 08:55:51 -0800175 const int32_t index = MotionEvent::getActionIndex(action);
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700176 if (index < 0) {
177 return Error() << "invalid index " << index << " for "
178 << MotionEvent::actionToString(action);
179 }
180 if (index >= pointerCount) {
181 return Error() << "invalid index " << index << " for pointerCount " << pointerCount;
182 }
183 if (pointerCount <= 1) {
184 return Error() << "invalid pointer count " << pointerCount << " for "
185 << MotionEvent::actionToString(action);
186 }
187 return {};
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700188 }
189 case AMOTION_EVENT_ACTION_BUTTON_PRESS:
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700190 case AMOTION_EVENT_ACTION_BUTTON_RELEASE: {
191 if (actionButton == 0) {
192 return Error() << "action button should be nonzero for "
193 << MotionEvent::actionToString(action);
194 }
195 return {};
196 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700197 default:
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700198 return Error() << "invalid action " << action;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800199 }
200}
201
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000202int64_t millis(std::chrono::nanoseconds t) {
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -0500203 return std::chrono::duration_cast<std::chrono::milliseconds>(t).count();
204}
205
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700206Result<void> validateMotionEvent(int32_t action, int32_t actionButton, size_t pointerCount,
207 const PointerProperties* pointerProperties) {
208 Result<void> actionCheck = checkMotionAction(action, actionButton, pointerCount);
209 if (!actionCheck.ok()) {
210 return actionCheck;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800211 }
212 if (pointerCount < 1 || pointerCount > MAX_POINTERS) {
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700213 return Error() << "Motion event has invalid pointer count " << pointerCount
214 << "; value must be between 1 and " << MAX_POINTERS << ".";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800215 }
Siarhei Vishniakou8a878352023-01-30 14:05:01 -0800216 std::bitset<MAX_POINTER_ID + 1> pointerIdBits;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800217 for (size_t i = 0; i < pointerCount; i++) {
218 int32_t id = pointerProperties[i].id;
219 if (id < 0 || id > MAX_POINTER_ID) {
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700220 return Error() << "Motion event has invalid pointer id " << id
221 << "; value must be between 0 and " << MAX_POINTER_ID;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800222 }
Siarhei Vishniakou8a878352023-01-30 14:05:01 -0800223 if (pointerIdBits.test(id)) {
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700224 return Error() << "Motion event has duplicate pointer id " << id;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800225 }
Siarhei Vishniakou8a878352023-01-30 14:05:01 -0800226 pointerIdBits.set(id);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800227 }
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700228 return {};
229}
230
231Result<void> validateInputEvent(const InputEvent& event) {
232 switch (event.getType()) {
233 case InputEventType::KEY: {
234 const KeyEvent& key = static_cast<const KeyEvent&>(event);
235 const int32_t action = key.getAction();
236 return validateKeyEvent(action);
237 }
238 case InputEventType::MOTION: {
239 const MotionEvent& motion = static_cast<const MotionEvent&>(event);
240 const int32_t action = motion.getAction();
241 const size_t pointerCount = motion.getPointerCount();
242 const PointerProperties* pointerProperties = motion.getPointerProperties();
243 const int32_t actionButton = motion.getActionButton();
244 return validateMotionEvent(action, actionButton, pointerCount, pointerProperties);
245 }
246 default: {
247 return {};
248 }
249 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800250}
251
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000252std::string dumpRegion(const Region& region) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800253 if (region.isEmpty()) {
Bernardo Rufino53fc31e2020-11-03 11:01:07 +0000254 return "<empty>";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800255 }
256
Bernardo Rufino53fc31e2020-11-03 11:01:07 +0000257 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800258 bool first = true;
259 Region::const_iterator cur = region.begin();
260 Region::const_iterator const tail = region.end();
261 while (cur != tail) {
262 if (first) {
263 first = false;
264 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800265 dump += "|";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800266 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800267 dump += StringPrintf("[%d,%d][%d,%d]", cur->left, cur->top, cur->right, cur->bottom);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800268 cur++;
269 }
Bernardo Rufino53fc31e2020-11-03 11:01:07 +0000270 return dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800271}
272
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000273std::string dumpQueue(const std::deque<DispatchEntry*>& queue, nsecs_t currentTime) {
Siarhei Vishniakou14411c92020-09-18 21:15:05 -0500274 constexpr size_t maxEntries = 50; // max events to print
275 constexpr size_t skipBegin = maxEntries / 2;
276 const size_t skipEnd = queue.size() - maxEntries / 2;
277 // skip from maxEntries / 2 ... size() - maxEntries/2
278 // only print from 0 .. skipBegin and then from skipEnd .. size()
279
280 std::string dump;
281 for (size_t i = 0; i < queue.size(); i++) {
282 const DispatchEntry& entry = *queue[i];
283 if (i >= skipBegin && i < skipEnd) {
284 dump += StringPrintf(INDENT4 "<skipped %zu entries>\n", skipEnd - skipBegin);
285 i = skipEnd - 1; // it will be incremented to "skipEnd" by 'continue'
286 continue;
287 }
288 dump.append(INDENT4);
289 dump += entry.eventEntry->getDescription();
Siarhei Vishniakou253f4642022-11-09 13:42:06 -0800290 dump += StringPrintf(", seq=%" PRIu32 ", targetFlags=%s, resolvedAction=%d, age=%" PRId64
291 "ms",
292 entry.seq, entry.targetFlags.string().c_str(), entry.resolvedAction,
Siarhei Vishniakou14411c92020-09-18 21:15:05 -0500293 ns2ms(currentTime - entry.eventEntry->eventTime));
294 if (entry.deliveryTime != 0) {
295 // This entry was delivered, so add information on how long we've been waiting
296 dump += StringPrintf(", wait=%" PRId64 "ms", ns2ms(currentTime - entry.deliveryTime));
297 }
298 dump.append("\n");
299 }
300 return dump;
301}
302
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -0700303/**
304 * Find the entry in std::unordered_map by key, and return it.
305 * If the entry is not found, return a default constructed entry.
306 *
307 * Useful when the entries are vectors, since an empty vector will be returned
308 * if the entry is not found.
309 * Also useful when the entries are sp<>. If an entry is not found, nullptr is returned.
310 */
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700311template <typename K, typename V>
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000312V getValueByKey(const std::unordered_map<K, V>& map, K key) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -0700313 auto it = map.find(key);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700314 return it != map.end() ? it->second : V{};
Tiger Huang721e26f2018-07-24 22:26:19 +0800315}
316
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000317bool haveSameToken(const sp<WindowInfoHandle>& first, const sp<WindowInfoHandle>& second) {
chaviwaf87b3e2019-10-01 16:59:28 -0700318 if (first == second) {
319 return true;
320 }
321
322 if (first == nullptr || second == nullptr) {
323 return false;
324 }
325
326 return first->getToken() == second->getToken();
327}
328
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000329bool haveSameApplicationToken(const WindowInfo* first, const WindowInfo* second) {
Bernardo Rufino1ff9d592021-01-18 16:58:57 +0000330 if (first == nullptr || second == nullptr) {
331 return false;
332 }
333 return first->applicationInfo.token != nullptr &&
334 first->applicationInfo.token == second->applicationInfo.token;
335}
336
Siarhei Vishniakou8a878352023-01-30 14:05:01 -0800337template <typename T>
338size_t firstMarkedBit(T set) {
339 // TODO: replace with std::countr_zero from <bit> when that's available
340 LOG_ALWAYS_FATAL_IF(set.none());
341 size_t i = 0;
342 while (!set.test(i)) {
343 i++;
344 }
345 return i;
346}
347
Siarhei Vishniakou253f4642022-11-09 13:42:06 -0800348std::unique_ptr<DispatchEntry> createDispatchEntry(
349 const InputTarget& inputTarget, std::shared_ptr<EventEntry> eventEntry,
350 ftl::Flags<InputTarget::Flags> inputTargetFlags) {
chaviw1ff3d1e2020-07-01 15:53:47 -0700351 if (inputTarget.useDefaultPointerTransform()) {
352 const ui::Transform& transform = inputTarget.getDefaultPointerTransform();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700353 return std::make_unique<DispatchEntry>(eventEntry, inputTargetFlags, transform,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700354 inputTarget.displayTransform,
355 inputTarget.globalScaleFactor);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000356 }
357
358 ALOG_ASSERT(eventEntry->type == EventEntry::Type::MOTION);
359 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(*eventEntry);
360
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700361 std::vector<PointerCoords> pointerCoords;
362 pointerCoords.resize(motionEntry.pointerCount);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000363
364 // Use the first pointer information to normalize all other pointers. This could be any pointer
365 // as long as all other pointers are normalized to the same value and the final DispatchEntry
chaviw1ff3d1e2020-07-01 15:53:47 -0700366 // uses the transform for the normalized pointer.
367 const ui::Transform& firstPointerTransform =
Siarhei Vishniakou8a878352023-01-30 14:05:01 -0800368 inputTarget.pointerTransforms[firstMarkedBit(inputTarget.pointerIds)];
chaviw1ff3d1e2020-07-01 15:53:47 -0700369 ui::Transform inverseFirstTransform = firstPointerTransform.inverse();
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000370
371 // Iterate through all pointers in the event to normalize against the first.
372 for (uint32_t pointerIndex = 0; pointerIndex < motionEntry.pointerCount; pointerIndex++) {
373 const PointerProperties& pointerProperties = motionEntry.pointerProperties[pointerIndex];
374 uint32_t pointerId = uint32_t(pointerProperties.id);
chaviw1ff3d1e2020-07-01 15:53:47 -0700375 const ui::Transform& currTransform = inputTarget.pointerTransforms[pointerId];
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000376
377 pointerCoords[pointerIndex].copyFrom(motionEntry.pointerCoords[pointerIndex]);
chaviw1ff3d1e2020-07-01 15:53:47 -0700378 // First, apply the current pointer's transform to update the coordinates into
379 // window space.
380 pointerCoords[pointerIndex].transform(currTransform);
381 // Next, apply the inverse transform of the normalized coordinates so the
382 // current coordinates are transformed into the normalized coordinate space.
383 pointerCoords[pointerIndex].transform(inverseFirstTransform);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000384 }
385
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700386 std::unique_ptr<MotionEntry> combinedMotionEntry =
387 std::make_unique<MotionEntry>(motionEntry.id, motionEntry.eventTime,
388 motionEntry.deviceId, motionEntry.source,
389 motionEntry.displayId, motionEntry.policyFlags,
390 motionEntry.action, motionEntry.actionButton,
391 motionEntry.flags, motionEntry.metaState,
392 motionEntry.buttonState, motionEntry.classification,
393 motionEntry.edgeFlags, motionEntry.xPrecision,
394 motionEntry.yPrecision, motionEntry.xCursorPosition,
395 motionEntry.yCursorPosition, motionEntry.downTime,
396 motionEntry.pointerCount, motionEntry.pointerProperties,
Prabir Pradhan5beda762021-12-10 09:30:08 +0000397 pointerCoords.data());
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000398
399 if (motionEntry.injectionState) {
400 combinedMotionEntry->injectionState = motionEntry.injectionState;
401 combinedMotionEntry->injectionState->refCount += 1;
402 }
403
404 std::unique_ptr<DispatchEntry> dispatchEntry =
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700405 std::make_unique<DispatchEntry>(std::move(combinedMotionEntry), inputTargetFlags,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700406 firstPointerTransform, inputTarget.displayTransform,
407 inputTarget.globalScaleFactor);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000408 return dispatchEntry;
409}
410
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000411status_t openInputChannelPair(const std::string& name, std::shared_ptr<InputChannel>& serverChannel,
412 std::unique_ptr<InputChannel>& clientChannel) {
Garfield Tan15601662020-09-22 15:32:38 -0700413 std::unique_ptr<InputChannel> uniqueServerChannel;
414 status_t result = InputChannel::openInputChannelPair(name, uniqueServerChannel, clientChannel);
415
416 serverChannel = std::move(uniqueServerChannel);
417 return result;
418}
419
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -0500420template <typename T>
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000421bool sharedPointersEqual(const std::shared_ptr<T>& lhs, const std::shared_ptr<T>& rhs) {
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -0500422 if (lhs == nullptr && rhs == nullptr) {
423 return true;
424 }
425 if (lhs == nullptr || rhs == nullptr) {
426 return false;
427 }
428 return *lhs == *rhs;
429}
430
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000431KeyEvent createKeyEvent(const KeyEntry& entry) {
Siarhei Vishniakou2e2ea992020-12-15 02:57:19 +0000432 KeyEvent event;
433 event.initialize(entry.id, entry.deviceId, entry.source, entry.displayId, INVALID_HMAC,
434 entry.action, entry.flags, entry.keyCode, entry.scanCode, entry.metaState,
435 entry.repeatCount, entry.downTime, entry.eventTime);
436 return event;
437}
438
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000439bool shouldReportMetricsForConnection(const Connection& connection) {
Siarhei Vishniakouf2652122021-03-05 21:39:46 +0000440 // Do not keep track of gesture monitors. They receive every event and would disproportionately
441 // affect the statistics.
442 if (connection.monitor) {
443 return false;
444 }
445 // If the connection is experiencing ANR, let's skip it. We have separate ANR metrics
446 if (!connection.responsive) {
447 return false;
448 }
449 return true;
450}
451
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000452bool shouldReportFinishedEvent(const DispatchEntry& dispatchEntry, const Connection& connection) {
Siarhei Vishniakouf2652122021-03-05 21:39:46 +0000453 const EventEntry& eventEntry = *dispatchEntry.eventEntry;
454 const int32_t& inputEventId = eventEntry.id;
455 if (inputEventId != dispatchEntry.resolvedEventId) {
456 // Event was transmuted
457 return false;
458 }
459 if (inputEventId == android::os::IInputConstants::INVALID_INPUT_EVENT_ID) {
460 return false;
461 }
462 // Only track latency for events that originated from hardware
463 if (eventEntry.isSynthesized()) {
464 return false;
465 }
466 const EventEntry::Type& inputEventEntryType = eventEntry.type;
467 if (inputEventEntryType == EventEntry::Type::KEY) {
468 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
469 if (keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) {
470 return false;
471 }
472 } else if (inputEventEntryType == EventEntry::Type::MOTION) {
473 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
474 if (motionEntry.action == AMOTION_EVENT_ACTION_CANCEL ||
475 motionEntry.action == AMOTION_EVENT_ACTION_HOVER_EXIT) {
476 return false;
477 }
478 } else {
479 // Not a key or a motion
480 return false;
481 }
482 if (!shouldReportMetricsForConnection(connection)) {
483 return false;
484 }
485 return true;
486}
487
Prabir Pradhancef936d2021-07-21 16:17:52 +0000488/**
489 * Connection is responsive if it has no events in the waitQueue that are older than the
490 * current time.
491 */
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000492bool isConnectionResponsive(const Connection& connection) {
Prabir Pradhancef936d2021-07-21 16:17:52 +0000493 const nsecs_t currentTime = now();
494 for (const DispatchEntry* entry : connection.waitQueue) {
495 if (entry->timeoutTime < currentTime) {
496 return false;
497 }
498 }
499 return true;
500}
501
Antonio Kantekf16f2832021-09-28 04:39:20 +0000502// Returns true if the event type passed as argument represents a user activity.
503bool isUserActivityEvent(const EventEntry& eventEntry) {
504 switch (eventEntry.type) {
Josep del Riob3981622023-04-18 15:49:45 +0000505 case EventEntry::Type::CONFIGURATION_CHANGED:
506 case EventEntry::Type::DEVICE_RESET:
507 case EventEntry::Type::DRAG:
Antonio Kantekf16f2832021-09-28 04:39:20 +0000508 case EventEntry::Type::FOCUS:
509 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
Antonio Kantekf16f2832021-09-28 04:39:20 +0000510 case EventEntry::Type::SENSOR:
Josep del Riob3981622023-04-18 15:49:45 +0000511 case EventEntry::Type::TOUCH_MODE_CHANGED:
Antonio Kantekf16f2832021-09-28 04:39:20 +0000512 return false;
Antonio Kantekf16f2832021-09-28 04:39:20 +0000513 case EventEntry::Type::KEY:
514 case EventEntry::Type::MOTION:
515 return true;
516 }
517}
518
Prabir Pradhan3f90d312021-11-19 03:57:24 -0800519// Returns true if the given window can accept pointer events at the given display location.
Prabir Pradhan82e081e2022-12-06 09:50:09 +0000520bool windowAcceptsTouchAt(const WindowInfo& windowInfo, int32_t displayId, float x, float y,
Prabir Pradhan33e3baa2022-12-06 20:30:22 +0000521 bool isStylus, const ui::Transform& displayTransform) {
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -0800522 const auto inputConfig = windowInfo.inputConfig;
523 if (windowInfo.displayId != displayId ||
524 inputConfig.test(WindowInfo::InputConfig::NOT_VISIBLE)) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -0800525 return false;
526 }
Prabir Pradhand65552b2021-10-07 11:23:50 -0700527 const bool windowCanInterceptTouch = isStylus && windowInfo.interceptsStylus();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -0800528 if (inputConfig.test(WindowInfo::InputConfig::NOT_TOUCHABLE) && !windowCanInterceptTouch) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -0800529 return false;
530 }
Prabir Pradhan33e3baa2022-12-06 20:30:22 +0000531
532 // Window Manager works in the logical display coordinate space. When it specifies bounds for a
533 // window as (l, t, r, b), the range of x in [l, r) and y in [t, b) are considered to be inside
534 // the window. Points on the right and bottom edges should not be inside the window, so we need
535 // to be careful about performing a hit test when the display is rotated, since the "right" and
536 // "bottom" of the window will be different in the display (un-rotated) space compared to in the
537 // logical display in which WM determined the bounds. Perform the hit test in the logical
538 // display space to ensure these edges are considered correctly in all orientations.
539 const auto touchableRegion = displayTransform.transform(windowInfo.touchableRegion);
540 const auto p = displayTransform.transform(x, y);
541 if (!touchableRegion.contains(std::floor(p.x), std::floor(p.y))) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -0800542 return false;
543 }
544 return true;
545}
546
Prabir Pradhand65552b2021-10-07 11:23:50 -0700547bool isPointerFromStylus(const MotionEntry& entry, int32_t pointerIndex) {
548 return isFromSource(entry.source, AINPUT_SOURCE_STYLUS) &&
Prabir Pradhane5626962022-10-27 20:30:53 +0000549 isStylusToolType(entry.pointerProperties[pointerIndex].toolType);
Prabir Pradhand65552b2021-10-07 11:23:50 -0700550}
551
Siarhei Vishniakou253f4642022-11-09 13:42:06 -0800552// Determines if the given window can be targeted as InputTarget::Flags::FOREGROUND.
Prabir Pradhan6dfbf262022-03-14 15:24:30 +0000553// Foreground events are only sent to "foreground targetable" windows, but not all gestures sent to
554// such window are necessarily targeted with the flag. For example, an event with ACTION_OUTSIDE can
555// be sent to such a window, but it is not a foreground event and doesn't use
Siarhei Vishniakou253f4642022-11-09 13:42:06 -0800556// InputTarget::Flags::FOREGROUND.
Prabir Pradhan6dfbf262022-03-14 15:24:30 +0000557bool canReceiveForegroundTouches(const WindowInfo& info) {
558 // A non-touchable window can still receive touch events (e.g. in the case of
559 // STYLUS_INTERCEPTOR), so prevent such windows from receiving foreground events for touches.
560 return !info.inputConfig.test(gui::WindowInfo::InputConfig::NOT_TOUCHABLE) && !info.isSpy();
561}
562
Prabir Pradhanaeebeb42023-06-13 19:53:03 +0000563bool isWindowOwnedBy(const sp<WindowInfoHandle>& windowHandle, gui::Pid pid, gui::Uid uid) {
Antonio Kantek48710e42022-03-24 14:19:30 -0700564 if (windowHandle == nullptr) {
565 return false;
566 }
567 const WindowInfo* windowInfo = windowHandle->getInfo();
568 if (pid == windowInfo->ownerPid && uid == windowInfo->ownerUid) {
569 return true;
570 }
571 return false;
572}
573
Prabir Pradhan5735a322022-04-11 17:23:34 +0000574// Checks targeted injection using the window's owner's uid.
575// Returns an empty string if an entry can be sent to the given window, or an error message if the
576// entry is a targeted injection whose uid target doesn't match the window owner.
577std::optional<std::string> verifyTargetedInjection(const sp<WindowInfoHandle>& window,
578 const EventEntry& entry) {
579 if (entry.injectionState == nullptr || !entry.injectionState->targetUid) {
580 // The event was not injected, or the injected event does not target a window.
581 return {};
582 }
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +0000583 const auto uid = *entry.injectionState->targetUid;
Prabir Pradhan5735a322022-04-11 17:23:34 +0000584 if (window == nullptr) {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +0000585 return StringPrintf("No valid window target for injection into uid %s.",
586 uid.toString().c_str());
Prabir Pradhan5735a322022-04-11 17:23:34 +0000587 }
588 if (entry.injectionState->targetUid != window->getInfo()->ownerUid) {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +0000589 return StringPrintf("Injected event targeted at uid %s would be dispatched to window '%s' "
590 "owned by uid %s.",
591 uid.toString().c_str(), window->getName().c_str(),
592 window->getInfo()->ownerUid.toString().c_str());
Prabir Pradhan5735a322022-04-11 17:23:34 +0000593 }
594 return {};
595}
596
Prabir Pradhan82e081e2022-12-06 09:50:09 +0000597std::pair<float, float> resolveTouchedPosition(const MotionEntry& entry) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -0700598 const bool isFromMouse = isFromSource(entry.source, AINPUT_SOURCE_MOUSE);
599 // Always dispatch mouse events to cursor position.
600 if (isFromMouse) {
Prabir Pradhan82e081e2022-12-06 09:50:09 +0000601 return {entry.xCursorPosition, entry.yCursorPosition};
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -0700602 }
603
Siarhei Vishniakou5b9766d2023-07-18 14:06:29 -0700604 const int32_t pointerIndex = MotionEvent::getActionIndex(entry.action);
Prabir Pradhan82e081e2022-12-06 09:50:09 +0000605 return {entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_X),
606 entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_Y)};
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -0700607}
608
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -0700609std::optional<nsecs_t> getDownTime(const EventEntry& eventEntry) {
610 if (eventEntry.type == EventEntry::Type::KEY) {
611 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
612 return keyEntry.downTime;
613 } else if (eventEntry.type == EventEntry::Type::MOTION) {
614 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
615 return motionEntry.downTime;
616 }
617 return std::nullopt;
618}
619
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000620/**
621 * Compare the old touch state to the new touch state, and generate the corresponding touched
622 * windows (== input targets).
623 * If a window had the hovering pointer, but now it doesn't, produce HOVER_EXIT for that window.
624 * If the pointer just entered the new window, produce HOVER_ENTER.
625 * For pointers remaining in the window, produce HOVER_MOVE.
626 */
627std::vector<TouchedWindow> getHoveringWindowsLocked(const TouchState* oldState,
628 const TouchState& newTouchState,
629 const MotionEntry& entry) {
630 std::vector<TouchedWindow> out;
631 const int32_t maskedAction = MotionEvent::getActionMasked(entry.action);
632 if (maskedAction != AMOTION_EVENT_ACTION_HOVER_ENTER &&
633 maskedAction != AMOTION_EVENT_ACTION_HOVER_MOVE &&
634 maskedAction != AMOTION_EVENT_ACTION_HOVER_EXIT) {
635 // Not a hover event - don't need to do anything
636 return out;
637 }
638
639 // We should consider all hovering pointers here. But for now, just use the first one
640 const int32_t pointerId = entry.pointerProperties[0].id;
641
642 std::set<sp<WindowInfoHandle>> oldWindows;
643 if (oldState != nullptr) {
644 oldWindows = oldState->getWindowsWithHoveringPointer(entry.deviceId, pointerId);
645 }
646
647 std::set<sp<WindowInfoHandle>> newWindows =
648 newTouchState.getWindowsWithHoveringPointer(entry.deviceId, pointerId);
649
650 // If the pointer is no longer in the new window set, send HOVER_EXIT.
651 for (const sp<WindowInfoHandle>& oldWindow : oldWindows) {
652 if (newWindows.find(oldWindow) == newWindows.end()) {
653 TouchedWindow touchedWindow;
654 touchedWindow.windowHandle = oldWindow;
655 touchedWindow.targetFlags = InputTarget::Flags::DISPATCH_AS_HOVER_EXIT;
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000656 out.push_back(touchedWindow);
657 }
658 }
659
660 for (const sp<WindowInfoHandle>& newWindow : newWindows) {
661 TouchedWindow touchedWindow;
662 touchedWindow.windowHandle = newWindow;
663 if (oldWindows.find(newWindow) == oldWindows.end()) {
664 // Any windows that have this pointer now, and didn't have it before, should get
665 // HOVER_ENTER
666 touchedWindow.targetFlags = InputTarget::Flags::DISPATCH_AS_HOVER_ENTER;
667 } else {
668 // This pointer was already sent to the window. Use ACTION_HOVER_MOVE.
Siarhei Vishniakouc2eb8502023-04-11 18:33:36 -0700669 if (CC_UNLIKELY(maskedAction != AMOTION_EVENT_ACTION_HOVER_MOVE)) {
670 LOG(FATAL) << "Expected ACTION_HOVER_MOVE instead of " << entry.getDescription();
671 }
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000672 touchedWindow.targetFlags = InputTarget::Flags::DISPATCH_AS_IS;
673 }
Siarhei Vishniakou0836a302023-05-03 13:54:30 -0700674 touchedWindow.addHoveringPointer(entry.deviceId, pointerId);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000675 if (canReceiveForegroundTouches(*newWindow->getInfo())) {
676 touchedWindow.targetFlags |= InputTarget::Flags::FOREGROUND;
677 }
678 out.push_back(touchedWindow);
679 }
680 return out;
681}
682
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -0800683template <typename T>
684std::vector<T>& operator+=(std::vector<T>& left, const std::vector<T>& right) {
685 left.insert(left.end(), right.begin(), right.end());
686 return left;
687}
688
Harry Cuttsb166c002023-05-09 13:06:05 +0000689// Filter windows in a TouchState and targets in a vector to remove untrusted windows/targets from
690// both.
691void filterUntrustedTargets(TouchState& touchState, std::vector<InputTarget>& targets) {
692 std::erase_if(touchState.windows, [&](const TouchedWindow& window) {
693 if (!window.windowHandle->getInfo()->inputConfig.test(
694 WindowInfo::InputConfig::TRUSTED_OVERLAY)) {
695 // In addition to TouchState, erase this window from the input targets! We don't have a
696 // good way to do this today except by adding a nested loop.
697 // TODO(b/282025641): simplify this code once InputTargets are being identified
698 // separately from TouchedWindows.
699 std::erase_if(targets, [&](const InputTarget& target) {
700 return target.inputChannel->getConnectionToken() == window.windowHandle->getToken();
701 });
702 return true;
703 }
704 return false;
705 });
706}
707
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000708} // namespace
709
Michael Wrightd02c5b62014-02-10 15:10:22 -0800710// --- InputDispatcher ---
711
Prabir Pradhana41d2442023-04-20 21:30:40 +0000712InputDispatcher::InputDispatcher(InputDispatcherPolicyInterface& policy)
Siarhei Vishniakou289e9242022-02-15 14:50:16 -0800713 : InputDispatcher(policy, STALE_EVENT_TIMEOUT) {}
714
Prabir Pradhana41d2442023-04-20 21:30:40 +0000715InputDispatcher::InputDispatcher(InputDispatcherPolicyInterface& policy,
Siarhei Vishniakou289e9242022-02-15 14:50:16 -0800716 std::chrono::nanoseconds staleEventTimeout)
Garfield Tan00f511d2019-06-12 16:55:40 -0700717 : mPolicy(policy),
718 mPendingEvent(nullptr),
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700719 mLastDropReason(DropReason::NOT_DROPPED),
Garfield Tanff1f1bb2020-01-28 13:24:04 -0800720 mIdGenerator(IdGenerator::Source::INPUT_DISPATCHER),
Garfield Tan00f511d2019-06-12 16:55:40 -0700721 mAppSwitchSawKeyDown(false),
Colin Cross5b799302022-10-18 21:52:41 -0700722 mAppSwitchDueTime(LLONG_MAX),
Garfield Tan00f511d2019-06-12 16:55:40 -0700723 mNextUnblockedEvent(nullptr),
Prabir Pradhan1376fcd2022-01-21 09:56:35 -0800724 mMonitorDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT),
Garfield Tan00f511d2019-06-12 16:55:40 -0700725 mDispatchEnabled(false),
726 mDispatchFrozen(false),
727 mInputFilterEnabled(false),
Bernardo Rufinoea97d182020-08-19 14:43:14 +0100728 mMaximumObscuringOpacityForTouch(1.0f),
Siarhei Vishniakou2508b872020-12-03 16:33:53 -1000729 mFocusedDisplayId(ADISPLAY_ID_DEFAULT),
Prabir Pradhan99987712020-11-10 18:43:05 -0800730 mWindowTokenWithPointerCapture(nullptr),
Siarhei Vishniakou289e9242022-02-15 14:50:16 -0800731 mStaleEventTimeout(staleEventTimeout),
Siarhei Vishniakoua04181f2021-03-26 05:56:49 +0000732 mLatencyAggregator(),
Antonio Kantek15beb512022-06-13 22:35:41 +0000733 mLatencyTracker(&mLatencyAggregator) {
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -0700734 mLooper = sp<Looper>::make(false);
Prabir Pradhanf93562f2018-11-29 12:13:37 -0800735 mReporter = createInputReporter();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800736
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -0700737 mWindowInfoListener = sp<DispatcherWindowListener>::make(*this);
Siarhei Vishniakou31977182022-09-30 08:51:23 -0700738#if defined(__ANDROID__)
Siarhei Vishniakou18050092021-09-01 13:32:49 -0700739 SurfaceComposerClient::getDefault()->addWindowInfosListener(mWindowInfoListener);
Siarhei Vishniakou31977182022-09-30 08:51:23 -0700740#endif
Yi Kong9b14ac62018-07-17 13:48:38 -0700741 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800742}
743
744InputDispatcher::~InputDispatcher() {
Prabir Pradhancef936d2021-07-21 16:17:52 +0000745 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800746
Prabir Pradhancef936d2021-07-21 16:17:52 +0000747 resetKeyRepeatLocked();
748 releasePendingEventLocked();
749 drainInboundQueueLocked();
750 mCommandQueue.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800751
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +0000752 while (!mConnectionsByToken.empty()) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -0700753 std::shared_ptr<Connection> connection = mConnectionsByToken.begin()->second;
Harry Cutts33476232023-01-30 19:57:29 +0000754 removeInputChannelLocked(connection->inputChannel->getConnectionToken(), /*notify=*/false);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800755 }
756}
757
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700758status_t InputDispatcher::start() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700759 if (mThread) {
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700760 return ALREADY_EXISTS;
761 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700762 mThread = std::make_unique<InputThread>(
763 "InputDispatcher", [this]() { dispatchOnce(); }, [this]() { mLooper->wake(); });
764 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700765}
766
767status_t InputDispatcher::stop() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700768 if (mThread && mThread->isCallingThread()) {
769 ALOGE("InputDispatcher cannot be stopped from its own thread!");
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700770 return INVALID_OPERATION;
771 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700772 mThread.reset();
773 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700774}
775
Michael Wrightd02c5b62014-02-10 15:10:22 -0800776void InputDispatcher::dispatchOnce() {
Colin Cross5b799302022-10-18 21:52:41 -0700777 nsecs_t nextWakeupTime = LLONG_MAX;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800778 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -0800779 std::scoped_lock _l(mLock);
780 mDispatcherIsAlive.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800781
782 // Run a dispatch loop if there are no pending commands.
783 // The dispatch loop might enqueue commands to run afterwards.
784 if (!haveCommandsLocked()) {
785 dispatchOnceInnerLocked(&nextWakeupTime);
786 }
787
788 // Run all pending commands if there are any.
789 // If any commands were run then force the next poll to wake up immediately.
Prabir Pradhancef936d2021-07-21 16:17:52 +0000790 if (runCommandsLockedInterruptable()) {
Colin Cross5b799302022-10-18 21:52:41 -0700791 nextWakeupTime = LLONG_MIN;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800792 }
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800793
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700794 // If we are still waiting for ack on some events,
795 // we might have to wake up earlier to check if an app is anr'ing.
796 const nsecs_t nextAnrCheck = processAnrsLocked();
797 nextWakeupTime = std::min(nextWakeupTime, nextAnrCheck);
798
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800799 // We are about to enter an infinitely long sleep, because we have no commands or
800 // pending or queued events
Colin Cross5b799302022-10-18 21:52:41 -0700801 if (nextWakeupTime == LLONG_MAX) {
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800802 mDispatcherEnteredIdle.notify_all();
803 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800804 } // release lock
805
806 // Wait for callback or timeout or wake. (make sure we round up, not down)
807 nsecs_t currentTime = now();
808 int timeoutMillis = toMillisecondTimeoutDelay(currentTime, nextWakeupTime);
809 mLooper->pollOnce(timeoutMillis);
810}
811
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700812/**
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500813 * Raise ANR if there is no focused window.
814 * Before the ANR is raised, do a final state check:
815 * 1. The currently focused application must be the same one we are waiting for.
816 * 2. Ensure we still don't have a focused window.
817 */
818void InputDispatcher::processNoFocusedWindowAnrLocked() {
819 // Check if the application that we are waiting for is still focused.
820 std::shared_ptr<InputApplicationHandle> focusedApplication =
821 getValueByKey(mFocusedApplicationHandlesByDisplay, mAwaitedApplicationDisplayId);
822 if (focusedApplication == nullptr ||
823 focusedApplication->getApplicationToken() !=
824 mAwaitedFocusedApplication->getApplicationToken()) {
825 // Unexpected because we should have reset the ANR timer when focused application changed
826 ALOGE("Waited for a focused window, but focused application has already changed to %s",
827 focusedApplication->getName().c_str());
828 return; // The focused application has changed.
829 }
830
chaviw98318de2021-05-19 16:45:23 -0500831 const sp<WindowInfoHandle>& focusedWindowHandle =
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500832 getFocusedWindowHandleLocked(mAwaitedApplicationDisplayId);
833 if (focusedWindowHandle != nullptr) {
834 return; // We now have a focused window. No need for ANR.
835 }
836 onAnrLocked(mAwaitedFocusedApplication);
837}
838
839/**
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700840 * Check if any of the connections' wait queues have events that are too old.
841 * If we waited for events to be ack'ed for more than the window timeout, raise an ANR.
842 * Return the time at which we should wake up next.
843 */
844nsecs_t InputDispatcher::processAnrsLocked() {
845 const nsecs_t currentTime = now();
Colin Cross5b799302022-10-18 21:52:41 -0700846 nsecs_t nextAnrCheck = LLONG_MAX;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700847 // Check if we are waiting for a focused window to appear. Raise ANR if waited too long
848 if (mNoFocusedWindowTimeoutTime.has_value() && mAwaitedFocusedApplication != nullptr) {
849 if (currentTime >= *mNoFocusedWindowTimeoutTime) {
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500850 processNoFocusedWindowAnrLocked();
Chris Yea209fde2020-07-22 13:54:51 -0700851 mAwaitedFocusedApplication.reset();
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500852 mNoFocusedWindowTimeoutTime = std::nullopt;
Colin Cross5b799302022-10-18 21:52:41 -0700853 return LLONG_MIN;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700854 } else {
Siarhei Vishniakou38a6d272020-10-20 20:29:33 -0500855 // Keep waiting. We will drop the event when mNoFocusedWindowTimeoutTime comes.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700856 nextAnrCheck = *mNoFocusedWindowTimeoutTime;
857 }
858 }
859
860 // Check if any connection ANRs are due
861 nextAnrCheck = std::min(nextAnrCheck, mAnrTracker.firstTimeout());
862 if (currentTime < nextAnrCheck) { // most likely scenario
863 return nextAnrCheck; // everything is normal. Let's check again at nextAnrCheck
864 }
865
866 // If we reached here, we have an unresponsive connection.
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -0700867 std::shared_ptr<Connection> connection = getConnectionLocked(mAnrTracker.firstToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700868 if (connection == nullptr) {
869 ALOGE("Could not find connection for entry %" PRId64, mAnrTracker.firstTimeout());
870 return nextAnrCheck;
871 }
872 connection->responsive = false;
873 // Stop waking up for this unresponsive connection
874 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000875 onAnrLocked(connection);
Colin Cross5b799302022-10-18 21:52:41 -0700876 return LLONG_MIN;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700877}
878
Prabir Pradhan1376fcd2022-01-21 09:56:35 -0800879std::chrono::nanoseconds InputDispatcher::getDispatchingTimeoutLocked(
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -0700880 const std::shared_ptr<Connection>& connection) {
Prabir Pradhan1376fcd2022-01-21 09:56:35 -0800881 if (connection->monitor) {
882 return mMonitorDispatchingTimeout;
883 }
884 const sp<WindowInfoHandle> window =
885 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700886 if (window != nullptr) {
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500887 return window->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700888 }
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500889 return DEFAULT_INPUT_DISPATCHING_TIMEOUT;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700890}
891
Michael Wrightd02c5b62014-02-10 15:10:22 -0800892void InputDispatcher::dispatchOnceInnerLocked(nsecs_t* nextWakeupTime) {
893 nsecs_t currentTime = now();
894
Jeff Browndc5992e2014-04-11 01:27:26 -0700895 // Reset the key repeat timer whenever normal dispatch is suspended while the
896 // device is in a non-interactive state. This is to ensure that we abort a key
897 // repeat if the device is just coming out of sleep.
898 if (!mDispatchEnabled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800899 resetKeyRepeatLocked();
900 }
901
902 // If dispatching is frozen, do not process timeouts or try to deliver any new events.
903 if (mDispatchFrozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +0100904 if (DEBUG_FOCUS) {
905 ALOGD("Dispatch frozen. Waiting some more.");
906 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800907 return;
908 }
909
910 // Optimize latency of app switches.
911 // Essentially we start a short timeout when an app switch key (HOME / ENDCALL) has
912 // been pressed. When it expires, we preempt dispatch and drop all other pending events.
913 bool isAppSwitchDue = mAppSwitchDueTime <= currentTime;
914 if (mAppSwitchDueTime < *nextWakeupTime) {
915 *nextWakeupTime = mAppSwitchDueTime;
916 }
917
918 // Ready to start a new event.
919 // If we don't already have a pending event, go grab one.
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700920 if (!mPendingEvent) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700921 if (mInboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800922 if (isAppSwitchDue) {
923 // The inbound queue is empty so the app switch key we were waiting
924 // for will never arrive. Stop waiting for it.
925 resetPendingAppSwitchLocked(false);
926 isAppSwitchDue = false;
927 }
928
929 // Synthesize a key repeat if appropriate.
930 if (mKeyRepeatState.lastKeyEntry) {
931 if (currentTime >= mKeyRepeatState.nextRepeatTime) {
932 mPendingEvent = synthesizeKeyRepeatLocked(currentTime);
933 } else {
934 if (mKeyRepeatState.nextRepeatTime < *nextWakeupTime) {
935 *nextWakeupTime = mKeyRepeatState.nextRepeatTime;
936 }
937 }
938 }
939
940 // Nothing to do if there is no pending event.
941 if (!mPendingEvent) {
942 return;
943 }
944 } else {
945 // Inbound queue has at least one entry.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700946 mPendingEvent = mInboundQueue.front();
947 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800948 traceInboundQueueLengthLocked();
949 }
950
951 // Poke user activity for this event.
952 if (mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700953 pokeUserActivityLocked(*mPendingEvent);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800954 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800955 }
956
957 // Now we have an event to dispatch.
958 // All events are eventually dequeued and processed this way, even if we intend to drop them.
Yi Kong9b14ac62018-07-17 13:48:38 -0700959 ALOG_ASSERT(mPendingEvent != nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800960 bool done = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700961 DropReason dropReason = DropReason::NOT_DROPPED;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800962 if (!(mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700963 dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800964 } else if (!mDispatchEnabled) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700965 dropReason = DropReason::DISABLED;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800966 }
967
968 if (mNextUnblockedEvent == mPendingEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -0700969 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800970 }
971
972 switch (mPendingEvent->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700973 case EventEntry::Type::CONFIGURATION_CHANGED: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700974 const ConfigurationChangedEntry& typedEntry =
975 static_cast<const ConfigurationChangedEntry&>(*mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700976 done = dispatchConfigurationChangedLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700977 dropReason = DropReason::NOT_DROPPED; // configuration changes are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700978 break;
979 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800980
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700981 case EventEntry::Type::DEVICE_RESET: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700982 const DeviceResetEntry& typedEntry =
983 static_cast<const DeviceResetEntry&>(*mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700984 done = dispatchDeviceResetLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700985 dropReason = DropReason::NOT_DROPPED; // device resets are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700986 break;
987 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800988
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100989 case EventEntry::Type::FOCUS: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700990 std::shared_ptr<FocusEntry> typedEntry =
991 std::static_pointer_cast<FocusEntry>(mPendingEvent);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100992 dispatchFocusLocked(currentTime, typedEntry);
993 done = true;
994 dropReason = DropReason::NOT_DROPPED; // focus events are never dropped
995 break;
996 }
997
Antonio Kantek7242d8b2021-08-05 16:07:20 -0700998 case EventEntry::Type::TOUCH_MODE_CHANGED: {
999 const auto typedEntry = std::static_pointer_cast<TouchModeEntry>(mPendingEvent);
1000 dispatchTouchModeChangeLocked(currentTime, typedEntry);
1001 done = true;
1002 dropReason = DropReason::NOT_DROPPED; // touch mode events are never dropped
1003 break;
1004 }
1005
Prabir Pradhan99987712020-11-10 18:43:05 -08001006 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
1007 const auto typedEntry =
1008 std::static_pointer_cast<PointerCaptureChangedEntry>(mPendingEvent);
1009 dispatchPointerCaptureChangedLocked(currentTime, typedEntry, dropReason);
1010 done = true;
1011 break;
1012 }
1013
arthurhungb89ccb02020-12-30 16:19:01 +08001014 case EventEntry::Type::DRAG: {
1015 std::shared_ptr<DragEntry> typedEntry =
1016 std::static_pointer_cast<DragEntry>(mPendingEvent);
1017 dispatchDragLocked(currentTime, typedEntry);
1018 done = true;
1019 break;
1020 }
1021
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001022 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001023 std::shared_ptr<KeyEntry> keyEntry = std::static_pointer_cast<KeyEntry>(mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001024 if (isAppSwitchDue) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001025 if (isAppSwitchKeyEvent(*keyEntry)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001026 resetPendingAppSwitchLocked(true);
1027 isAppSwitchDue = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001028 } else if (dropReason == DropReason::NOT_DROPPED) {
1029 dropReason = DropReason::APP_SWITCH;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001030 }
1031 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001032 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *keyEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001033 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001034 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001035 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
1036 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001037 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001038 done = dispatchKeyLocked(currentTime, keyEntry, &dropReason, nextWakeupTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001039 break;
1040 }
1041
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001042 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001043 std::shared_ptr<MotionEntry> motionEntry =
1044 std::static_pointer_cast<MotionEntry>(mPendingEvent);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001045 if (dropReason == DropReason::NOT_DROPPED && isAppSwitchDue) {
1046 dropReason = DropReason::APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001047 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001048 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *motionEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001049 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001050 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001051 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
1052 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001053 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001054 done = dispatchMotionLocked(currentTime, motionEntry, &dropReason, nextWakeupTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001055 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001056 }
Chris Yef59a2f42020-10-16 12:55:26 -07001057
1058 case EventEntry::Type::SENSOR: {
1059 std::shared_ptr<SensorEntry> sensorEntry =
1060 std::static_pointer_cast<SensorEntry>(mPendingEvent);
1061 if (dropReason == DropReason::NOT_DROPPED && isAppSwitchDue) {
1062 dropReason = DropReason::APP_SWITCH;
1063 }
1064 // Sensor timestamps use SYSTEM_TIME_BOOTTIME time base, so we can't use
1065 // 'currentTime' here, get SYSTEM_TIME_BOOTTIME instead.
1066 nsecs_t bootTime = systemTime(SYSTEM_TIME_BOOTTIME);
1067 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(bootTime, *sensorEntry)) {
1068 dropReason = DropReason::STALE;
1069 }
1070 dispatchSensorLocked(currentTime, sensorEntry, &dropReason, nextWakeupTime);
1071 done = true;
1072 break;
1073 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001074 }
1075
1076 if (done) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001077 if (dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001078 dropInboundEventLocked(*mPendingEvent, dropReason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001079 }
Michael Wright3a981722015-06-10 15:26:13 +01001080 mLastDropReason = dropReason;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001081
1082 releasePendingEventLocked();
Colin Cross5b799302022-10-18 21:52:41 -07001083 *nextWakeupTime = LLONG_MIN; // force next poll to wake up immediately
Michael Wrightd02c5b62014-02-10 15:10:22 -08001084 }
1085}
1086
Siarhei Vishniakou289e9242022-02-15 14:50:16 -08001087bool InputDispatcher::isStaleEvent(nsecs_t currentTime, const EventEntry& entry) {
1088 return std::chrono::nanoseconds(currentTime - entry.eventTime) >= mStaleEventTimeout;
1089}
1090
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001091/**
1092 * Return true if the events preceding this incoming motion event should be dropped
1093 * Return false otherwise (the default behaviour)
1094 */
1095bool InputDispatcher::shouldPruneInboundQueueLocked(const MotionEntry& motionEntry) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001096 const bool isPointerDownEvent = motionEntry.action == AMOTION_EVENT_ACTION_DOWN &&
Prabir Pradhanaa561d12021-09-24 06:57:33 -07001097 isFromSource(motionEntry.source, AINPUT_SOURCE_CLASS_POINTER);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001098
1099 // Optimize case where the current application is unresponsive and the user
1100 // decides to touch a window in a different application.
1101 // If the application takes too long to catch up then we drop all events preceding
1102 // the touch into the other window.
1103 if (isPointerDownEvent && mAwaitedFocusedApplication != nullptr) {
Siarhei Vishniakou9306c382022-09-30 15:30:31 -07001104 const int32_t displayId = motionEntry.displayId;
1105 const auto [x, y] = resolveTouchedPosition(motionEntry);
Harry Cutts33476232023-01-30 19:57:29 +00001106 const bool isStylus = isPointerFromStylus(motionEntry, /*pointerIndex=*/0);
Siarhei Vishniakou9306c382022-09-30 15:30:31 -07001107
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08001108 auto [touchedWindowHandle, _] = findTouchedWindowAtLocked(displayId, x, y, isStylus);
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001109 if (touchedWindowHandle != nullptr &&
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001110 touchedWindowHandle->getApplicationToken() !=
1111 mAwaitedFocusedApplication->getApplicationToken()) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001112 // User touched a different application than the one we are waiting on.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001113 ALOGI("Pruning input queue because user touched a different application while waiting "
1114 "for %s",
1115 mAwaitedFocusedApplication->getName().c_str());
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001116 return true;
1117 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001118
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08001119 // Alternatively, maybe there's a spy window that could handle this event.
1120 const std::vector<sp<WindowInfoHandle>> touchedSpies =
1121 findTouchedSpyWindowsAtLocked(displayId, x, y, isStylus);
1122 for (const auto& windowHandle : touchedSpies) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07001123 const std::shared_ptr<Connection> connection =
1124 getConnectionLocked(windowHandle->getToken());
Siarhei Vishniakou34ed4d42020-06-18 00:43:02 +00001125 if (connection != nullptr && connection->responsive) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08001126 // This spy window could take more input. Drop all events preceding this
1127 // event, so that the spy window can get a chance to receive the stream.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001128 ALOGW("Pruning the input queue because %s is unresponsive, but we have a "
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08001129 "responsive spy window that may handle the event.",
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001130 mAwaitedFocusedApplication->getName().c_str());
1131 return true;
1132 }
1133 }
1134 }
1135
1136 // Prevent getting stuck: if we have a pending key event, and some motion events that have not
1137 // yet been processed by some connections, the dispatcher will wait for these motion
1138 // events to be processed before dispatching the key event. This is because these motion events
1139 // may cause a new window to be launched, which the user might expect to receive focus.
1140 // To prevent waiting forever for such events, just send the key to the currently focused window
1141 if (isPointerDownEvent && mKeyIsWaitingForEventsTimeout) {
1142 ALOGD("Received a new pointer down event, stop waiting for events to process and "
1143 "just send the pending key event to the focused window.");
1144 mKeyIsWaitingForEventsTimeout = now();
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001145 }
1146 return false;
1147}
1148
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001149bool InputDispatcher::enqueueInboundEventLocked(std::unique_ptr<EventEntry> newEntry) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001150 bool needWake = mInboundQueue.empty();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001151 mInboundQueue.push_back(std::move(newEntry));
1152 EventEntry& entry = *(mInboundQueue.back());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001153 traceInboundQueueLengthLocked();
1154
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001155 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001156 case EventEntry::Type::KEY: {
Prabir Pradhan5735a322022-04-11 17:23:34 +00001157 LOG_ALWAYS_FATAL_IF((entry.policyFlags & POLICY_FLAG_TRUSTED) == 0,
1158 "Unexpected untrusted event.");
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001159 // Optimize app switch latency.
1160 // If the application takes too long to catch up then we drop all events preceding
1161 // the app switch key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001162 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001163 if (isAppSwitchKeyEvent(keyEntry)) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001164 if (keyEntry.action == AKEY_EVENT_ACTION_DOWN) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001165 mAppSwitchSawKeyDown = true;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001166 } else if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001167 if (mAppSwitchSawKeyDown) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001168 if (DEBUG_APP_SWITCH) {
1169 ALOGD("App switch is pending!");
1170 }
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001171 mAppSwitchDueTime = keyEntry.eventTime + APP_SWITCH_TIMEOUT;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001172 mAppSwitchSawKeyDown = false;
1173 needWake = true;
1174 }
1175 }
1176 }
Arthur Hung2ee6d0b2022-03-03 20:19:38 +08001177
1178 // If a new up event comes in, and the pending event with same key code has been asked
1179 // to try again later because of the policy. We have to reset the intercept key wake up
1180 // time for it may have been handled in the policy and could be dropped.
1181 if (keyEntry.action == AKEY_EVENT_ACTION_UP && mPendingEvent &&
1182 mPendingEvent->type == EventEntry::Type::KEY) {
1183 KeyEntry& pendingKey = static_cast<KeyEntry&>(*mPendingEvent);
1184 if (pendingKey.keyCode == keyEntry.keyCode &&
1185 pendingKey.interceptKeyResult ==
Michael Wright5caf55a2022-11-24 22:31:42 +00001186 KeyEntry::InterceptKeyResult::TRY_AGAIN_LATER) {
1187 pendingKey.interceptKeyResult = KeyEntry::InterceptKeyResult::UNKNOWN;
Arthur Hung2ee6d0b2022-03-03 20:19:38 +08001188 pendingKey.interceptKeyWakeupTime = 0;
1189 needWake = true;
1190 }
1191 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001192 break;
1193 }
1194
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001195 case EventEntry::Type::MOTION: {
Prabir Pradhan5735a322022-04-11 17:23:34 +00001196 LOG_ALWAYS_FATAL_IF((entry.policyFlags & POLICY_FLAG_TRUSTED) == 0,
1197 "Unexpected untrusted event.");
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001198 if (shouldPruneInboundQueueLocked(static_cast<MotionEntry&>(entry))) {
1199 mNextUnblockedEvent = mInboundQueue.back();
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001200 needWake = true;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001201 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001202 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001203 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001204 case EventEntry::Type::FOCUS: {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001205 LOG_ALWAYS_FATAL("Focus events should be inserted using enqueueFocusEventLocked");
1206 break;
1207 }
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001208 case EventEntry::Type::TOUCH_MODE_CHANGED:
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001209 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08001210 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07001211 case EventEntry::Type::SENSOR:
arthurhungb89ccb02020-12-30 16:19:01 +08001212 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
1213 case EventEntry::Type::DRAG: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001214 // nothing to do
1215 break;
1216 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001217 }
1218
1219 return needWake;
1220}
1221
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001222void InputDispatcher::addRecentEventLocked(std::shared_ptr<EventEntry> entry) {
Chris Yef59a2f42020-10-16 12:55:26 -07001223 // Do not store sensor event in recent queue to avoid flooding the queue.
1224 if (entry->type != EventEntry::Type::SENSOR) {
1225 mRecentQueue.push_back(entry);
1226 }
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001227 if (mRecentQueue.size() > RECENT_QUEUE_MAX_SIZE) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001228 mRecentQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001229 }
1230}
1231
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08001232std::pair<sp<WindowInfoHandle>, std::vector<InputTarget>>
Prabir Pradhan82e081e2022-12-06 09:50:09 +00001233InputDispatcher::findTouchedWindowAtLocked(int32_t displayId, float x, float y, bool isStylus,
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08001234 bool ignoreDragWindow) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001235 // Traverse windows from front to back to find touched window.
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08001236 std::vector<InputTarget> outsideTargets;
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001237 const auto& windowHandles = getWindowHandlesLocked(displayId);
chaviw98318de2021-05-19 16:45:23 -05001238 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
arthurhung6d4bed92021-03-17 11:59:33 +08001239 if (ignoreDragWindow && haveSameToken(windowHandle, mDragState->dragWindow)) {
arthurhungb89ccb02020-12-30 16:19:01 +08001240 continue;
1241 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001242
Prabir Pradhan3f90d312021-11-19 03:57:24 -08001243 const WindowInfo& info = *windowHandle->getInfo();
Prabir Pradhan33e3baa2022-12-06 20:30:22 +00001244 if (!info.isSpy() &&
1245 windowAcceptsTouchAt(info, displayId, x, y, isStylus, getTransformLocked(displayId))) {
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08001246 return {windowHandle, outsideTargets};
Prabir Pradhan3f90d312021-11-19 03:57:24 -08001247 }
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001248
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08001249 if (info.inputConfig.test(WindowInfo::InputConfig::WATCH_OUTSIDE_TOUCH)) {
1250 addWindowTargetLocked(windowHandle, InputTarget::Flags::DISPATCH_AS_OUTSIDE,
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08001251 /*pointerIds=*/{}, /*firstDownTimeInTarget=*/std::nullopt,
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08001252 outsideTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001253 }
1254 }
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08001255 return {nullptr, {}};
Michael Wrightd02c5b62014-02-10 15:10:22 -08001256}
1257
Prabir Pradhand65552b2021-10-07 11:23:50 -07001258std::vector<sp<WindowInfoHandle>> InputDispatcher::findTouchedSpyWindowsAtLocked(
Prabir Pradhan82e081e2022-12-06 09:50:09 +00001259 int32_t displayId, float x, float y, bool isStylus) const {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001260 // Traverse windows from front to back and gather the touched spy windows.
1261 std::vector<sp<WindowInfoHandle>> spyWindows;
1262 const auto& windowHandles = getWindowHandlesLocked(displayId);
1263 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
1264 const WindowInfo& info = *windowHandle->getInfo();
1265
Prabir Pradhan33e3baa2022-12-06 20:30:22 +00001266 if (!windowAcceptsTouchAt(info, displayId, x, y, isStylus, getTransformLocked(displayId))) {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001267 continue;
1268 }
1269 if (!info.isSpy()) {
1270 // The first touched non-spy window was found, so return the spy windows touched so far.
1271 return spyWindows;
1272 }
1273 spyWindows.push_back(windowHandle);
1274 }
1275 return spyWindows;
1276}
1277
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001278void InputDispatcher::dropInboundEventLocked(const EventEntry& entry, DropReason dropReason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001279 const char* reason;
1280 switch (dropReason) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001281 case DropReason::POLICY:
Prabir Pradhan65613802023-02-22 23:36:58 +00001282 if (debugInboundEventDetails()) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001283 ALOGD("Dropped event because policy consumed it.");
1284 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001285 reason = "inbound event was dropped because the policy consumed it";
1286 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001287 case DropReason::DISABLED:
1288 if (mLastDropReason != DropReason::DISABLED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001289 ALOGI("Dropped event because input dispatch is disabled.");
1290 }
1291 reason = "inbound event was dropped because input dispatch is disabled";
1292 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001293 case DropReason::APP_SWITCH:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001294 ALOGI("Dropped event because of pending overdue app switch.");
1295 reason = "inbound event was dropped because of pending overdue app switch";
1296 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001297 case DropReason::BLOCKED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001298 ALOGI("Dropped event because the current application is not responding and the user "
1299 "has started interacting with a different application.");
1300 reason = "inbound event was dropped because the current application is not responding "
1301 "and the user has started interacting with a different application";
1302 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001303 case DropReason::STALE:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001304 ALOGI("Dropped event because it is stale.");
1305 reason = "inbound event was dropped because it is stale";
1306 break;
Prabir Pradhan99987712020-11-10 18:43:05 -08001307 case DropReason::NO_POINTER_CAPTURE:
1308 ALOGI("Dropped event because there is no window with Pointer Capture.");
1309 reason = "inbound event was dropped because there is no window with Pointer Capture";
1310 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001311 case DropReason::NOT_DROPPED: {
1312 LOG_ALWAYS_FATAL("Should not be dropping a NOT_DROPPED event");
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001313 return;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001314 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001315 }
1316
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001317 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001318 case EventEntry::Type::KEY: {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001319 CancelationOptions options(CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS, reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001320 synthesizeCancelationEventsForAllConnectionsLocked(options);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001321 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001322 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001323 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001324 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
1325 if (motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001326 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS, reason);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001327 synthesizeCancelationEventsForAllConnectionsLocked(options);
1328 } else {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001329 CancelationOptions options(CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS,
1330 reason);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001331 synthesizeCancelationEventsForAllConnectionsLocked(options);
1332 }
1333 break;
1334 }
Chris Yef59a2f42020-10-16 12:55:26 -07001335 case EventEntry::Type::SENSOR: {
1336 break;
1337 }
arthurhungb89ccb02020-12-30 16:19:01 +08001338 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
1339 case EventEntry::Type::DRAG: {
Prabir Pradhan99987712020-11-10 18:43:05 -08001340 break;
1341 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001342 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001343 case EventEntry::Type::TOUCH_MODE_CHANGED:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001344 case EventEntry::Type::CONFIGURATION_CHANGED:
1345 case EventEntry::Type::DEVICE_RESET: {
Dominik Laskowski75788452021-02-09 18:51:25 -08001346 LOG_ALWAYS_FATAL("Should not drop %s events", ftl::enum_string(entry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001347 break;
1348 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001349 }
1350}
1351
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08001352static bool isAppSwitchKeyCode(int32_t keyCode) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001353 return keyCode == AKEYCODE_HOME || keyCode == AKEYCODE_ENDCALL ||
1354 keyCode == AKEYCODE_APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001355}
1356
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001357bool InputDispatcher::isAppSwitchKeyEvent(const KeyEntry& keyEntry) {
1358 return !(keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) && isAppSwitchKeyCode(keyEntry.keyCode) &&
1359 (keyEntry.policyFlags & POLICY_FLAG_TRUSTED) &&
1360 (keyEntry.policyFlags & POLICY_FLAG_PASS_TO_USER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001361}
1362
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07001363bool InputDispatcher::isAppSwitchPendingLocked() const {
Colin Cross5b799302022-10-18 21:52:41 -07001364 return mAppSwitchDueTime != LLONG_MAX;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001365}
1366
1367void InputDispatcher::resetPendingAppSwitchLocked(bool handled) {
Colin Cross5b799302022-10-18 21:52:41 -07001368 mAppSwitchDueTime = LLONG_MAX;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001369
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001370 if (DEBUG_APP_SWITCH) {
1371 if (handled) {
1372 ALOGD("App switch has arrived.");
1373 } else {
1374 ALOGD("App switch was abandoned.");
1375 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001376 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001377}
1378
Michael Wrightd02c5b62014-02-10 15:10:22 -08001379bool InputDispatcher::haveCommandsLocked() const {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001380 return !mCommandQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001381}
1382
Prabir Pradhancef936d2021-07-21 16:17:52 +00001383bool InputDispatcher::runCommandsLockedInterruptable() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001384 if (mCommandQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001385 return false;
1386 }
1387
1388 do {
Prabir Pradhancef936d2021-07-21 16:17:52 +00001389 auto command = std::move(mCommandQueue.front());
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001390 mCommandQueue.pop_front();
Prabir Pradhancef936d2021-07-21 16:17:52 +00001391 // Commands are run with the lock held, but may release and re-acquire the lock from within.
1392 command();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001393 } while (!mCommandQueue.empty());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001394 return true;
1395}
1396
Prabir Pradhancef936d2021-07-21 16:17:52 +00001397void InputDispatcher::postCommandLocked(Command&& command) {
1398 mCommandQueue.push_back(command);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001399}
1400
1401void InputDispatcher::drainInboundQueueLocked() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001402 while (!mInboundQueue.empty()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001403 std::shared_ptr<EventEntry> entry = mInboundQueue.front();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001404 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001405 releaseInboundEventLocked(entry);
1406 }
1407 traceInboundQueueLengthLocked();
1408}
1409
1410void InputDispatcher::releasePendingEventLocked() {
1411 if (mPendingEvent) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001412 releaseInboundEventLocked(mPendingEvent);
Yi Kong9b14ac62018-07-17 13:48:38 -07001413 mPendingEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001414 }
1415}
1416
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001417void InputDispatcher::releaseInboundEventLocked(std::shared_ptr<EventEntry> entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001418 InjectionState* injectionState = entry->injectionState;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001419 if (injectionState && injectionState->injectionResult == InputEventInjectionResult::PENDING) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001420 if (DEBUG_DISPATCH_CYCLE) {
1421 ALOGD("Injected inbound event was dropped.");
1422 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001423 setInjectionResult(*entry, InputEventInjectionResult::FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001424 }
1425 if (entry == mNextUnblockedEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001426 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001427 }
1428 addRecentEventLocked(entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001429}
1430
1431void InputDispatcher::resetKeyRepeatLocked() {
1432 if (mKeyRepeatState.lastKeyEntry) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001433 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001434 }
1435}
1436
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001437std::shared_ptr<KeyEntry> InputDispatcher::synthesizeKeyRepeatLocked(nsecs_t currentTime) {
1438 std::shared_ptr<KeyEntry> entry = mKeyRepeatState.lastKeyEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001439
Michael Wright2e732952014-09-24 13:26:59 -07001440 uint32_t policyFlags = entry->policyFlags &
1441 (POLICY_FLAG_RAW_MASK | POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_TRUSTED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001442
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001443 std::shared_ptr<KeyEntry> newEntry =
1444 std::make_unique<KeyEntry>(mIdGenerator.nextId(), currentTime, entry->deviceId,
1445 entry->source, entry->displayId, policyFlags, entry->action,
1446 entry->flags, entry->keyCode, entry->scanCode,
1447 entry->metaState, entry->repeatCount + 1, entry->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001448
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001449 newEntry->syntheticRepeat = true;
1450 mKeyRepeatState.lastKeyEntry = newEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001451 mKeyRepeatState.nextRepeatTime = currentTime + mConfig.keyRepeatDelay;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001452 return newEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001453}
1454
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001455bool InputDispatcher::dispatchConfigurationChangedLocked(nsecs_t currentTime,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001456 const ConfigurationChangedEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001457 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1458 ALOGD("dispatchConfigurationChanged - eventTime=%" PRId64, entry.eventTime);
1459 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001460
1461 // Reset key repeating in case a keyboard device was added or removed or something.
1462 resetKeyRepeatLocked();
1463
1464 // Enqueue a command to run outside the lock to tell the policy that the configuration changed.
Prabir Pradhancef936d2021-07-21 16:17:52 +00001465 auto command = [this, eventTime = entry.eventTime]() REQUIRES(mLock) {
1466 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00001467 mPolicy.notifyConfigurationChanged(eventTime);
Prabir Pradhancef936d2021-07-21 16:17:52 +00001468 };
1469 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001470 return true;
1471}
1472
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001473bool InputDispatcher::dispatchDeviceResetLocked(nsecs_t currentTime,
1474 const DeviceResetEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001475 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1476 ALOGD("dispatchDeviceReset - eventTime=%" PRId64 ", deviceId=%d", entry.eventTime,
1477 entry.deviceId);
1478 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001479
liushenxiang42232912021-05-21 20:24:09 +08001480 // Reset key repeating in case a keyboard device was disabled or enabled.
1481 if (mKeyRepeatState.lastKeyEntry && mKeyRepeatState.lastKeyEntry->deviceId == entry.deviceId) {
1482 resetKeyRepeatLocked();
1483 }
1484
Michael Wrightfb04fd52022-11-24 22:31:11 +00001485 CancelationOptions options(CancelationOptions::Mode::CANCEL_ALL_EVENTS, "device was reset");
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001486 options.deviceId = entry.deviceId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001487 synthesizeCancelationEventsForAllConnectionsLocked(options);
Siarhei Vishniakou0686f0c2023-05-02 11:56:15 -07001488
1489 // Remove all active pointers from this device
1490 for (auto& [_, touchState] : mTouchStatesByDisplay) {
1491 touchState.removeAllPointersForDevice(entry.deviceId);
1492 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001493 return true;
1494}
1495
Vishnu Nairad321cd2020-08-20 16:40:21 -07001496void InputDispatcher::enqueueFocusEventLocked(const sp<IBinder>& windowToken, bool hasFocus,
Vishnu Nairc519ff72021-01-21 08:23:08 -08001497 const std::string& reason) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001498 if (mPendingEvent != nullptr) {
1499 // Move the pending event to the front of the queue. This will give the chance
1500 // for the pending event to get dispatched to the newly focused window
1501 mInboundQueue.push_front(mPendingEvent);
1502 mPendingEvent = nullptr;
1503 }
1504
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001505 std::unique_ptr<FocusEntry> focusEntry =
1506 std::make_unique<FocusEntry>(mIdGenerator.nextId(), now(), windowToken, hasFocus,
1507 reason);
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001508
1509 // This event should go to the front of the queue, but behind all other focus events
1510 // Find the last focus event, and insert right after it
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001511 std::deque<std::shared_ptr<EventEntry>>::reverse_iterator it =
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001512 std::find_if(mInboundQueue.rbegin(), mInboundQueue.rend(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001513 [](const std::shared_ptr<EventEntry>& event) {
1514 return event->type == EventEntry::Type::FOCUS;
1515 });
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001516
1517 // Maintain the order of focus events. Insert the entry after all other focus events.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001518 mInboundQueue.insert(it.base(), std::move(focusEntry));
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001519}
1520
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001521void InputDispatcher::dispatchFocusLocked(nsecs_t currentTime, std::shared_ptr<FocusEntry> entry) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05001522 std::shared_ptr<InputChannel> channel = getInputChannelLocked(entry->connectionToken);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001523 if (channel == nullptr) {
1524 return; // Window has gone away
1525 }
1526 InputTarget target;
1527 target.inputChannel = channel;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08001528 target.flags = InputTarget::Flags::DISPATCH_AS_IS;
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001529 entry->dispatchInProgress = true;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00001530 std::string message = std::string("Focus ") + (entry->hasFocus ? "entering " : "leaving ") +
1531 channel->getName();
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07001532 std::string reason = std::string("reason=").append(entry->reason);
1533 android_log_event_list(LOGTAG_INPUT_FOCUS) << message << reason << LOG_ID_EVENTS;
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001534 dispatchEventLocked(currentTime, entry, {target});
1535}
1536
Prabir Pradhan99987712020-11-10 18:43:05 -08001537void InputDispatcher::dispatchPointerCaptureChangedLocked(
1538 nsecs_t currentTime, const std::shared_ptr<PointerCaptureChangedEntry>& entry,
1539 DropReason& dropReason) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001540 dropReason = DropReason::NOT_DROPPED;
1541
Prabir Pradhan99987712020-11-10 18:43:05 -08001542 const bool haveWindowWithPointerCapture = mWindowTokenWithPointerCapture != nullptr;
Prabir Pradhan99987712020-11-10 18:43:05 -08001543 sp<IBinder> token;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001544
1545 if (entry->pointerCaptureRequest.enable) {
1546 // Enable Pointer Capture.
1547 if (haveWindowWithPointerCapture &&
1548 (entry->pointerCaptureRequest == mCurrentPointerCaptureRequest)) {
Prabir Pradhan7092e262022-05-03 16:51:09 +00001549 // This can happen if pointer capture is disabled and re-enabled before we notify the
1550 // app of the state change, so there is no need to notify the app.
1551 ALOGI("Skipping dispatch of Pointer Capture being enabled: no state change.");
1552 return;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001553 }
1554 if (!mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08001555 // This can happen if a window requests capture and immediately releases capture.
1556 ALOGW("No window requested Pointer Capture.");
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001557 dropReason = DropReason::NO_POINTER_CAPTURE;
Prabir Pradhan99987712020-11-10 18:43:05 -08001558 return;
1559 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001560 if (entry->pointerCaptureRequest.seq != mCurrentPointerCaptureRequest.seq) {
1561 ALOGI("Skipping dispatch of Pointer Capture being enabled: sequence number mismatch.");
1562 return;
1563 }
1564
Vishnu Nairc519ff72021-01-21 08:23:08 -08001565 token = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Prabir Pradhan99987712020-11-10 18:43:05 -08001566 LOG_ALWAYS_FATAL_IF(!token, "Cannot find focused window for Pointer Capture.");
1567 mWindowTokenWithPointerCapture = token;
1568 } else {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001569 // Disable Pointer Capture.
1570 // We do not check if the sequence number matches for requests to disable Pointer Capture
1571 // for two reasons:
1572 // 1. Pointer Capture can be disabled by a focus change, which means we can get two entries
1573 // to disable capture with the same sequence number: one generated by
1574 // disablePointerCaptureForcedLocked() and another as an acknowledgement of Pointer
1575 // Capture being disabled in InputReader.
1576 // 2. We respect any request to disable Pointer Capture generated by InputReader, since the
1577 // actual Pointer Capture state that affects events being generated by input devices is
1578 // in InputReader.
1579 if (!haveWindowWithPointerCapture) {
1580 // Pointer capture was already forcefully disabled because of focus change.
1581 dropReason = DropReason::NOT_DROPPED;
1582 return;
1583 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001584 token = mWindowTokenWithPointerCapture;
1585 mWindowTokenWithPointerCapture = nullptr;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001586 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan7d030382020-12-21 07:58:35 -08001587 setPointerCaptureLocked(false);
1588 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001589 }
1590
1591 auto channel = getInputChannelLocked(token);
1592 if (channel == nullptr) {
1593 // Window has gone away, clean up Pointer Capture state.
1594 mWindowTokenWithPointerCapture = nullptr;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001595 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan7d030382020-12-21 07:58:35 -08001596 setPointerCaptureLocked(false);
1597 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001598 return;
1599 }
1600 InputTarget target;
1601 target.inputChannel = channel;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08001602 target.flags = InputTarget::Flags::DISPATCH_AS_IS;
Prabir Pradhan99987712020-11-10 18:43:05 -08001603 entry->dispatchInProgress = true;
1604 dispatchEventLocked(currentTime, entry, {target});
1605
1606 dropReason = DropReason::NOT_DROPPED;
1607}
1608
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001609void InputDispatcher::dispatchTouchModeChangeLocked(nsecs_t currentTime,
1610 const std::shared_ptr<TouchModeEntry>& entry) {
1611 const std::vector<sp<WindowInfoHandle>>& windowHandles =
Antonio Kantek15beb512022-06-13 22:35:41 +00001612 getWindowHandlesLocked(entry->displayId);
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001613 if (windowHandles.empty()) {
1614 return;
1615 }
1616 const std::vector<InputTarget> inputTargets =
1617 getInputTargetsFromWindowHandlesLocked(windowHandles);
1618 if (inputTargets.empty()) {
1619 return;
1620 }
1621 entry->dispatchInProgress = true;
1622 dispatchEventLocked(currentTime, entry, inputTargets);
1623}
1624
1625std::vector<InputTarget> InputDispatcher::getInputTargetsFromWindowHandlesLocked(
1626 const std::vector<sp<WindowInfoHandle>>& windowHandles) const {
1627 std::vector<InputTarget> inputTargets;
1628 for (const sp<WindowInfoHandle>& handle : windowHandles) {
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001629 const sp<IBinder>& token = handle->getToken();
1630 if (token == nullptr) {
1631 continue;
1632 }
1633 std::shared_ptr<InputChannel> channel = getInputChannelLocked(token);
1634 if (channel == nullptr) {
1635 continue; // Window has gone away
1636 }
1637 InputTarget target;
1638 target.inputChannel = channel;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08001639 target.flags = InputTarget::Flags::DISPATCH_AS_IS;
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001640 inputTargets.push_back(target);
1641 }
1642 return inputTargets;
1643}
1644
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001645bool InputDispatcher::dispatchKeyLocked(nsecs_t currentTime, std::shared_ptr<KeyEntry> entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001646 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001647 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001648 if (!entry->dispatchInProgress) {
1649 if (entry->repeatCount == 0 && entry->action == AKEY_EVENT_ACTION_DOWN &&
1650 (entry->policyFlags & POLICY_FLAG_TRUSTED) &&
1651 (!(entry->policyFlags & POLICY_FLAG_DISABLE_KEY_REPEAT))) {
1652 if (mKeyRepeatState.lastKeyEntry &&
Chris Ye2ad95392020-09-01 13:44:44 -07001653 mKeyRepeatState.lastKeyEntry->keyCode == entry->keyCode &&
Michael Wrightd02c5b62014-02-10 15:10:22 -08001654 // We have seen two identical key downs in a row which indicates that the device
1655 // driver is automatically generating key repeats itself. We take note of the
1656 // repeat here, but we disable our own next key repeat timer since it is clear that
1657 // we will not need to synthesize key repeats ourselves.
Chris Ye2ad95392020-09-01 13:44:44 -07001658 mKeyRepeatState.lastKeyEntry->deviceId == entry->deviceId) {
1659 // Make sure we don't get key down from a different device. If a different
1660 // device Id has same key pressed down, the new device Id will replace the
1661 // current one to hold the key repeat with repeat count reset.
1662 // In the future when got a KEY_UP on the device id, drop it and do not
1663 // stop the key repeat on current device.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001664 entry->repeatCount = mKeyRepeatState.lastKeyEntry->repeatCount + 1;
1665 resetKeyRepeatLocked();
Colin Cross5b799302022-10-18 21:52:41 -07001666 mKeyRepeatState.nextRepeatTime = LLONG_MAX; // don't generate repeats ourselves
Michael Wrightd02c5b62014-02-10 15:10:22 -08001667 } else {
1668 // Not a repeat. Save key down state in case we do see a repeat later.
1669 resetKeyRepeatLocked();
1670 mKeyRepeatState.nextRepeatTime = entry->eventTime + mConfig.keyRepeatTimeout;
1671 }
1672 mKeyRepeatState.lastKeyEntry = entry;
Chris Ye2ad95392020-09-01 13:44:44 -07001673 } else if (entry->action == AKEY_EVENT_ACTION_UP && mKeyRepeatState.lastKeyEntry &&
1674 mKeyRepeatState.lastKeyEntry->deviceId != entry->deviceId) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001675 // The key on device 'deviceId' is still down, do not stop key repeat
Prabir Pradhan65613802023-02-22 23:36:58 +00001676 if (debugInboundEventDetails()) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001677 ALOGD("deviceId=%d got KEY_UP as stale", entry->deviceId);
1678 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001679 } else if (!entry->syntheticRepeat) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001680 resetKeyRepeatLocked();
1681 }
1682
1683 if (entry->repeatCount == 1) {
1684 entry->flags |= AKEY_EVENT_FLAG_LONG_PRESS;
1685 } else {
1686 entry->flags &= ~AKEY_EVENT_FLAG_LONG_PRESS;
1687 }
1688
1689 entry->dispatchInProgress = true;
1690
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001691 logOutboundKeyDetails("dispatchKey - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001692 }
1693
1694 // Handle case where the policy asked us to try again later last time.
Michael Wright5caf55a2022-11-24 22:31:42 +00001695 if (entry->interceptKeyResult == KeyEntry::InterceptKeyResult::TRY_AGAIN_LATER) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001696 if (currentTime < entry->interceptKeyWakeupTime) {
1697 if (entry->interceptKeyWakeupTime < *nextWakeupTime) {
1698 *nextWakeupTime = entry->interceptKeyWakeupTime;
1699 }
1700 return false; // wait until next wakeup
1701 }
Michael Wright5caf55a2022-11-24 22:31:42 +00001702 entry->interceptKeyResult = KeyEntry::InterceptKeyResult::UNKNOWN;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001703 entry->interceptKeyWakeupTime = 0;
1704 }
1705
1706 // Give the policy a chance to intercept the key.
Michael Wright5caf55a2022-11-24 22:31:42 +00001707 if (entry->interceptKeyResult == KeyEntry::InterceptKeyResult::UNKNOWN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001708 if (entry->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07001709 sp<IBinder> focusedWindowToken =
Vishnu Nairc519ff72021-01-21 08:23:08 -08001710 mFocusResolver.getFocusedWindowToken(getTargetDisplayId(*entry));
Prabir Pradhancef936d2021-07-21 16:17:52 +00001711
1712 auto command = [this, focusedWindowToken, entry]() REQUIRES(mLock) {
1713 doInterceptKeyBeforeDispatchingCommand(focusedWindowToken, *entry);
1714 };
1715 postCommandLocked(std::move(command));
Josep del Riob3981622023-04-18 15:49:45 +00001716 // Poke user activity for keys not passed to user
1717 pokeUserActivityLocked(*entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001718 return false; // wait for the command to run
1719 } else {
Michael Wright5caf55a2022-11-24 22:31:42 +00001720 entry->interceptKeyResult = KeyEntry::InterceptKeyResult::CONTINUE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001721 }
Michael Wright5caf55a2022-11-24 22:31:42 +00001722 } else if (entry->interceptKeyResult == KeyEntry::InterceptKeyResult::SKIP) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001723 if (*dropReason == DropReason::NOT_DROPPED) {
1724 *dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001725 }
1726 }
1727
1728 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001729 if (*dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001730 setInjectionResult(*entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001731 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
1732 : InputEventInjectionResult::FAILED);
Garfield Tan6a5a14e2020-01-28 13:24:04 -08001733 mReporter->reportDroppedKey(entry->id);
Josep del Riob3981622023-04-18 15:49:45 +00001734 // Poke user activity for undispatched keys
1735 pokeUserActivityLocked(*entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001736 return true;
1737 }
1738
1739 // Identify targets.
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001740 InputEventInjectionResult injectionResult;
1741 sp<WindowInfoHandle> focusedWindow =
1742 findFocusedWindowTargetLocked(currentTime, *entry, nextWakeupTime,
1743 /*byref*/ injectionResult);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001744 if (injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001745 return false;
1746 }
1747
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001748 setInjectionResult(*entry, injectionResult);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001749 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001750 return true;
1751 }
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001752 LOG_ALWAYS_FATAL_IF(focusedWindow == nullptr);
1753
1754 std::vector<InputTarget> inputTargets;
1755 addWindowTargetLocked(focusedWindow,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08001756 InputTarget::Flags::FOREGROUND | InputTarget::Flags::DISPATCH_AS_IS,
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08001757 /*pointerIds=*/{}, getDownTime(*entry), inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001758
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001759 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001760 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001761
1762 // Dispatch the key.
1763 dispatchEventLocked(currentTime, entry, inputTargets);
1764 return true;
1765}
1766
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001767void InputDispatcher::logOutboundKeyDetails(const char* prefix, const KeyEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001768 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1769 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32 ", "
1770 "policyFlags=0x%x, action=0x%x, flags=0x%x, keyCode=0x%x, scanCode=0x%x, "
1771 "metaState=0x%x, repeatCount=%d, downTime=%" PRId64,
1772 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId,
1773 entry.policyFlags, entry.action, entry.flags, entry.keyCode, entry.scanCode,
1774 entry.metaState, entry.repeatCount, entry.downTime);
1775 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001776}
1777
Prabir Pradhancef936d2021-07-21 16:17:52 +00001778void InputDispatcher::dispatchSensorLocked(nsecs_t currentTime,
1779 const std::shared_ptr<SensorEntry>& entry,
Chris Yef59a2f42020-10-16 12:55:26 -07001780 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001781 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1782 ALOGD("notifySensorEvent eventTime=%" PRId64 ", hwTimestamp=%" PRId64 ", deviceId=%d, "
1783 "source=0x%x, sensorType=%s",
1784 entry->eventTime, entry->hwTimestamp, entry->deviceId, entry->source,
Dominik Laskowski75788452021-02-09 18:51:25 -08001785 ftl::enum_string(entry->sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001786 }
Prabir Pradhancef936d2021-07-21 16:17:52 +00001787 auto command = [this, entry]() REQUIRES(mLock) {
1788 scoped_unlock unlock(mLock);
1789
1790 if (entry->accuracyChanged) {
Prabir Pradhana41d2442023-04-20 21:30:40 +00001791 mPolicy.notifySensorAccuracy(entry->deviceId, entry->sensorType, entry->accuracy);
Prabir Pradhancef936d2021-07-21 16:17:52 +00001792 }
Prabir Pradhana41d2442023-04-20 21:30:40 +00001793 mPolicy.notifySensorEvent(entry->deviceId, entry->sensorType, entry->accuracy,
1794 entry->hwTimestamp, entry->values);
Prabir Pradhancef936d2021-07-21 16:17:52 +00001795 };
1796 postCommandLocked(std::move(command));
Chris Yef59a2f42020-10-16 12:55:26 -07001797}
1798
1799bool InputDispatcher::flushSensor(int deviceId, InputDeviceSensorType sensorType) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001800 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1801 ALOGD("flushSensor deviceId=%d, sensorType=%s", deviceId,
Dominik Laskowski75788452021-02-09 18:51:25 -08001802 ftl::enum_string(sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001803 }
Chris Yef59a2f42020-10-16 12:55:26 -07001804 { // acquire lock
1805 std::scoped_lock _l(mLock);
1806
1807 for (auto it = mInboundQueue.begin(); it != mInboundQueue.end(); it++) {
1808 std::shared_ptr<EventEntry> entry = *it;
1809 if (entry->type == EventEntry::Type::SENSOR) {
1810 it = mInboundQueue.erase(it);
1811 releaseInboundEventLocked(entry);
1812 }
1813 }
1814 }
1815 return true;
1816}
1817
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001818bool InputDispatcher::dispatchMotionLocked(nsecs_t currentTime, std::shared_ptr<MotionEntry> entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001819 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001820 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001821 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001822 if (!entry->dispatchInProgress) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001823 entry->dispatchInProgress = true;
1824
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001825 logOutboundMotionDetails("dispatchMotion - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001826 }
1827
1828 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001829 if (*dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001830 setInjectionResult(*entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001831 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
1832 : InputEventInjectionResult::FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001833 return true;
1834 }
1835
Prabir Pradhanaa561d12021-09-24 06:57:33 -07001836 const bool isPointerEvent = isFromSource(entry->source, AINPUT_SOURCE_CLASS_POINTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001837
1838 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001839 std::vector<InputTarget> inputTargets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001840
1841 bool conflictingPointerActions = false;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001842 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001843 if (isPointerEvent) {
1844 // Pointer event. (eg. touchscreen)
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00001845
1846 if (mDragState &&
1847 (entry->action & AMOTION_EVENT_ACTION_MASK) == AMOTION_EVENT_ACTION_POINTER_DOWN) {
1848 // If drag and drop ongoing and pointer down occur: pilfer drag window pointers
1849 pilferPointersLocked(mDragState->dragWindow->getToken());
1850 }
1851
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08001852 inputTargets =
Siarhei Vishniakou4fe57392022-10-25 13:44:30 -07001853 findTouchedWindowTargetsLocked(currentTime, *entry, &conflictingPointerActions,
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001854 /*byref*/ injectionResult);
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08001855 LOG_ALWAYS_FATAL_IF(injectionResult != InputEventInjectionResult::SUCCEEDED &&
1856 !inputTargets.empty());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001857 } else {
1858 // Non touch event. (eg. trackball)
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001859 sp<WindowInfoHandle> focusedWindow =
1860 findFocusedWindowTargetLocked(currentTime, *entry, nextWakeupTime, injectionResult);
1861 if (injectionResult == InputEventInjectionResult::SUCCEEDED) {
1862 LOG_ALWAYS_FATAL_IF(focusedWindow == nullptr);
1863 addWindowTargetLocked(focusedWindow,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08001864 InputTarget::Flags::FOREGROUND |
1865 InputTarget::Flags::DISPATCH_AS_IS,
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08001866 /*pointerIds=*/{}, getDownTime(*entry), inputTargets);
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001867 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001868 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001869 if (injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001870 return false;
1871 }
1872
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001873 setInjectionResult(*entry, injectionResult);
Prabir Pradhan5735a322022-04-11 17:23:34 +00001874 if (injectionResult == InputEventInjectionResult::TARGET_MISMATCH) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001875 return true;
1876 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001877 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001878 CancelationOptions::Mode mode(
1879 isPointerEvent ? CancelationOptions::Mode::CANCEL_POINTER_EVENTS
1880 : CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS);
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001881 CancelationOptions options(mode, "input event injection failed");
1882 synthesizeCancelationEventsForMonitorsLocked(options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001883 return true;
1884 }
1885
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001886 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001887 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001888
1889 // Dispatch the motion.
1890 if (conflictingPointerActions) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001891 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001892 "conflicting pointer actions");
Michael Wrightd02c5b62014-02-10 15:10:22 -08001893 synthesizeCancelationEventsForAllConnectionsLocked(options);
1894 }
1895 dispatchEventLocked(currentTime, entry, inputTargets);
1896 return true;
1897}
1898
chaviw98318de2021-05-19 16:45:23 -05001899void InputDispatcher::enqueueDragEventLocked(const sp<WindowInfoHandle>& windowHandle,
Arthur Hung54745652022-04-20 07:17:41 +00001900 bool isExiting, const int32_t rawX,
1901 const int32_t rawY) {
1902 const vec2 xy = windowHandle->getInfo()->transform.transform(vec2(rawX, rawY));
arthurhungb89ccb02020-12-30 16:19:01 +08001903 std::unique_ptr<DragEntry> dragEntry =
Arthur Hung54745652022-04-20 07:17:41 +00001904 std::make_unique<DragEntry>(mIdGenerator.nextId(), now(), windowHandle->getToken(),
1905 isExiting, xy.x, xy.y);
arthurhungb89ccb02020-12-30 16:19:01 +08001906
1907 enqueueInboundEventLocked(std::move(dragEntry));
1908}
1909
1910void InputDispatcher::dispatchDragLocked(nsecs_t currentTime, std::shared_ptr<DragEntry> entry) {
1911 std::shared_ptr<InputChannel> channel = getInputChannelLocked(entry->connectionToken);
1912 if (channel == nullptr) {
1913 return; // Window has gone away
1914 }
1915 InputTarget target;
1916 target.inputChannel = channel;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08001917 target.flags = InputTarget::Flags::DISPATCH_AS_IS;
arthurhungb89ccb02020-12-30 16:19:01 +08001918 entry->dispatchInProgress = true;
1919 dispatchEventLocked(currentTime, entry, {target});
1920}
1921
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001922void InputDispatcher::logOutboundMotionDetails(const char* prefix, const MotionEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001923 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -08001924 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=%s, displayId=%" PRId32
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001925 ", policyFlags=0x%x, "
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001926 "action=%s, actionButton=0x%x, flags=0x%x, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001927 "metaState=0x%x, buttonState=0x%x,"
1928 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%" PRId64,
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -08001929 prefix, entry.eventTime, entry.deviceId,
1930 inputEventSourceToString(entry.source).c_str(), entry.displayId, entry.policyFlags,
1931 MotionEvent::actionToString(entry.action).c_str(), entry.actionButton, entry.flags,
1932 entry.metaState, entry.buttonState, entry.edgeFlags, entry.xPrecision,
1933 entry.yPrecision, entry.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001934
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001935 for (uint32_t i = 0; i < entry.pointerCount; i++) {
Siarhei Vishniakou09a8fe42022-07-21 17:27:03 -07001936 ALOGD(" Pointer %d: id=%d, toolType=%s, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001937 "x=%f, y=%f, pressure=%f, size=%f, "
1938 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
1939 "orientation=%f",
Siarhei Vishniakou09a8fe42022-07-21 17:27:03 -07001940 i, entry.pointerProperties[i].id,
1941 ftl::enum_string(entry.pointerProperties[i].toolType).c_str(),
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001942 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
1943 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
1944 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
1945 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
1946 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
1947 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
1948 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
1949 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
1950 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
1951 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001952 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001953}
1954
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001955void InputDispatcher::dispatchEventLocked(nsecs_t currentTime,
1956 std::shared_ptr<EventEntry> eventEntry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001957 const std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001958 ATRACE_CALL();
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001959 if (DEBUG_DISPATCH_CYCLE) {
1960 ALOGD("dispatchEventToCurrentInputTargets");
1961 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001962
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00001963 processInteractionsLocked(*eventEntry, inputTargets);
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00001964
Michael Wrightd02c5b62014-02-10 15:10:22 -08001965 ALOG_ASSERT(eventEntry->dispatchInProgress); // should already have been set to true
1966
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001967 pokeUserActivityLocked(*eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001968
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001969 for (const InputTarget& inputTarget : inputTargets) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07001970 std::shared_ptr<Connection> connection =
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07001971 getConnectionLocked(inputTarget.inputChannel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07001972 if (connection != nullptr) {
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08001973 prepareDispatchCycleLocked(currentTime, connection, eventEntry, inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001974 } else {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001975 if (DEBUG_FOCUS) {
1976 ALOGD("Dropping event delivery to target with channel '%s' because it "
1977 "is no longer registered with the input dispatcher.",
1978 inputTarget.inputChannel->getName().c_str());
1979 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001980 }
1981 }
1982}
1983
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07001984void InputDispatcher::cancelEventsForAnrLocked(const std::shared_ptr<Connection>& connection) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001985 // We will not be breaking any connections here, even if the policy wants us to abort dispatch.
1986 // If the policy decides to close the app, we will get a channel removal event via
1987 // unregisterInputChannel, and will clean up the connection that way. We are already not
1988 // sending new pointers to the connection when it blocked, but focused events will continue to
1989 // pile up.
1990 ALOGW("Canceling events for %s because it is unresponsive",
1991 connection->inputChannel->getName().c_str());
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08001992 if (connection->status == Connection::Status::NORMAL) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001993 CancelationOptions options(CancelationOptions::Mode::CANCEL_ALL_EVENTS,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001994 "application not responding");
1995 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001996 }
1997}
1998
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001999void InputDispatcher::resetNoFocusedWindowTimeoutLocked() {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002000 if (DEBUG_FOCUS) {
2001 ALOGD("Resetting ANR timeouts.");
2002 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002003
2004 // Reset input target wait timeout.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002005 mNoFocusedWindowTimeoutTime = std::nullopt;
Chris Yea209fde2020-07-22 13:54:51 -07002006 mAwaitedFocusedApplication.reset();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002007}
2008
Tiger Huang721e26f2018-07-24 22:26:19 +08002009/**
2010 * Get the display id that the given event should go to. If this event specifies a valid display id,
2011 * then it should be dispatched to that display. Otherwise, the event goes to the focused display.
2012 * Focused display is the display that the user most recently interacted with.
2013 */
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002014int32_t InputDispatcher::getTargetDisplayId(const EventEntry& entry) {
Tiger Huang721e26f2018-07-24 22:26:19 +08002015 int32_t displayId;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002016 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002017 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002018 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
2019 displayId = keyEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002020 break;
2021 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002022 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002023 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
2024 displayId = motionEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002025 break;
2026 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00002027 case EventEntry::Type::TOUCH_MODE_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08002028 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002029 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002030 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07002031 case EventEntry::Type::DEVICE_RESET:
arthurhungb89ccb02020-12-30 16:19:01 +08002032 case EventEntry::Type::SENSOR:
2033 case EventEntry::Type::DRAG: {
Dominik Laskowski75788452021-02-09 18:51:25 -08002034 ALOGE("%s events do not have a target display", ftl::enum_string(entry.type).c_str());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002035 return ADISPLAY_ID_NONE;
2036 }
Tiger Huang721e26f2018-07-24 22:26:19 +08002037 }
2038 return displayId == ADISPLAY_ID_NONE ? mFocusedDisplayId : displayId;
2039}
2040
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002041bool InputDispatcher::shouldWaitToSendKeyLocked(nsecs_t currentTime,
2042 const char* focusedWindowName) {
2043 if (mAnrTracker.empty()) {
2044 // already processed all events that we waited for
2045 mKeyIsWaitingForEventsTimeout = std::nullopt;
2046 return false;
2047 }
2048
2049 if (!mKeyIsWaitingForEventsTimeout.has_value()) {
2050 // Start the timer
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00002051 // Wait to send key because there are unprocessed events that may cause focus to change
Siarhei Vishniakou70622952020-07-30 11:17:23 -05002052 mKeyIsWaitingForEventsTimeout = currentTime +
2053 std::chrono::duration_cast<std::chrono::nanoseconds>(KEY_WAITING_FOR_EVENTS_TIMEOUT)
2054 .count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002055 return true;
2056 }
2057
2058 // We still have pending events, and already started the timer
2059 if (currentTime < *mKeyIsWaitingForEventsTimeout) {
2060 return true; // Still waiting
2061 }
2062
2063 // Waited too long, and some connection still hasn't processed all motions
2064 // Just send the key to the focused window
2065 ALOGW("Dispatching key to %s even though there are other unprocessed events",
2066 focusedWindowName);
2067 mKeyIsWaitingForEventsTimeout = std::nullopt;
2068 return false;
2069}
2070
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002071sp<WindowInfoHandle> InputDispatcher::findFocusedWindowTargetLocked(
2072 nsecs_t currentTime, const EventEntry& entry, nsecs_t* nextWakeupTime,
2073 InputEventInjectionResult& outInjectionResult) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002074 std::string reason;
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002075 outInjectionResult = InputEventInjectionResult::FAILED; // Default result
Michael Wrightd02c5b62014-02-10 15:10:22 -08002076
Tiger Huang721e26f2018-07-24 22:26:19 +08002077 int32_t displayId = getTargetDisplayId(entry);
chaviw98318de2021-05-19 16:45:23 -05002078 sp<WindowInfoHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Chris Yea209fde2020-07-22 13:54:51 -07002079 std::shared_ptr<InputApplicationHandle> focusedApplicationHandle =
Tiger Huang721e26f2018-07-24 22:26:19 +08002080 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
2081
Michael Wrightd02c5b62014-02-10 15:10:22 -08002082 // If there is no currently focused window and no focused application
2083 // then drop the event.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002084 if (focusedWindowHandle == nullptr && focusedApplicationHandle == nullptr) {
2085 ALOGI("Dropping %s event because there is no focused window or focused application in "
2086 "display %" PRId32 ".",
Dominik Laskowski75788452021-02-09 18:51:25 -08002087 ftl::enum_string(entry.type).c_str(), displayId);
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002088 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002089 }
2090
Vishnu Nair062a8672021-09-03 16:07:44 -07002091 // Drop key events if requested by input feature
2092 if (focusedWindowHandle != nullptr && shouldDropInput(entry, focusedWindowHandle)) {
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002093 return nullptr;
Vishnu Nair062a8672021-09-03 16:07:44 -07002094 }
2095
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002096 // Compatibility behavior: raise ANR if there is a focused application, but no focused window.
2097 // Only start counting when we have a focused event to dispatch. The ANR is canceled if we
2098 // start interacting with another application via touch (app switch). This code can be removed
2099 // if the "no focused window ANR" is moved to the policy. Input doesn't know whether
2100 // an app is expected to have a focused window.
2101 if (focusedWindowHandle == nullptr && focusedApplicationHandle != nullptr) {
2102 if (!mNoFocusedWindowTimeoutTime.has_value()) {
2103 // We just discovered that there's no focused window. Start the ANR timer
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05002104 std::chrono::nanoseconds timeout = focusedApplicationHandle->getDispatchingTimeout(
2105 DEFAULT_INPUT_DISPATCHING_TIMEOUT);
2106 mNoFocusedWindowTimeoutTime = currentTime + timeout.count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002107 mAwaitedFocusedApplication = focusedApplicationHandle;
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05002108 mAwaitedApplicationDisplayId = displayId;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002109 ALOGW("Waiting because no window has focus but %s may eventually add a "
2110 "window when it finishes starting up. Will wait for %" PRId64 "ms",
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05002111 mAwaitedFocusedApplication->getName().c_str(), millis(timeout));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002112 *nextWakeupTime = *mNoFocusedWindowTimeoutTime;
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002113 outInjectionResult = InputEventInjectionResult::PENDING;
2114 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002115 } else if (currentTime > *mNoFocusedWindowTimeoutTime) {
2116 // Already raised ANR. Drop the event
2117 ALOGE("Dropping %s event because there is no focused window",
Dominik Laskowski75788452021-02-09 18:51:25 -08002118 ftl::enum_string(entry.type).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002119 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002120 } else {
2121 // Still waiting for the focused window
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002122 outInjectionResult = InputEventInjectionResult::PENDING;
2123 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002124 }
2125 }
2126
2127 // we have a valid, non-null focused window
2128 resetNoFocusedWindowTimeoutLocked();
2129
Prabir Pradhan5735a322022-04-11 17:23:34 +00002130 // Verify targeted injection.
2131 if (const auto err = verifyTargetedInjection(focusedWindowHandle, entry); err) {
2132 ALOGW("Dropping injected event: %s", (*err).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002133 outInjectionResult = InputEventInjectionResult::TARGET_MISMATCH;
2134 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002135 }
2136
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002137 if (focusedWindowHandle->getInfo()->inputConfig.test(
2138 WindowInfo::InputConfig::PAUSE_DISPATCHING)) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002139 ALOGI("Waiting because %s is paused", focusedWindowHandle->getName().c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002140 outInjectionResult = InputEventInjectionResult::PENDING;
2141 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002142 }
2143
2144 // If the event is a key event, then we must wait for all previous events to
2145 // complete before delivering it because previous events may have the
2146 // side-effect of transferring focus to a different window and we want to
2147 // ensure that the following keys are sent to the new window.
2148 //
2149 // Suppose the user touches a button in a window then immediately presses "A".
2150 // If the button causes a pop-up window to appear then we want to ensure that
2151 // the "A" key is delivered to the new pop-up window. This is because users
2152 // often anticipate pending UI changes when typing on a keyboard.
2153 // To obtain this behavior, we must serialize key events with respect to all
2154 // prior input events.
2155 if (entry.type == EventEntry::Type::KEY) {
2156 if (shouldWaitToSendKeyLocked(currentTime, focusedWindowHandle->getName().c_str())) {
2157 *nextWakeupTime = *mKeyIsWaitingForEventsTimeout;
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002158 outInjectionResult = InputEventInjectionResult::PENDING;
2159 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002160 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002161 }
2162
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002163 outInjectionResult = InputEventInjectionResult::SUCCEEDED;
2164 return focusedWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002165}
2166
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002167/**
2168 * Given a list of monitors, remove the ones we cannot find a connection for, and the ones
2169 * that are currently unresponsive.
2170 */
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002171std::vector<Monitor> InputDispatcher::selectResponsiveMonitorsLocked(
2172 const std::vector<Monitor>& monitors) const {
2173 std::vector<Monitor> responsiveMonitors;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002174 std::copy_if(monitors.begin(), monitors.end(), std::back_inserter(responsiveMonitors),
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002175 [this](const Monitor& monitor) REQUIRES(mLock) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07002176 std::shared_ptr<Connection> connection =
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002177 getConnectionLocked(monitor.inputChannel->getConnectionToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002178 if (connection == nullptr) {
2179 ALOGE("Could not find connection for monitor %s",
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002180 monitor.inputChannel->getName().c_str());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002181 return false;
2182 }
2183 if (!connection->responsive) {
2184 ALOGW("Unresponsive monitor %s will not get the new gesture",
2185 connection->inputChannel->getName().c_str());
2186 return false;
2187 }
2188 return true;
2189 });
2190 return responsiveMonitors;
2191}
2192
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07002193/**
2194 * In general, touch should be always split between windows. Some exceptions:
2195 * 1. Don't split touch is if we have an active pointer down, and a new pointer is going down that's
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002196 * from the same device, *and* the window that's receiving the current pointer does not support
2197 * split touch.
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07002198 * 2. Don't split mouse events
2199 */
2200bool InputDispatcher::shouldSplitTouch(const TouchState& touchState,
2201 const MotionEntry& entry) const {
2202 if (isFromSource(entry.source, AINPUT_SOURCE_MOUSE)) {
2203 // We should never split mouse events
2204 return false;
2205 }
2206 for (const TouchedWindow& touchedWindow : touchState.windows) {
2207 if (touchedWindow.windowHandle->getInfo()->isSpy()) {
2208 // Spy windows should not affect whether or not touch is split.
2209 continue;
2210 }
2211 if (touchedWindow.windowHandle->getInfo()->supportsSplitTouch()) {
2212 continue;
2213 }
Arthur Hungc539dbb2022-12-08 07:45:36 +00002214 if (touchedWindow.windowHandle->getInfo()->inputConfig.test(
2215 gui::WindowInfo::InputConfig::IS_WALLPAPER)) {
2216 // Wallpaper window should not affect whether or not touch is split
2217 continue;
2218 }
2219
Siarhei Vishniakou45504fe2023-05-05 16:05:10 -07002220 if (touchedWindow.hasTouchingPointers(entry.deviceId)) {
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07002221 return false;
2222 }
2223 }
2224 return true;
2225}
2226
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002227std::vector<InputTarget> InputDispatcher::findTouchedWindowTargetsLocked(
Siarhei Vishniakou4fe57392022-10-25 13:44:30 -07002228 nsecs_t currentTime, const MotionEntry& entry, bool* outConflictingPointerActions,
2229 InputEventInjectionResult& outInjectionResult) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002230 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002231
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002232 std::vector<InputTarget> targets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002233 // For security reasons, we defer updating the touch state until we are sure that
2234 // event injection will be allowed.
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002235 const int32_t displayId = entry.displayId;
2236 const int32_t action = entry.action;
Siarhei Vishniakoubf880522023-05-01 11:03:22 -07002237 const int32_t maskedAction = MotionEvent::getActionMasked(action);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002238
2239 // Update the touch state as needed based on the properties of the touch event.
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002240 outInjectionResult = InputEventInjectionResult::PENDING;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002241
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002242 // Copy current touch state into tempTouchState.
2243 // This state will be used to update mTouchStatesByDisplay at the end of this function.
2244 // If no state for the specified display exists, then our initial state will be empty.
Yi Kong9b14ac62018-07-17 13:48:38 -07002245 const TouchState* oldState = nullptr;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002246 TouchState tempTouchState;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002247 if (const auto it = mTouchStatesByDisplay.find(displayId); it != mTouchStatesByDisplay.end()) {
2248 oldState = &(it->second);
Prabir Pradhane680f9b2022-02-04 04:24:00 -08002249 tempTouchState = *oldState;
Jeff Brownf086ddb2014-02-11 14:28:48 -08002250 }
2251
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07002252 bool isSplit = shouldSplitTouch(tempTouchState, entry);
Siarhei Vishniakou45504fe2023-05-05 16:05:10 -07002253 bool switchedDevice = false;
2254 if (oldState != nullptr) {
2255 std::set<int32_t> oldActiveDevices = oldState->getActiveDeviceIds();
2256 const bool anotherDeviceIsActive =
2257 oldActiveDevices.count(entry.deviceId) == 0 && !oldActiveDevices.empty();
2258 switchedDevice |= anotherDeviceIsActive;
Siarhei Vishniakou45504fe2023-05-05 16:05:10 -07002259 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002260
2261 const bool isHoverAction = (maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE ||
2262 maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2263 maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT);
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002264 // A DOWN could be generated from POINTER_DOWN if the initial pointers did not land into any
2265 // touchable windows.
2266 const bool wasDown = oldState != nullptr && oldState->isDown();
2267 const bool isDown = (maskedAction == AMOTION_EVENT_ACTION_DOWN) ||
2268 (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN && !wasDown);
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07002269 const bool newGesture = isDown || maskedAction == AMOTION_EVENT_ACTION_SCROLL ||
2270 maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2271 maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE;
Prabir Pradhanaa561d12021-09-24 06:57:33 -07002272 const bool isFromMouse = isFromSource(entry.source, AINPUT_SOURCE_MOUSE);
Siarhei Vishniakou5cee1e32022-11-29 12:35:39 -08002273
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002274 // If pointers are already down, let's finish the current gesture and ignore the new events
2275 // from another device. However, if the new event is a down event, let's cancel the current
2276 // touch and let the new one take over.
2277 if (switchedDevice && wasDown && !isDown) {
Siarhei Vishniakou45504fe2023-05-05 16:05:10 -07002278 LOG(INFO) << "Dropping event because a pointer for another device "
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002279 << " is already down in display " << displayId << ": " << entry.getDescription();
2280 // TODO(b/211379801): test multiple simultaneous input streams.
2281 outInjectionResult = InputEventInjectionResult::FAILED;
2282 return {}; // wrong device
2283 }
2284
Michael Wrightd02c5b62014-02-10 15:10:22 -08002285 if (newGesture) {
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002286 // If a new gesture is starting, clear the touch state completely.
2287 tempTouchState.reset();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002288 isSplit = false;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04002289 } else if (switchedDevice && maskedAction == AMOTION_EVENT_ACTION_MOVE) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07002290 ALOGI("Dropping move event because a pointer for a different device is already active "
2291 "in display %" PRId32,
2292 displayId);
Siarhei Vishniakou16e4fa02023-02-16 17:48:56 -08002293 // TODO(b/211379801): test multiple simultaneous input streams.
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002294 outInjectionResult = InputEventInjectionResult::FAILED;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002295 return {}; // wrong device
Michael Wrightd02c5b62014-02-10 15:10:22 -08002296 }
2297
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002298 if (isHoverAction) {
2299 // For hover actions, we will treat 'tempTouchState' as a new state, so let's erase
2300 // all of the existing hovering pointers and recompute.
2301 tempTouchState.clearHoveringPointers();
2302 }
2303
Michael Wrightd02c5b62014-02-10 15:10:22 -08002304 if (newGesture || (isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN)) {
2305 /* Case 1: New splittable pointer going down, or need target for hover or scroll. */
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07002306 const auto [x, y] = resolveTouchedPosition(entry);
Siarhei Vishniakou5b9766d2023-07-18 14:06:29 -07002307 const int32_t pointerIndex = MotionEvent::getActionIndex(action);
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002308 // Outside targets should be added upon first dispatched DOWN event. That means, this should
2309 // be a pointer that would generate ACTION_DOWN, *and* touch should not already be down.
Prabir Pradhand65552b2021-10-07 11:23:50 -07002310 const bool isStylus = isPointerFromStylus(entry, pointerIndex);
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002311 auto [newTouchedWindowHandle, outsideTargets] =
2312 findTouchedWindowAtLocked(displayId, x, y, isStylus);
Michael Wright3dd60e22019-03-27 22:06:44 +00002313
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002314 if (isDown) {
2315 targets += outsideTargets;
2316 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002317 // Handle the case where we did not find a window.
Yi Kong9b14ac62018-07-17 13:48:38 -07002318 if (newTouchedWindowHandle == nullptr) {
Prabir Pradhan82e081e2022-12-06 09:50:09 +00002319 ALOGD("No new touched window at (%.1f, %.1f) in display %" PRId32, x, y, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002320 // Try to assign the pointer to the first foreground window we find, if there is one.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002321 newTouchedWindowHandle = tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002322 }
2323
Prabir Pradhan5735a322022-04-11 17:23:34 +00002324 // Verify targeted injection.
2325 if (const auto err = verifyTargetedInjection(newTouchedWindowHandle, entry); err) {
2326 ALOGW("Dropping injected touch event: %s", (*err).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002327 outInjectionResult = os::InputEventInjectionResult::TARGET_MISMATCH;
Prabir Pradhan5735a322022-04-11 17:23:34 +00002328 newTouchedWindowHandle = nullptr;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002329 return {};
Prabir Pradhan5735a322022-04-11 17:23:34 +00002330 }
2331
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002332 // Figure out whether splitting will be allowed for this window.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002333 if (newTouchedWindowHandle != nullptr) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002334 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
2335 // New window supports splitting, but we should never split mouse events.
2336 isSplit = !isFromMouse;
2337 } else if (isSplit) {
2338 // New window does not support splitting but we have already split events.
2339 // Ignore the new window.
Siarhei Vishniakou25537f82023-07-18 14:35:47 -07002340 LOG(INFO) << "Skipping " << newTouchedWindowHandle->getName()
2341 << " because it doesn't support split touch";
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002342 newTouchedWindowHandle = nullptr;
2343 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002344 } else {
2345 // No window is touched, so set split to true. This will allow the next pointer down to
Prabir Pradhan713bb3e2021-12-20 02:07:40 -08002346 // be delivered to a new window which supports split touch. Pointers from a mouse device
2347 // should never be split.
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07002348 isSplit = !isFromMouse;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002349 }
2350
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002351 std::vector<sp<WindowInfoHandle>> newTouchedWindows =
Prabir Pradhand65552b2021-10-07 11:23:50 -07002352 findTouchedSpyWindowsAtLocked(displayId, x, y, isStylus);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002353 if (newTouchedWindowHandle != nullptr) {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002354 // Process the foreground window first so that it is the first to receive the event.
2355 newTouchedWindows.insert(newTouchedWindows.begin(), newTouchedWindowHandle);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002356 }
2357
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002358 if (newTouchedWindows.empty()) {
Prabir Pradhan82e081e2022-12-06 09:50:09 +00002359 ALOGI("Dropping event because there is no touchable window at (%.1f, %.1f) on display "
2360 "%d.",
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002361 x, y, displayId);
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002362 outInjectionResult = InputEventInjectionResult::FAILED;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002363 return {};
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002364 }
2365
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002366 for (const sp<WindowInfoHandle>& windowHandle : newTouchedWindows) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07002367 if (!canWindowReceiveMotionLocked(windowHandle, entry)) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002368 continue;
2369 }
2370
Siarhei Vishniakoub681c202023-05-01 11:22:33 -07002371 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2372 maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE) {
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002373 const int32_t pointerId = entry.pointerProperties[0].id;
Siarhei Vishniakoub681c202023-05-01 11:22:33 -07002374 // The "windowHandle" is the target of this hovering pointer.
2375 tempTouchState.addHoveringPointerToWindow(windowHandle, entry.deviceId, pointerId);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002376 }
2377
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002378 // Set target flags.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002379 ftl::Flags<InputTarget::Flags> targetFlags = InputTarget::Flags::DISPATCH_AS_IS;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002380
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002381 if (canReceiveForegroundTouches(*windowHandle->getInfo())) {
2382 // There should only be one touched window that can be "foreground" for the pointer.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002383 targetFlags |= InputTarget::Flags::FOREGROUND;
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002384 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002385
2386 if (isSplit) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002387 targetFlags |= InputTarget::Flags::SPLIT;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002388 }
2389 if (isWindowObscuredAtPointLocked(windowHandle, x, y)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002390 targetFlags |= InputTarget::Flags::WINDOW_IS_OBSCURED;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002391 } else if (isWindowObscuredLocked(windowHandle)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002392 targetFlags |= InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002393 }
Michael Wright3dd60e22019-03-27 22:06:44 +00002394
2395 // Update the temporary touch state.
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08002396 std::bitset<MAX_POINTER_ID + 1> pointerIds;
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002397 if (!isHoverAction) {
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08002398 pointerIds.set(entry.pointerProperties[pointerIndex].id);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002399 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002400
Siarhei Vishniakoue0431e42023-01-28 17:01:39 -08002401 const bool isDownOrPointerDown = maskedAction == AMOTION_EVENT_ACTION_DOWN ||
2402 maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN;
2403
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002404 // TODO(b/211379801): Currently, even if pointerIds are empty (hover case), we would
2405 // still add a window to the touch state. We should avoid doing that, but some of the
2406 // later checks ("at least one foreground window") rely on this in order to dispatch
2407 // the event properly, so that needs to be updated, possibly by looking at InputTargets.
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002408 tempTouchState.addOrUpdateWindow(windowHandle, targetFlags, entry.deviceId, pointerIds,
Siarhei Vishniakoue0431e42023-01-28 17:01:39 -08002409 isDownOrPointerDown
2410 ? std::make_optional(entry.eventTime)
2411 : std::nullopt);
Arthur Hungc539dbb2022-12-08 07:45:36 +00002412
2413 // If this is the pointer going down and the touched window has a wallpaper
2414 // then also add the touched wallpaper windows so they are locked in for the duration
2415 // of the touch gesture.
2416 // We do not collect wallpapers during HOVER_MOVE or SCROLL because the wallpaper
2417 // engine only supports touch events. We would need to add a mechanism similar
2418 // to View.onGenericMotionEvent to enable wallpapers to handle these events.
Siarhei Vishniakoue0431e42023-01-28 17:01:39 -08002419 if (isDownOrPointerDown) {
Arthur Hungc539dbb2022-12-08 07:45:36 +00002420 if (targetFlags.test(InputTarget::Flags::FOREGROUND) &&
2421 windowHandle->getInfo()->inputConfig.test(
2422 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER)) {
2423 sp<WindowInfoHandle> wallpaper = findWallpaperWindowBelow(windowHandle);
2424 if (wallpaper != nullptr) {
2425 ftl::Flags<InputTarget::Flags> wallpaperFlags =
2426 InputTarget::Flags::WINDOW_IS_OBSCURED |
2427 InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED |
2428 InputTarget::Flags::DISPATCH_AS_IS;
2429 if (isSplit) {
2430 wallpaperFlags |= InputTarget::Flags::SPLIT;
2431 }
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002432 tempTouchState.addOrUpdateWindow(wallpaper, wallpaperFlags, entry.deviceId,
2433 pointerIds, entry.eventTime);
Arthur Hungc539dbb2022-12-08 07:45:36 +00002434 }
2435 }
2436 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002437 }
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00002438
Siarhei Vishniakou060f82b2023-01-27 06:39:14 -08002439 // If a window is already pilfering some pointers, give it this new pointer as well and
2440 // make it pilfering. This will prevent other non-spy windows from getting this pointer,
2441 // which is a specific behaviour that we want.
2442 const int32_t pointerId = entry.pointerProperties[pointerIndex].id;
2443 for (TouchedWindow& touchedWindow : tempTouchState.windows) {
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002444 if (touchedWindow.hasTouchingPointer(entry.deviceId, pointerId) &&
2445 touchedWindow.hasPilferingPointers(entry.deviceId)) {
Siarhei Vishniakou060f82b2023-01-27 06:39:14 -08002446 // This window is already pilfering some pointers, and this new pointer is also
2447 // going to it. Therefore, take over this pointer and don't give it to anyone
2448 // else.
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002449 touchedWindow.addPilferingPointer(entry.deviceId, pointerId);
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00002450 }
2451 }
Siarhei Vishniakou060f82b2023-01-27 06:39:14 -08002452
2453 // Restrict all pilfered pointers to the pilfering windows.
2454 tempTouchState.cancelPointersForNonPilferingWindows();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002455 } else {
2456 /* Case 2: Pointer move, up, cancel or non-splittable pointer down. */
2457
2458 // If the pointer is not currently down, then ignore the event.
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07002459 if (!tempTouchState.isDown() && maskedAction != AMOTION_EVENT_ACTION_HOVER_EXIT) {
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002460 LOG(INFO) << "Dropping event because the pointer is not down or we previously "
2461 "dropped the pointer down event in display "
2462 << displayId << ": " << entry.getDescription();
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002463 outInjectionResult = InputEventInjectionResult::FAILED;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002464 return {};
Michael Wrightd02c5b62014-02-10 15:10:22 -08002465 }
2466
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07002467 // If the pointer is not currently hovering, then ignore the event.
2468 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT) {
2469 const int32_t pointerId = entry.pointerProperties[0].id;
2470 if (oldState == nullptr ||
2471 oldState->getWindowsWithHoveringPointer(entry.deviceId, pointerId).empty()) {
2472 LOG(INFO) << "Dropping event because the hovering pointer is not in any windows in "
2473 "display "
2474 << displayId << ": " << entry.getDescription();
2475 outInjectionResult = InputEventInjectionResult::FAILED;
2476 return {};
2477 }
2478 tempTouchState.removeHoveringPointer(entry.deviceId, pointerId);
2479 }
2480
arthurhung6d4bed92021-03-17 11:59:33 +08002481 addDragEventLocked(entry);
arthurhungb89ccb02020-12-30 16:19:01 +08002482
Michael Wrightd02c5b62014-02-10 15:10:22 -08002483 // Check whether touches should slip outside of the current foreground window.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002484 if (maskedAction == AMOTION_EVENT_ACTION_MOVE && entry.pointerCount == 1 &&
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002485 tempTouchState.isSlippery()) {
Siarhei Vishniakou9306c382022-09-30 15:30:31 -07002486 const auto [x, y] = resolveTouchedPosition(entry);
Harry Cutts33476232023-01-30 19:57:29 +00002487 const bool isStylus = isPointerFromStylus(entry, /*pointerIndex=*/0);
chaviw98318de2021-05-19 16:45:23 -05002488 sp<WindowInfoHandle> oldTouchedWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002489 tempTouchState.getFirstForegroundWindowHandle();
Siarhei Vishniakou0f6558d2023-04-21 12:05:13 -07002490 LOG_ALWAYS_FATAL_IF(oldTouchedWindowHandle == nullptr);
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002491 auto [newTouchedWindowHandle, _] = findTouchedWindowAtLocked(displayId, x, y, isStylus);
Vishnu Nair062a8672021-09-03 16:07:44 -07002492
Prabir Pradhan5735a322022-04-11 17:23:34 +00002493 // Verify targeted injection.
2494 if (const auto err = verifyTargetedInjection(newTouchedWindowHandle, entry); err) {
2495 ALOGW("Dropping injected event: %s", (*err).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002496 outInjectionResult = os::InputEventInjectionResult::TARGET_MISMATCH;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002497 return {};
Prabir Pradhan5735a322022-04-11 17:23:34 +00002498 }
2499
Vishnu Nair062a8672021-09-03 16:07:44 -07002500 // Drop touch events if requested by input feature
2501 if (newTouchedWindowHandle != nullptr &&
2502 shouldDropInput(entry, newTouchedWindowHandle)) {
2503 newTouchedWindowHandle = nullptr;
2504 }
2505
Siarhei Vishniakouafa08cc2023-05-08 22:35:50 -07002506 if (newTouchedWindowHandle != nullptr &&
2507 !haveSameToken(oldTouchedWindowHandle, newTouchedWindowHandle)) {
Siarhei Vishniakou0f6558d2023-04-21 12:05:13 -07002508 ALOGD("Touch is slipping out of window %s into window %s in display %" PRId32,
2509 oldTouchedWindowHandle->getName().c_str(),
2510 newTouchedWindowHandle->getName().c_str(), displayId);
2511
Michael Wrightd02c5b62014-02-10 15:10:22 -08002512 // Make a slippery exit from the old window.
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08002513 std::bitset<MAX_POINTER_ID + 1> pointerIds;
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002514 const int32_t pointerId = entry.pointerProperties[0].id;
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08002515 pointerIds.set(pointerId);
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002516
2517 const TouchedWindow& touchedWindow =
2518 tempTouchState.getTouchedWindow(oldTouchedWindowHandle);
2519 addWindowTargetLocked(oldTouchedWindowHandle,
2520 InputTarget::Flags::DISPATCH_AS_SLIPPERY_EXIT, pointerIds,
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002521 touchedWindow.getDownTimeInTarget(entry.deviceId), targets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002522
2523 // Make a slippery entrance into the new window.
2524 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
Prabir Pradhan713bb3e2021-12-20 02:07:40 -08002525 isSplit = !isFromMouse;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002526 }
2527
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002528 ftl::Flags<InputTarget::Flags> targetFlags =
2529 InputTarget::Flags::DISPATCH_AS_SLIPPERY_ENTER;
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002530 if (canReceiveForegroundTouches(*newTouchedWindowHandle->getInfo())) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002531 targetFlags |= InputTarget::Flags::FOREGROUND;
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002532 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002533 if (isSplit) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002534 targetFlags |= InputTarget::Flags::SPLIT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002535 }
2536 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002537 targetFlags |= InputTarget::Flags::WINDOW_IS_OBSCURED;
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002538 } else if (isWindowObscuredLocked(newTouchedWindowHandle)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002539 targetFlags |= InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002540 }
2541
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002542 tempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags,
2543 entry.deviceId, pointerIds, entry.eventTime);
Arthur Hungc539dbb2022-12-08 07:45:36 +00002544
2545 // Check if the wallpaper window should deliver the corresponding event.
2546 slipWallpaperTouch(targetFlags, oldTouchedWindowHandle, newTouchedWindowHandle,
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002547 tempTouchState, entry.deviceId, pointerId, targets);
2548 tempTouchState.removeTouchingPointerFromWindow(entry.deviceId, pointerId,
2549 oldTouchedWindowHandle);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002550 }
2551 }
Arthur Hung96483742022-11-15 03:30:48 +00002552
2553 // Update the pointerIds for non-splittable when it received pointer down.
2554 if (!isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN) {
2555 // If no split, we suppose all touched windows should receive pointer down.
Siarhei Vishniakou5b9766d2023-07-18 14:06:29 -07002556 const int32_t pointerIndex = MotionEvent::getActionIndex(action);
Arthur Hung96483742022-11-15 03:30:48 +00002557 for (size_t i = 0; i < tempTouchState.windows.size(); i++) {
2558 TouchedWindow& touchedWindow = tempTouchState.windows[i];
2559 // Ignore drag window for it should just track one pointer.
2560 if (mDragState && mDragState->dragWindow == touchedWindow.windowHandle) {
2561 continue;
2562 }
Siarhei Vishniakou5b9766d2023-07-18 14:06:29 -07002563 std::bitset<MAX_POINTER_ID + 1> touchingPointers;
2564 touchingPointers.set(entry.pointerProperties[pointerIndex].id);
2565 touchedWindow.addTouchingPointers(entry.deviceId, touchingPointers);
Arthur Hung96483742022-11-15 03:30:48 +00002566 }
2567 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002568 }
2569
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002570 // Update dispatching for hover enter and exit.
Sam Dubeyf886dec2023-01-27 13:28:19 +00002571 {
2572 std::vector<TouchedWindow> hoveringWindows =
2573 getHoveringWindowsLocked(oldState, tempTouchState, entry);
2574 for (const TouchedWindow& touchedWindow : hoveringWindows) {
Siarhei Vishniakoud5876ba2023-05-15 17:58:34 -07002575 std::optional<InputTarget> target =
2576 createInputTargetLocked(touchedWindow.windowHandle, touchedWindow.targetFlags,
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002577 touchedWindow.getDownTimeInTarget(entry.deviceId));
Siarhei Vishniakoud5876ba2023-05-15 17:58:34 -07002578 if (!target) {
2579 continue;
2580 }
2581 // Hardcode to single hovering pointer for now.
2582 std::bitset<MAX_POINTER_ID + 1> pointerIds;
2583 pointerIds.set(entry.pointerProperties[0].id);
2584 target->addPointers(pointerIds, touchedWindow.windowHandle->getInfo()->transform);
2585 targets.push_back(*target);
Sam Dubeyf886dec2023-01-27 13:28:19 +00002586 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002587 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002588
Prabir Pradhan5735a322022-04-11 17:23:34 +00002589 // Ensure that all touched windows are valid for injection.
2590 if (entry.injectionState != nullptr) {
2591 std::string errs;
2592 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Prabir Pradhan5735a322022-04-11 17:23:34 +00002593 const auto err = verifyTargetedInjection(touchedWindow.windowHandle, entry);
2594 if (err) errs += "\n - " + *err;
2595 }
2596 if (!errs.empty()) {
2597 ALOGW("Dropping targeted injection: At least one touched window is not owned by uid "
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00002598 "%s:%s",
2599 entry.injectionState->targetUid->toString().c_str(), errs.c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002600 outInjectionResult = InputEventInjectionResult::TARGET_MISMATCH;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002601 return {};
Prabir Pradhan5735a322022-04-11 17:23:34 +00002602 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002603 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002604
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002605 // Check whether windows listening for outside touches are owned by the same UID. If the owner
2606 // has a different UID, then we will not reveal coordinate information to this window.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002607 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
chaviw98318de2021-05-19 16:45:23 -05002608 sp<WindowInfoHandle> foregroundWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002609 tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002610 if (foregroundWindowHandle) {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00002611 const auto foregroundWindowUid = foregroundWindowHandle->getInfo()->ownerUid;
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002612 for (InputTarget& target : targets) {
2613 if (target.flags.test(InputTarget::Flags::DISPATCH_AS_OUTSIDE)) {
2614 sp<WindowInfoHandle> targetWindow =
2615 getWindowHandleLocked(target.inputChannel->getConnectionToken());
2616 if (targetWindow->getInfo()->ownerUid != foregroundWindowUid) {
2617 target.flags |= InputTarget::Flags::ZERO_COORDS;
Michael Wright3dd60e22019-03-27 22:06:44 +00002618 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002619 }
2620 }
2621 }
2622 }
2623
Harry Cuttsb166c002023-05-09 13:06:05 +00002624 // If this is a touchpad navigation gesture, it needs to only be sent to trusted targets, as we
2625 // only want the system UI to handle these gestures.
2626 const bool isTouchpadNavGesture = isFromSource(entry.source, AINPUT_SOURCE_MOUSE) &&
2627 entry.classification == MotionClassification::MULTI_FINGER_SWIPE;
2628 if (isTouchpadNavGesture) {
2629 filterUntrustedTargets(/* byref */ tempTouchState, /* byref */ targets);
2630 }
2631
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07002632 // Output targets from the touch state.
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002633 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002634 if (!touchedWindow.hasTouchingPointers(entry.deviceId) &&
2635 !touchedWindow.hasHoveringPointers(entry.deviceId)) {
Siarhei Vishniakoue0431e42023-01-28 17:01:39 -08002636 // Windows with hovering pointers are getting persisted inside TouchState.
2637 // Do not send this event to those windows.
2638 continue;
2639 }
Harry Cuttsb166c002023-05-09 13:06:05 +00002640
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002641 addWindowTargetLocked(touchedWindow.windowHandle, touchedWindow.targetFlags,
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002642 touchedWindow.getTouchingPointers(entry.deviceId),
2643 touchedWindow.getDownTimeInTarget(entry.deviceId), targets);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002644 }
Sam Dubey39d37cf2022-12-07 18:05:35 +00002645
Siarhei Vishniakou580fb3a2023-05-05 15:02:20 -07002646 // During targeted injection, only allow owned targets to receive events
2647 std::erase_if(targets, [&](const InputTarget& target) {
2648 LOG_ALWAYS_FATAL_IF(target.windowHandle == nullptr);
2649 const auto err = verifyTargetedInjection(target.windowHandle, entry);
2650 if (err) {
2651 LOG(WARNING) << "Dropping injected event from " << target.windowHandle->getName()
2652 << ": " << (*err);
2653 return true;
2654 }
2655 return false;
2656 });
2657
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07002658 if (targets.empty()) {
2659 LOG(INFO) << "Dropping event because no targets were found: " << entry.getDescription();
2660 outInjectionResult = InputEventInjectionResult::FAILED;
2661 return {};
2662 }
2663
2664 // If we only have windows getting ACTION_OUTSIDE, then drop the event, because there is no
2665 // window that is actually receiving the entire gesture.
2666 if (std::all_of(targets.begin(), targets.end(), [](const InputTarget& target) {
2667 return target.flags.test(InputTarget::Flags::DISPATCH_AS_OUTSIDE);
2668 })) {
2669 LOG(INFO) << "Dropping event because all windows would just receive ACTION_OUTSIDE: "
2670 << entry.getDescription();
2671 outInjectionResult = InputEventInjectionResult::FAILED;
2672 return {};
2673 }
2674
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002675 outInjectionResult = InputEventInjectionResult::SUCCEEDED;
Sam Dubeyf886dec2023-01-27 13:28:19 +00002676 // Drop the outside or hover touch windows since we will not care about them
2677 // in the next iteration.
2678 tempTouchState.filterNonAsIsTouchWindows();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002679
Michael Wrightd02c5b62014-02-10 15:10:22 -08002680 // Update final pieces of touch state if the injector had permission.
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002681 if (switchedDevice) {
2682 if (DEBUG_FOCUS) {
2683 ALOGD("Conflicting pointer actions: Switched to a different device.");
2684 }
2685 *outConflictingPointerActions = true;
2686 }
2687
2688 if (isHoverAction) {
2689 // Started hovering, therefore no longer down.
Siarhei Vishniakou3ad385b2022-11-04 10:09:53 -07002690 if (oldState && oldState->isDown()) {
Siarhei Vishniakou6e1e9872022-11-08 17:51:35 -08002691 ALOGD_IF(DEBUG_FOCUS,
2692 "Conflicting pointer actions: Hover received while pointer was down.");
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002693 *outConflictingPointerActions = true;
2694 }
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002695 } else if (maskedAction == AMOTION_EVENT_ACTION_UP) {
2696 // Pointer went up.
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002697 tempTouchState.removeTouchingPointer(entry.deviceId, entry.pointerProperties[0].id);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002698 } else if (maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002699 // All pointers up or canceled.
2700 tempTouchState.reset();
2701 } else if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
2702 // First pointer went down.
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002703 if (oldState && (oldState->isDown() || oldState->hasHoveringPointers())) {
2704 ALOGD("Conflicting pointer actions: Down received while already down or hovering.");
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002705 *outConflictingPointerActions = true;
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002706 }
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002707 } else if (maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
2708 // One pointer went up.
Siarhei Vishniakou5b9766d2023-07-18 14:06:29 -07002709 const int32_t pointerIndex = MotionEvent::getActionIndex(action);
2710 const uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
2711 tempTouchState.removeTouchingPointer(entry.deviceId, pointerId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002712 }
2713
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002714 // Save changes unless the action was scroll in which case the temporary touch
2715 // state was only valid for this one action.
2716 if (maskedAction != AMOTION_EVENT_ACTION_SCROLL) {
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07002717 if (displayId >= 0) {
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002718 tempTouchState.clearWindowsWithoutPointers();
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002719 mTouchStatesByDisplay[displayId] = tempTouchState;
2720 } else {
2721 mTouchStatesByDisplay.erase(displayId);
2722 }
2723 }
2724
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -08002725 if (tempTouchState.windows.empty()) {
2726 mTouchStatesByDisplay.erase(displayId);
2727 }
2728
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002729 return targets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002730}
2731
arthurhung6d4bed92021-03-17 11:59:33 +08002732void InputDispatcher::finishDragAndDrop(int32_t displayId, float x, float y) {
Prabir Pradhand65552b2021-10-07 11:23:50 -07002733 // Prevent stylus interceptor windows from affecting drag and drop behavior for now, until we
2734 // have an explicit reason to support it.
2735 constexpr bool isStylus = false;
2736
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002737 auto [dropWindow, _] =
Harry Cutts33476232023-01-30 19:57:29 +00002738 findTouchedWindowAtLocked(displayId, x, y, isStylus, /*ignoreDragWindow=*/true);
arthurhung6d4bed92021-03-17 11:59:33 +08002739 if (dropWindow) {
2740 vec2 local = dropWindow->getInfo()->transform.transform(x, y);
Prabir Pradhancef936d2021-07-21 16:17:52 +00002741 sendDropWindowCommandLocked(dropWindow->getToken(), local.x, local.y);
Arthur Hung6d0571e2021-04-09 20:18:16 +08002742 } else {
Arthur Hung54745652022-04-20 07:17:41 +00002743 ALOGW("No window found when drop.");
Prabir Pradhancef936d2021-07-21 16:17:52 +00002744 sendDropWindowCommandLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08002745 }
2746 mDragState.reset();
2747}
2748
2749void InputDispatcher::addDragEventLocked(const MotionEntry& entry) {
Arthur Hung3915c1f2022-05-31 07:17:17 +00002750 if (!mDragState || mDragState->dragWindow->getInfo()->displayId != entry.displayId) {
arthurhungb89ccb02020-12-30 16:19:01 +08002751 return;
2752 }
2753
arthurhung6d4bed92021-03-17 11:59:33 +08002754 if (!mDragState->isStartDrag) {
2755 mDragState->isStartDrag = true;
2756 mDragState->isStylusButtonDownAtStart =
2757 (entry.buttonState & AMOTION_EVENT_BUTTON_STYLUS_PRIMARY) != 0;
2758 }
2759
Arthur Hung54745652022-04-20 07:17:41 +00002760 // Find the pointer index by id.
2761 int32_t pointerIndex = 0;
2762 for (; static_cast<uint32_t>(pointerIndex) < entry.pointerCount; pointerIndex++) {
2763 const PointerProperties& pointerProperties = entry.pointerProperties[pointerIndex];
2764 if (pointerProperties.id == mDragState->pointerId) {
2765 break;
arthurhung6d4bed92021-03-17 11:59:33 +08002766 }
Arthur Hung54745652022-04-20 07:17:41 +00002767 }
arthurhung6d4bed92021-03-17 11:59:33 +08002768
Arthur Hung54745652022-04-20 07:17:41 +00002769 if (uint32_t(pointerIndex) == entry.pointerCount) {
2770 LOG_ALWAYS_FATAL("Should find a valid pointer index by id %d", mDragState->pointerId);
Arthur Hung54745652022-04-20 07:17:41 +00002771 }
2772
2773 const int32_t maskedAction = entry.action & AMOTION_EVENT_ACTION_MASK;
2774 const int32_t x = entry.pointerCoords[pointerIndex].getX();
2775 const int32_t y = entry.pointerCoords[pointerIndex].getY();
2776
2777 switch (maskedAction) {
2778 case AMOTION_EVENT_ACTION_MOVE: {
2779 // Handle the special case : stylus button no longer pressed.
2780 bool isStylusButtonDown =
2781 (entry.buttonState & AMOTION_EVENT_BUTTON_STYLUS_PRIMARY) != 0;
2782 if (mDragState->isStylusButtonDownAtStart && !isStylusButtonDown) {
2783 finishDragAndDrop(entry.displayId, x, y);
2784 return;
2785 }
2786
2787 // Prevent stylus interceptor windows from affecting drag and drop behavior for now,
2788 // until we have an explicit reason to support it.
2789 constexpr bool isStylus = false;
2790
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002791 auto [hoverWindowHandle, _] = findTouchedWindowAtLocked(entry.displayId, x, y, isStylus,
Harry Cutts33476232023-01-30 19:57:29 +00002792 /*ignoreDragWindow=*/true);
Arthur Hung54745652022-04-20 07:17:41 +00002793 // enqueue drag exit if needed.
2794 if (hoverWindowHandle != mDragState->dragHoverWindowHandle &&
2795 !haveSameToken(hoverWindowHandle, mDragState->dragHoverWindowHandle)) {
2796 if (mDragState->dragHoverWindowHandle != nullptr) {
Harry Cutts33476232023-01-30 19:57:29 +00002797 enqueueDragEventLocked(mDragState->dragHoverWindowHandle, /*isExiting=*/true, x,
Arthur Hung54745652022-04-20 07:17:41 +00002798 y);
2799 }
2800 mDragState->dragHoverWindowHandle = hoverWindowHandle;
2801 }
2802 // enqueue drag location if needed.
2803 if (hoverWindowHandle != nullptr) {
Harry Cutts33476232023-01-30 19:57:29 +00002804 enqueueDragEventLocked(hoverWindowHandle, /*isExiting=*/false, x, y);
Arthur Hung54745652022-04-20 07:17:41 +00002805 }
2806 break;
2807 }
2808
2809 case AMOTION_EVENT_ACTION_POINTER_UP:
Siarhei Vishniakou5b9766d2023-07-18 14:06:29 -07002810 if (MotionEvent::getActionIndex(entry.action) != pointerIndex) {
Arthur Hung54745652022-04-20 07:17:41 +00002811 break;
2812 }
2813 // The drag pointer is up.
2814 [[fallthrough]];
2815 case AMOTION_EVENT_ACTION_UP:
2816 finishDragAndDrop(entry.displayId, x, y);
2817 break;
2818 case AMOTION_EVENT_ACTION_CANCEL: {
2819 ALOGD("Receiving cancel when drag and drop.");
2820 sendDropWindowCommandLocked(nullptr, 0, 0);
2821 mDragState.reset();
2822 break;
2823 }
arthurhungb89ccb02020-12-30 16:19:01 +08002824 }
2825}
2826
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002827std::optional<InputTarget> InputDispatcher::createInputTargetLocked(
2828 const sp<android::gui::WindowInfoHandle>& windowHandle,
2829 ftl::Flags<InputTarget::Flags> targetFlags,
2830 std::optional<nsecs_t> firstDownTimeInTarget) const {
2831 std::shared_ptr<InputChannel> inputChannel = getInputChannelLocked(windowHandle->getToken());
2832 if (inputChannel == nullptr) {
2833 ALOGW("Not creating InputTarget for %s, no input channel", windowHandle->getName().c_str());
2834 return {};
2835 }
2836 InputTarget inputTarget;
2837 inputTarget.inputChannel = inputChannel;
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00002838 inputTarget.windowHandle = windowHandle;
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002839 inputTarget.flags = targetFlags;
2840 inputTarget.globalScaleFactor = windowHandle->getInfo()->globalScaleFactor;
2841 inputTarget.firstDownTimeInTarget = firstDownTimeInTarget;
2842 const auto& displayInfoIt = mDisplayInfos.find(windowHandle->getInfo()->displayId);
2843 if (displayInfoIt != mDisplayInfos.end()) {
2844 inputTarget.displayTransform = displayInfoIt->second.transform;
2845 } else {
Siarhei Vishniakou580fb3a2023-05-05 15:02:20 -07002846 // DisplayInfo not found for this window on display windowHandle->getInfo()->displayId.
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002847 // TODO(b/198444055): Make this an error message after 'setInputWindows' API is removed.
2848 }
2849 return inputTarget;
2850}
2851
chaviw98318de2021-05-19 16:45:23 -05002852void InputDispatcher::addWindowTargetLocked(const sp<WindowInfoHandle>& windowHandle,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002853 ftl::Flags<InputTarget::Flags> targetFlags,
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08002854 std::bitset<MAX_POINTER_ID + 1> pointerIds,
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002855 std::optional<nsecs_t> firstDownTimeInTarget,
Siarhei Vishniakouf75cddb2022-10-25 10:42:16 -07002856 std::vector<InputTarget>& inputTargets) const {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002857 std::vector<InputTarget>::iterator it =
2858 std::find_if(inputTargets.begin(), inputTargets.end(),
2859 [&windowHandle](const InputTarget& inputTarget) {
2860 return inputTarget.inputChannel->getConnectionToken() ==
2861 windowHandle->getToken();
2862 });
Chavi Weingarten97b8eec2020-01-09 18:09:08 +00002863
chaviw98318de2021-05-19 16:45:23 -05002864 const WindowInfo* windowInfo = windowHandle->getInfo();
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002865
2866 if (it == inputTargets.end()) {
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002867 std::optional<InputTarget> target =
2868 createInputTargetLocked(windowHandle, targetFlags, firstDownTimeInTarget);
2869 if (!target) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002870 return;
2871 }
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002872 inputTargets.push_back(*target);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002873 it = inputTargets.end() - 1;
2874 }
2875
2876 ALOG_ASSERT(it->flags == targetFlags);
2877 ALOG_ASSERT(it->globalScaleFactor == windowInfo->globalScaleFactor);
2878
chaviw1ff3d1e2020-07-01 15:53:47 -07002879 it->addPointers(pointerIds, windowInfo->transform);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002880}
2881
Michael Wright3dd60e22019-03-27 22:06:44 +00002882void InputDispatcher::addGlobalMonitoringTargetsLocked(std::vector<InputTarget>& inputTargets,
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002883 int32_t displayId) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002884 auto monitorsIt = mGlobalMonitorsByDisplay.find(displayId);
2885 if (monitorsIt == mGlobalMonitorsByDisplay.end()) return;
Michael Wright3dd60e22019-03-27 22:06:44 +00002886
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002887 for (const Monitor& monitor : selectResponsiveMonitorsLocked(monitorsIt->second)) {
2888 InputTarget target;
2889 target.inputChannel = monitor.inputChannel;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002890 target.flags = InputTarget::Flags::DISPATCH_AS_IS;
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002891 // target.firstDownTimeInTarget is not set for global monitors. It is only required in split
2892 // touch and global monitoring works as intended even without setting firstDownTimeInTarget
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002893 if (const auto& it = mDisplayInfos.find(displayId); it != mDisplayInfos.end()) {
2894 target.displayTransform = it->second.transform;
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002895 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002896 target.setDefaultPointerTransform(target.displayTransform);
2897 inputTargets.push_back(target);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002898 }
2899}
2900
Robert Carrc9bf1d32020-04-13 17:21:08 -07002901/**
2902 * Indicate whether one window handle should be considered as obscuring
2903 * another window handle. We only check a few preconditions. Actually
2904 * checking the bounds is left to the caller.
2905 */
chaviw98318de2021-05-19 16:45:23 -05002906static bool canBeObscuredBy(const sp<WindowInfoHandle>& windowHandle,
2907 const sp<WindowInfoHandle>& otherHandle) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002908 // Compare by token so cloned layers aren't counted
2909 if (haveSameToken(windowHandle, otherHandle)) {
2910 return false;
2911 }
2912 auto info = windowHandle->getInfo();
2913 auto otherInfo = otherHandle->getInfo();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002914 if (otherInfo->inputConfig.test(WindowInfo::InputConfig::NOT_VISIBLE)) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002915 return false;
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002916 } else if (otherInfo->alpha == 0 &&
2917 otherInfo->inputConfig.test(WindowInfo::InputConfig::NOT_TOUCHABLE)) {
Bernardo Rufino653d2e02020-10-20 17:32:40 +00002918 // Those act as if they were invisible, so we don't need to flag them.
2919 // We do want to potentially flag touchable windows even if they have 0
2920 // opacity, since they can consume touches and alter the effects of the
2921 // user interaction (eg. apps that rely on
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002922 // Flags::WINDOW_IS_PARTIALLY_OBSCURED should still be told about those
Bernardo Rufino653d2e02020-10-20 17:32:40 +00002923 // windows), hence we also check for FLAG_NOT_TOUCHABLE.
2924 return false;
Bernardo Rufino8007daf2020-09-22 09:40:01 +00002925 } else if (info->ownerUid == otherInfo->ownerUid) {
2926 // If ownerUid is the same we don't generate occlusion events as there
2927 // is no security boundary within an uid.
Robert Carrc9bf1d32020-04-13 17:21:08 -07002928 return false;
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002929 } else if (otherInfo->inputConfig.test(gui::WindowInfo::InputConfig::TRUSTED_OVERLAY)) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002930 return false;
2931 } else if (otherInfo->displayId != info->displayId) {
2932 return false;
2933 }
2934 return true;
2935}
2936
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002937/**
2938 * Returns touch occlusion information in the form of TouchOcclusionInfo. To check if the touch is
2939 * untrusted, one should check:
2940 *
2941 * 1. If result.hasBlockingOcclusion is true.
2942 * If it's, it means the touch should be blocked due to a window with occlusion mode of
2943 * BLOCK_UNTRUSTED.
2944 *
2945 * 2. If result.obscuringOpacity > mMaximumObscuringOpacityForTouch.
2946 * If it is (and 1 is false), then the touch should be blocked because a stack of windows
2947 * (possibly only one) with occlusion mode of USE_OPACITY from one UID resulted in a composed
2948 * obscuring opacity above the threshold. Note that if there was no window of occlusion mode
2949 * USE_OPACITY, result.obscuringOpacity would've been 0 and since
2950 * mMaximumObscuringOpacityForTouch >= 0, the condition above would never be true.
2951 *
2952 * If neither of those is true, then it means the touch can be allowed.
2953 */
2954InputDispatcher::TouchOcclusionInfo InputDispatcher::computeTouchOcclusionInfoLocked(
chaviw98318de2021-05-19 16:45:23 -05002955 const sp<WindowInfoHandle>& windowHandle, int32_t x, int32_t y) const {
2956 const WindowInfo* windowInfo = windowHandle->getInfo();
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002957 int32_t displayId = windowInfo->displayId;
chaviw98318de2021-05-19 16:45:23 -05002958 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002959 TouchOcclusionInfo info;
2960 info.hasBlockingOcclusion = false;
2961 info.obscuringOpacity = 0;
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00002962 info.obscuringUid = gui::Uid::INVALID;
2963 std::map<gui::Uid, float> opacityByUid;
chaviw98318de2021-05-19 16:45:23 -05002964 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002965 if (windowHandle == otherHandle) {
2966 break; // All future windows are below us. Exit early.
2967 }
chaviw98318de2021-05-19 16:45:23 -05002968 const WindowInfo* otherInfo = otherHandle->getInfo();
Bernardo Rufino1ff9d592021-01-18 16:58:57 +00002969 if (canBeObscuredBy(windowHandle, otherHandle) && otherInfo->frameContainsPoint(x, y) &&
2970 !haveSameApplicationToken(windowInfo, otherInfo)) {
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002971 if (DEBUG_TOUCH_OCCLUSION) {
2972 info.debugInfo.push_back(
Harry Cutts101ee9b2023-07-06 18:04:14 +00002973 dumpWindowForTouchOcclusion(otherInfo, /*isTouchedWindow=*/false));
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002974 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002975 // canBeObscuredBy() has returned true above, which means this window is untrusted, so
2976 // we perform the checks below to see if the touch can be propagated or not based on the
2977 // window's touch occlusion mode
2978 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::BLOCK_UNTRUSTED) {
2979 info.hasBlockingOcclusion = true;
2980 info.obscuringUid = otherInfo->ownerUid;
2981 info.obscuringPackage = otherInfo->packageName;
2982 break;
2983 }
2984 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::USE_OPACITY) {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00002985 const auto uid = otherInfo->ownerUid;
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002986 float opacity =
2987 (opacityByUid.find(uid) == opacityByUid.end()) ? 0 : opacityByUid[uid];
2988 // Given windows A and B:
2989 // opacity(A, B) = 1 - [1 - opacity(A)] * [1 - opacity(B)]
2990 opacity = 1 - (1 - opacity) * (1 - otherInfo->alpha);
2991 opacityByUid[uid] = opacity;
2992 if (opacity > info.obscuringOpacity) {
2993 info.obscuringOpacity = opacity;
2994 info.obscuringUid = uid;
2995 info.obscuringPackage = otherInfo->packageName;
2996 }
2997 }
2998 }
2999 }
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00003000 if (DEBUG_TOUCH_OCCLUSION) {
Harry Cutts101ee9b2023-07-06 18:04:14 +00003001 info.debugInfo.push_back(dumpWindowForTouchOcclusion(windowInfo, /*isTouchedWindow=*/true));
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00003002 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003003 return info;
3004}
3005
chaviw98318de2021-05-19 16:45:23 -05003006std::string InputDispatcher::dumpWindowForTouchOcclusion(const WindowInfo* info,
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00003007 bool isTouchedWindow) const {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003008 return StringPrintf(INDENT2 "* %spackage=%s/%s, id=%" PRId32 ", mode=%s, alpha=%.2f, "
Prabir Pradhan51e7db02022-02-07 06:02:57 -08003009 "frame=[%" PRId32 ",%" PRId32 "][%" PRId32 ",%" PRId32
3010 "], touchableRegion=%s, window={%s}, inputConfig={%s}, "
3011 "hasToken=%s, applicationInfo.name=%s, applicationInfo.token=%s\n",
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08003012 isTouchedWindow ? "[TOUCHED] " : "", info->packageName.c_str(),
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003013 info->ownerUid.toString().c_str(), info->id,
3014 toString(info->touchOcclusionMode).c_str(), info->alpha, info->frameLeft,
3015 info->frameTop, info->frameRight, info->frameBottom,
3016 dumpRegion(info->touchableRegion).c_str(), info->name.c_str(),
3017 info->inputConfig.string().c_str(), toString(info->token != nullptr),
3018 info->applicationInfo.name.c_str(),
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07003019 binderToString(info->applicationInfo.token).c_str());
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00003020}
3021
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003022bool InputDispatcher::isTouchTrustedLocked(const TouchOcclusionInfo& occlusionInfo) const {
3023 if (occlusionInfo.hasBlockingOcclusion) {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003024 ALOGW("Untrusted touch due to occlusion by %s/%s", occlusionInfo.obscuringPackage.c_str(),
3025 occlusionInfo.obscuringUid.toString().c_str());
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003026 return false;
3027 }
3028 if (occlusionInfo.obscuringOpacity > mMaximumObscuringOpacityForTouch) {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003029 ALOGW("Untrusted touch due to occlusion by %s/%s (obscuring opacity = "
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003030 "%.2f, maximum allowed = %.2f)",
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003031 occlusionInfo.obscuringPackage.c_str(), occlusionInfo.obscuringUid.toString().c_str(),
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003032 occlusionInfo.obscuringOpacity, mMaximumObscuringOpacityForTouch);
3033 return false;
3034 }
3035 return true;
3036}
3037
chaviw98318de2021-05-19 16:45:23 -05003038bool InputDispatcher::isWindowObscuredAtPointLocked(const sp<WindowInfoHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003039 int32_t x, int32_t y) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003040 int32_t displayId = windowHandle->getInfo()->displayId;
chaviw98318de2021-05-19 16:45:23 -05003041 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
3042 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07003043 if (windowHandle == otherHandle) {
3044 break; // All future windows are below us. Exit early.
Michael Wrightd02c5b62014-02-10 15:10:22 -08003045 }
chaviw98318de2021-05-19 16:45:23 -05003046 const WindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07003047 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08003048 otherInfo->frameContainsPoint(x, y)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003049 return true;
3050 }
3051 }
3052 return false;
3053}
3054
chaviw98318de2021-05-19 16:45:23 -05003055bool InputDispatcher::isWindowObscuredLocked(const sp<WindowInfoHandle>& windowHandle) const {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07003056 int32_t displayId = windowHandle->getInfo()->displayId;
chaviw98318de2021-05-19 16:45:23 -05003057 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
3058 const WindowInfo* windowInfo = windowHandle->getInfo();
3059 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07003060 if (windowHandle == otherHandle) {
3061 break; // All future windows are below us. Exit early.
Michael Wrightcdcd8f22016-03-22 16:52:13 -07003062 }
chaviw98318de2021-05-19 16:45:23 -05003063 const WindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07003064 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08003065 otherInfo->overlaps(windowInfo)) {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07003066 return true;
3067 }
3068 }
3069 return false;
3070}
3071
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08003072std::string InputDispatcher::getApplicationWindowLabel(
chaviw98318de2021-05-19 16:45:23 -05003073 const InputApplicationHandle* applicationHandle, const sp<WindowInfoHandle>& windowHandle) {
Yi Kong9b14ac62018-07-17 13:48:38 -07003074 if (applicationHandle != nullptr) {
3075 if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07003076 return applicationHandle->getName() + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003077 } else {
3078 return applicationHandle->getName();
3079 }
Yi Kong9b14ac62018-07-17 13:48:38 -07003080 } else if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07003081 return windowHandle->getInfo()->applicationInfo.name + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003082 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003083 return "<unknown application or window>";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003084 }
3085}
3086
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003087void InputDispatcher::pokeUserActivityLocked(const EventEntry& eventEntry) {
Antonio Kantekf16f2832021-09-28 04:39:20 +00003088 if (!isUserActivityEvent(eventEntry)) {
3089 // Not poking user activity if the event type does not represent a user activity
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003090 return;
3091 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003092 int32_t displayId = getTargetDisplayId(eventEntry);
chaviw98318de2021-05-19 16:45:23 -05003093 sp<WindowInfoHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Josep del Riob3981622023-04-18 15:49:45 +00003094 const WindowInfo* windowDisablingUserActivityInfo = nullptr;
Tiger Huang721e26f2018-07-24 22:26:19 +08003095 if (focusedWindowHandle != nullptr) {
chaviw98318de2021-05-19 16:45:23 -05003096 const WindowInfo* info = focusedWindowHandle->getInfo();
Prabir Pradhan51e7db02022-02-07 06:02:57 -08003097 if (info->inputConfig.test(WindowInfo::InputConfig::DISABLE_USER_ACTIVITY)) {
Josep del Riob3981622023-04-18 15:49:45 +00003098 windowDisablingUserActivityInfo = info;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003099 }
3100 }
3101
3102 int32_t eventType = USER_ACTIVITY_EVENT_OTHER;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003103 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003104 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003105 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
3106 if (motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003107 return;
3108 }
Josep del Riob3981622023-04-18 15:49:45 +00003109 if (windowDisablingUserActivityInfo != nullptr) {
3110 if (DEBUG_DISPATCH_CYCLE) {
3111 ALOGD("Not poking user activity: disabled by window '%s'.",
3112 windowDisablingUserActivityInfo->name.c_str());
3113 }
3114 return;
3115 }
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003116 if (MotionEvent::isTouchEvent(motionEntry.source, motionEntry.action)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003117 eventType = USER_ACTIVITY_EVENT_TOUCH;
3118 }
3119 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003120 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003121 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003122 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
3123 if (keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003124 return;
3125 }
Josep del Riob3981622023-04-18 15:49:45 +00003126 // If the key code is unknown, we don't consider it user activity
3127 if (keyEntry.keyCode == AKEYCODE_UNKNOWN) {
3128 return;
3129 }
3130 // Don't inhibit events that were intercepted or are not passed to
3131 // the apps, like system shortcuts
3132 if (windowDisablingUserActivityInfo != nullptr &&
3133 keyEntry.interceptKeyResult != KeyEntry::InterceptKeyResult::SKIP &&
3134 keyEntry.policyFlags & POLICY_FLAG_PASS_TO_USER) {
3135 if (DEBUG_DISPATCH_CYCLE) {
3136 ALOGD("Not poking user activity: disabled by window '%s'.",
3137 windowDisablingUserActivityInfo->name.c_str());
3138 }
3139 return;
3140 }
3141
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003142 eventType = USER_ACTIVITY_EVENT_BUTTON;
3143 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003144 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00003145 default: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003146 LOG_ALWAYS_FATAL("%s events are not user activity",
Dominik Laskowski75788452021-02-09 18:51:25 -08003147 ftl::enum_string(eventEntry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003148 break;
3149 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003150 }
3151
Prabir Pradhancef936d2021-07-21 16:17:52 +00003152 auto command = [this, eventTime = eventEntry.eventTime, eventType, displayId]()
3153 REQUIRES(mLock) {
3154 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00003155 mPolicy.pokeUserActivity(eventTime, eventType, displayId);
Prabir Pradhancef936d2021-07-21 16:17:52 +00003156 };
3157 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003158}
3159
3160void InputDispatcher::prepareDispatchCycleLocked(nsecs_t currentTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003161 const std::shared_ptr<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003162 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003163 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003164 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003165 std::string message =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003166 StringPrintf("prepareDispatchCycleLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003167 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00003168 ATRACE_NAME(message.c_str());
3169 }
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003170 if (DEBUG_DISPATCH_CYCLE) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003171 ALOGD("channel '%s' ~ prepareDispatchCycle - flags=%s, "
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08003172 "globalScaleFactor=%f, pointerIds=%s %s",
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003173 connection->getInputChannelName().c_str(), inputTarget.flags.string().c_str(),
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08003174 inputTarget.globalScaleFactor, bitsetToString(inputTarget.pointerIds).c_str(),
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003175 inputTarget.getPointerInfoString().c_str());
3176 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003177
3178 // Skip this event if the connection status is not normal.
3179 // We don't want to enqueue additional outbound events if the connection is broken.
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003180 if (connection->status != Connection::Status::NORMAL) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003181 if (DEBUG_DISPATCH_CYCLE) {
3182 ALOGD("channel '%s' ~ Dropping event because the channel status is %s",
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003183 connection->getInputChannelName().c_str(),
3184 ftl::enum_string(connection->status).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003185 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003186 return;
3187 }
3188
3189 // Split a motion event if needed.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003190 if (inputTarget.flags.test(InputTarget::Flags::SPLIT)) {
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003191 LOG_ALWAYS_FATAL_IF(eventEntry->type != EventEntry::Type::MOTION,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003192 "Entry type %s should not have Flags::SPLIT",
Dominik Laskowski75788452021-02-09 18:51:25 -08003193 ftl::enum_string(eventEntry->type).c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003194
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003195 const MotionEntry& originalMotionEntry = static_cast<const MotionEntry&>(*eventEntry);
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003196 if (inputTarget.pointerIds.count() != originalMotionEntry.pointerCount) {
Siarhei Vishniakou16e4fa02023-02-16 17:48:56 -08003197 if (!inputTarget.firstDownTimeInTarget.has_value()) {
3198 logDispatchStateLocked();
3199 LOG(FATAL) << "Splitting motion events requires a down time to be set for the "
3200 "target on connection "
3201 << connection->getInputChannelName() << " for "
3202 << originalMotionEntry.getDescription();
3203 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003204 std::unique_ptr<MotionEntry> splitMotionEntry =
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00003205 splitMotionEvent(originalMotionEntry, inputTarget.pointerIds,
3206 inputTarget.firstDownTimeInTarget.value());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003207 if (!splitMotionEntry) {
3208 return; // split event was dropped
3209 }
Arthur Hungb3307ee2021-10-14 10:57:37 +00003210 if (splitMotionEntry->action == AMOTION_EVENT_ACTION_CANCEL) {
3211 std::string reason = std::string("reason=pointer cancel on split window");
3212 android_log_event_list(LOGTAG_INPUT_CANCEL)
3213 << connection->getInputChannelName().c_str() << reason << LOG_ID_EVENTS;
3214 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003215 if (DEBUG_FOCUS) {
3216 ALOGD("channel '%s' ~ Split motion event.",
3217 connection->getInputChannelName().c_str());
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003218 logOutboundMotionDetails(" ", *splitMotionEntry);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003219 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003220 enqueueDispatchEntriesLocked(currentTime, connection, std::move(splitMotionEntry),
3221 inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003222 return;
3223 }
3224 }
3225
3226 // Not splitting. Enqueue dispatch entries for the event as is.
3227 enqueueDispatchEntriesLocked(currentTime, connection, eventEntry, inputTarget);
3228}
3229
3230void InputDispatcher::enqueueDispatchEntriesLocked(nsecs_t currentTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003231 const std::shared_ptr<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003232 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003233 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003234 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003235 std::string message =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003236 StringPrintf("enqueueDispatchEntriesLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003237 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00003238 ATRACE_NAME(message.c_str());
3239 }
Siarhei Vishniakou5cee1e32022-11-29 12:35:39 -08003240 LOG_ALWAYS_FATAL_IF(!inputTarget.flags.any(InputTarget::DISPATCH_MASK),
3241 "No dispatch flags are set for %s", eventEntry->getDescription().c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00003242
hongzuo liu95785e22022-09-06 02:51:35 +00003243 const bool wasEmpty = connection->outboundQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003244
3245 // Enqueue dispatch entries for the requested modes.
chaviw8c9cf542019-03-25 13:02:48 -07003246 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003247 InputTarget::Flags::DISPATCH_AS_HOVER_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07003248 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003249 InputTarget::Flags::DISPATCH_AS_OUTSIDE);
chaviw8c9cf542019-03-25 13:02:48 -07003250 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003251 InputTarget::Flags::DISPATCH_AS_HOVER_ENTER);
chaviw8c9cf542019-03-25 13:02:48 -07003252 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003253 InputTarget::Flags::DISPATCH_AS_IS);
chaviw8c9cf542019-03-25 13:02:48 -07003254 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003255 InputTarget::Flags::DISPATCH_AS_SLIPPERY_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07003256 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003257 InputTarget::Flags::DISPATCH_AS_SLIPPERY_ENTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003258
3259 // If the outbound queue was previously empty, start the dispatch cycle going.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003260 if (wasEmpty && !connection->outboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003261 startDispatchCycleLocked(currentTime, connection);
3262 }
3263}
3264
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003265void InputDispatcher::enqueueDispatchEntryLocked(const std::shared_ptr<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003266 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003267 const InputTarget& inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003268 ftl::Flags<InputTarget::Flags> dispatchMode) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003269 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003270 std::string message = StringPrintf("enqueueDispatchEntry(inputChannel=%s, dispatchMode=%s)",
3271 connection->getInputChannelName().c_str(),
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003272 dispatchMode.string().c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00003273 ATRACE_NAME(message.c_str());
3274 }
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003275 ftl::Flags<InputTarget::Flags> inputTargetFlags = inputTarget.flags;
3276 if (!inputTargetFlags.any(dispatchMode)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003277 return;
3278 }
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003279
3280 inputTargetFlags.clear(InputTarget::DISPATCH_MASK);
3281 inputTargetFlags |= dispatchMode;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003282
3283 // This is a new event.
3284 // Enqueue a new dispatch entry onto the outbound queue for this connection.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003285 std::unique_ptr<DispatchEntry> dispatchEntry =
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003286 createDispatchEntry(inputTarget, eventEntry, inputTargetFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003287
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003288 // Use the eventEntry from dispatchEntry since the entry may have changed and can now be a
3289 // different EventEntry than what was passed in.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003290 EventEntry& newEntry = *(dispatchEntry->eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003291 // Apply target flags and update the connection's input state.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003292 switch (newEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003293 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003294 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(newEntry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003295 if (!connection->inputState.trackKey(keyEntry, dispatchEntry->resolvedAction,
3296 dispatchEntry->resolvedFlags)) {
Siarhei Vishniakouc94dafe2023-05-26 10:24:19 -07003297 LOG(WARNING) << "channel " << connection->getInputChannelName()
3298 << "~ dropping inconsistent event: " << *dispatchEntry;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003299 return; // skip the inconsistent event
3300 }
3301 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003302 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003303
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003304 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003305 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003306 // Assign a default value to dispatchEntry that will never be generated by InputReader,
3307 // and assign a InputDispatcher value if it doesn't change in the if-else chain below.
3308 constexpr int32_t DEFAULT_RESOLVED_EVENT_ID =
3309 static_cast<int32_t>(IdGenerator::Source::OTHER);
3310 dispatchEntry->resolvedEventId = DEFAULT_RESOLVED_EVENT_ID;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003311 if (dispatchMode.test(InputTarget::Flags::DISPATCH_AS_OUTSIDE)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003312 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_OUTSIDE;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003313 } else if (dispatchMode.test(InputTarget::Flags::DISPATCH_AS_HOVER_EXIT)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003314 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_EXIT;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003315 } else if (dispatchMode.test(InputTarget::Flags::DISPATCH_AS_HOVER_ENTER)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003316 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003317 } else if (dispatchMode.test(InputTarget::Flags::DISPATCH_AS_SLIPPERY_EXIT)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003318 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_CANCEL;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003319 } else if (dispatchMode.test(InputTarget::Flags::DISPATCH_AS_SLIPPERY_ENTER)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003320 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_DOWN;
3321 } else {
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003322 dispatchEntry->resolvedEventId = motionEntry.id;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003323 }
3324 if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_HOVER_MOVE &&
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003325 !connection->inputState.isHovering(motionEntry.deviceId, motionEntry.source,
3326 motionEntry.displayId)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003327 if (DEBUG_DISPATCH_CYCLE) {
3328 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: filling in missing hover "
3329 "enter event",
3330 connection->getInputChannelName().c_str());
3331 }
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00003332 // We keep the 'resolvedEventId' here equal to the original 'motionEntry.id' because
3333 // this is a one-to-one event conversion.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003334 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
3335 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003336
Siarhei Vishniakou1ae72f12023-01-29 12:55:30 -08003337 if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_CANCEL) {
3338 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_CANCELED;
3339 }
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003340 if (dispatchEntry->targetFlags.test(InputTarget::Flags::WINDOW_IS_OBSCURED)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003341 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED;
3342 }
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003343 if (dispatchEntry->targetFlags.test(InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003344 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
3345 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003346
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003347 if (!connection->inputState.trackMotion(motionEntry, dispatchEntry->resolvedAction,
3348 dispatchEntry->resolvedFlags)) {
Siarhei Vishniakouc94dafe2023-05-26 10:24:19 -07003349 LOG(WARNING) << "channel " << connection->getInputChannelName()
3350 << "~ dropping inconsistent event: " << *dispatchEntry;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003351 return; // skip the inconsistent event
3352 }
3353
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003354 dispatchEntry->resolvedEventId =
3355 dispatchEntry->resolvedEventId == DEFAULT_RESOLVED_EVENT_ID
3356 ? mIdGenerator.nextId()
3357 : motionEntry.id;
3358 if (ATRACE_ENABLED() && dispatchEntry->resolvedEventId != motionEntry.id) {
3359 std::string message = StringPrintf("Transmute MotionEvent(id=0x%" PRIx32
3360 ") to MotionEvent(id=0x%" PRIx32 ").",
3361 motionEntry.id, dispatchEntry->resolvedEventId);
3362 ATRACE_NAME(message.c_str());
3363 }
3364
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08003365 if ((motionEntry.flags & AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE) &&
3366 (motionEntry.policyFlags & POLICY_FLAG_TRUSTED)) {
3367 // Skip reporting pointer down outside focus to the policy.
3368 break;
3369 }
3370
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003371 dispatchPointerDownOutsideFocus(motionEntry.source, dispatchEntry->resolvedAction,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003372 inputTarget.inputChannel->getConnectionToken());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003373
3374 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003375 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003376 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003377 case EventEntry::Type::TOUCH_MODE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08003378 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
3379 case EventEntry::Type::DRAG: {
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003380 break;
3381 }
Chris Yef59a2f42020-10-16 12:55:26 -07003382 case EventEntry::Type::SENSOR: {
3383 LOG_ALWAYS_FATAL("SENSOR events should not go to apps via input channel");
3384 break;
3385 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003386 case EventEntry::Type::CONFIGURATION_CHANGED:
3387 case EventEntry::Type::DEVICE_RESET: {
3388 LOG_ALWAYS_FATAL("%s events should not go to apps",
Dominik Laskowski75788452021-02-09 18:51:25 -08003389 ftl::enum_string(newEntry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003390 break;
3391 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003392 }
3393
3394 // Remember that we are waiting for this dispatch to complete.
3395 if (dispatchEntry->hasForegroundTarget()) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003396 incrementPendingForegroundDispatches(newEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003397 }
3398
3399 // Enqueue the dispatch entry.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003400 connection->outboundQueue.push_back(dispatchEntry.release());
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003401 traceOutboundQueueLength(*connection);
chaviw8c9cf542019-03-25 13:02:48 -07003402}
3403
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003404/**
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003405 * This function is for debugging and metrics collection. It has two roles.
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003406 *
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003407 * The first role is to log input interaction with windows, which helps determine what the user was
3408 * interacting with. For example, if user is touching launcher, we will see an input_interaction log
3409 * that user started interacting with launcher window, as well as any other window that received
3410 * that gesture, such as the wallpaper or other spy windows. A new input_interaction is only logged
3411 * when the set of tokens that received the event changes. It is not logged again as long as the
3412 * user is interacting with the same windows.
3413 *
3414 * The second role is to track input device activity for metrics collection. For each input event,
3415 * we report the set of UIDs that the input device interacted with to the policy. Unlike for the
3416 * input_interaction logs, the device interaction is reported even when the set of interaction
3417 * tokens do not change.
3418 *
3419 * For these purposes, we do not count ACTION_OUTSIDE, ACTION_UP and ACTION_CANCEL actions as
3420 * interaction. This includes up and cancel events for both keys and motions.
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003421 */
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003422void InputDispatcher::processInteractionsLocked(const EventEntry& entry,
3423 const std::vector<InputTarget>& targets) {
3424 int32_t deviceId;
3425 nsecs_t eventTime;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003426 // Skip ACTION_UP events, and all events other than keys and motions
3427 if (entry.type == EventEntry::Type::KEY) {
3428 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
3429 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
3430 return;
3431 }
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003432 deviceId = keyEntry.deviceId;
3433 eventTime = keyEntry.eventTime;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003434 } else if (entry.type == EventEntry::Type::MOTION) {
3435 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
3436 if (motionEntry.action == AMOTION_EVENT_ACTION_UP ||
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003437 motionEntry.action == AMOTION_EVENT_ACTION_CANCEL ||
3438 MotionEvent::getActionMasked(motionEntry.action) == AMOTION_EVENT_ACTION_POINTER_UP) {
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003439 return;
3440 }
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003441 deviceId = motionEntry.deviceId;
3442 eventTime = motionEntry.eventTime;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003443 } else {
3444 return; // Not a key or a motion
3445 }
3446
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003447 std::set<gui::Uid> interactionUids;
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07003448 std::unordered_set<sp<IBinder>, StrongPointerHash<IBinder>> newConnectionTokens;
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003449 std::vector<std::shared_ptr<Connection>> newConnections;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003450 for (const InputTarget& target : targets) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003451 if (target.flags.test(InputTarget::Flags::DISPATCH_AS_OUTSIDE)) {
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003452 continue; // Skip windows that receive ACTION_OUTSIDE
3453 }
3454
3455 sp<IBinder> token = target.inputChannel->getConnectionToken();
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003456 std::shared_ptr<Connection> connection = getConnectionLocked(token);
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003457 if (connection == nullptr) {
3458 continue;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003459 }
3460 newConnectionTokens.insert(std::move(token));
3461 newConnections.emplace_back(connection);
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003462 if (target.windowHandle) {
3463 interactionUids.emplace(target.windowHandle->getInfo()->ownerUid);
3464 }
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003465 }
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003466
3467 auto command = [this, deviceId, eventTime, uids = std::move(interactionUids)]()
3468 REQUIRES(mLock) {
3469 scoped_unlock unlock(mLock);
3470 mPolicy.notifyDeviceInteraction(deviceId, eventTime, uids);
3471 };
3472 postCommandLocked(std::move(command));
3473
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003474 if (newConnectionTokens == mInteractionConnectionTokens) {
3475 return; // no change
3476 }
3477 mInteractionConnectionTokens = newConnectionTokens;
3478
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003479 std::string targetList;
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003480 for (const std::shared_ptr<Connection>& connection : newConnections) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003481 targetList += connection->getWindowName() + ", ";
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003482 }
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003483 std::string message = "Interaction with: " + targetList;
3484 if (targetList.empty()) {
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003485 message += "<none>";
3486 }
3487 android_log_event_list(LOGTAG_INPUT_INTERACTION) << message << LOG_ID_EVENTS;
3488}
3489
chaviwfd6d3512019-03-25 13:23:49 -07003490void InputDispatcher::dispatchPointerDownOutsideFocus(uint32_t source, int32_t action,
Vishnu Nairad321cd2020-08-20 16:40:21 -07003491 const sp<IBinder>& token) {
chaviw8c9cf542019-03-25 13:02:48 -07003492 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
chaviwfd6d3512019-03-25 13:23:49 -07003493 uint32_t maskedSource = source & AINPUT_SOURCE_CLASS_MASK;
3494 if (maskedSource != AINPUT_SOURCE_CLASS_POINTER || maskedAction != AMOTION_EVENT_ACTION_DOWN) {
chaviw8c9cf542019-03-25 13:02:48 -07003495 return;
3496 }
3497
Vishnu Nairc519ff72021-01-21 08:23:08 -08003498 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07003499 if (focusedToken == token) {
3500 // ignore since token is focused
chaviw8c9cf542019-03-25 13:02:48 -07003501 return;
3502 }
3503
Prabir Pradhancef936d2021-07-21 16:17:52 +00003504 auto command = [this, token]() REQUIRES(mLock) {
3505 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00003506 mPolicy.onPointerDownOutsideFocus(token);
Prabir Pradhancef936d2021-07-21 16:17:52 +00003507 };
3508 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003509}
3510
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003511status_t InputDispatcher::publishMotionEvent(Connection& connection,
3512 DispatchEntry& dispatchEntry) const {
3513 const EventEntry& eventEntry = *(dispatchEntry.eventEntry);
3514 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
3515
3516 PointerCoords scaledCoords[MAX_POINTERS];
3517 const PointerCoords* usingCoords = motionEntry.pointerCoords;
3518
3519 // Set the X and Y offset and X and Y scale depending on the input source.
3520 if ((motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) &&
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003521 !(dispatchEntry.targetFlags.test(InputTarget::Flags::ZERO_COORDS))) {
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003522 float globalScaleFactor = dispatchEntry.globalScaleFactor;
3523 if (globalScaleFactor != 1.0f) {
3524 for (uint32_t i = 0; i < motionEntry.pointerCount; i++) {
3525 scaledCoords[i] = motionEntry.pointerCoords[i];
3526 // Don't apply window scale here since we don't want scale to affect raw
3527 // coordinates. The scale will be sent back to the client and applied
3528 // later when requesting relative coordinates.
Harry Cutts33476232023-01-30 19:57:29 +00003529 scaledCoords[i].scale(globalScaleFactor, /*windowXScale=*/1, /*windowYScale=*/1);
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003530 }
3531 usingCoords = scaledCoords;
3532 }
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003533 } else if (dispatchEntry.targetFlags.test(InputTarget::Flags::ZERO_COORDS)) {
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003534 // We don't want the dispatch target to know the coordinates
3535 for (uint32_t i = 0; i < motionEntry.pointerCount; i++) {
3536 scaledCoords[i].clear();
3537 }
3538 usingCoords = scaledCoords;
3539 }
3540
3541 std::array<uint8_t, 32> hmac = getSignature(motionEntry, dispatchEntry);
3542
3543 // Publish the motion event.
3544 return connection.inputPublisher
3545 .publishMotionEvent(dispatchEntry.seq, dispatchEntry.resolvedEventId,
3546 motionEntry.deviceId, motionEntry.source, motionEntry.displayId,
3547 std::move(hmac), dispatchEntry.resolvedAction,
3548 motionEntry.actionButton, dispatchEntry.resolvedFlags,
3549 motionEntry.edgeFlags, motionEntry.metaState,
3550 motionEntry.buttonState, motionEntry.classification,
3551 dispatchEntry.transform, motionEntry.xPrecision,
3552 motionEntry.yPrecision, motionEntry.xCursorPosition,
3553 motionEntry.yCursorPosition, dispatchEntry.rawTransform,
3554 motionEntry.downTime, motionEntry.eventTime,
3555 motionEntry.pointerCount, motionEntry.pointerProperties,
3556 usingCoords);
3557}
3558
Michael Wrightd02c5b62014-02-10 15:10:22 -08003559void InputDispatcher::startDispatchCycleLocked(nsecs_t currentTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003560 const std::shared_ptr<Connection>& connection) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003561 if (ATRACE_ENABLED()) {
3562 std::string message = StringPrintf("startDispatchCycleLocked(inputChannel=%s)",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003563 connection->getInputChannelName().c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00003564 ATRACE_NAME(message.c_str());
3565 }
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003566 if (DEBUG_DISPATCH_CYCLE) {
3567 ALOGD("channel '%s' ~ startDispatchCycle", connection->getInputChannelName().c_str());
3568 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003569
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003570 while (connection->status == Connection::Status::NORMAL && !connection->outboundQueue.empty()) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003571 DispatchEntry* dispatchEntry = connection->outboundQueue.front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003572 dispatchEntry->deliveryTime = currentTime;
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003573 const std::chrono::nanoseconds timeout = getDispatchingTimeoutLocked(connection);
Siarhei Vishniakou70622952020-07-30 11:17:23 -05003574 dispatchEntry->timeoutTime = currentTime + timeout.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003575
3576 // Publish the event.
3577 status_t status;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003578 const EventEntry& eventEntry = *(dispatchEntry->eventEntry);
3579 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003580 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003581 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
3582 std::array<uint8_t, 32> hmac = getSignature(keyEntry, *dispatchEntry);
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08003583 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07003584 LOG(INFO) << "Publishing " << *dispatchEntry << " to "
3585 << connection->getInputChannelName();
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08003586 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003587
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003588 // Publish the key event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003589 status = connection->inputPublisher
3590 .publishKeyEvent(dispatchEntry->seq,
3591 dispatchEntry->resolvedEventId, keyEntry.deviceId,
3592 keyEntry.source, keyEntry.displayId,
3593 std::move(hmac), dispatchEntry->resolvedAction,
3594 dispatchEntry->resolvedFlags, keyEntry.keyCode,
3595 keyEntry.scanCode, keyEntry.metaState,
3596 keyEntry.repeatCount, keyEntry.downTime,
3597 keyEntry.eventTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003598 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003599 }
3600
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003601 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08003602 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07003603 LOG(INFO) << "Publishing " << *dispatchEntry << " to "
3604 << connection->getInputChannelName();
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08003605 }
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003606 status = publishMotionEvent(*connection, *dispatchEntry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003607 break;
3608 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003609
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003610 case EventEntry::Type::FOCUS: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003611 const FocusEntry& focusEntry = static_cast<const FocusEntry&>(eventEntry);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003612 status = connection->inputPublisher.publishFocusEvent(dispatchEntry->seq,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003613 focusEntry.id,
Antonio Kantek3cfec7b2021-11-05 18:26:17 -07003614 focusEntry.hasFocus);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003615 break;
3616 }
3617
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003618 case EventEntry::Type::TOUCH_MODE_CHANGED: {
3619 const TouchModeEntry& touchModeEntry =
3620 static_cast<const TouchModeEntry&>(eventEntry);
3621 status = connection->inputPublisher
3622 .publishTouchModeEvent(dispatchEntry->seq, touchModeEntry.id,
3623 touchModeEntry.inTouchMode);
3624
3625 break;
3626 }
3627
Prabir Pradhan99987712020-11-10 18:43:05 -08003628 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
3629 const auto& captureEntry =
3630 static_cast<const PointerCaptureChangedEntry&>(eventEntry);
3631 status = connection->inputPublisher
3632 .publishCaptureEvent(dispatchEntry->seq, captureEntry.id,
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00003633 captureEntry.pointerCaptureRequest.enable);
Prabir Pradhan99987712020-11-10 18:43:05 -08003634 break;
3635 }
3636
arthurhungb89ccb02020-12-30 16:19:01 +08003637 case EventEntry::Type::DRAG: {
3638 const DragEntry& dragEntry = static_cast<const DragEntry&>(eventEntry);
3639 status = connection->inputPublisher.publishDragEvent(dispatchEntry->seq,
3640 dragEntry.id, dragEntry.x,
3641 dragEntry.y,
3642 dragEntry.isExiting);
3643 break;
3644 }
3645
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003646 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07003647 case EventEntry::Type::DEVICE_RESET:
3648 case EventEntry::Type::SENSOR: {
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003649 LOG_ALWAYS_FATAL("Should never start dispatch cycles for %s events",
Dominik Laskowski75788452021-02-09 18:51:25 -08003650 ftl::enum_string(eventEntry.type).c_str());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003651 return;
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003652 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003653 }
3654
3655 // Check the result.
3656 if (status) {
3657 if (status == WOULD_BLOCK) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003658 if (connection->waitQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003659 ALOGE("channel '%s' ~ Could not publish event because the pipe is full. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003660 "This is unexpected because the wait queue is empty, so the pipe "
3661 "should be empty and we shouldn't have any problems writing an "
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +00003662 "event to it, status=%s(%d)",
3663 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3664 status);
Harry Cutts33476232023-01-30 19:57:29 +00003665 abortBrokenDispatchCycleLocked(currentTime, connection, /*notify=*/true);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003666 } else {
3667 // Pipe is full and we are waiting for the app to finish process some events
3668 // before sending more events to it.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003669 if (DEBUG_DISPATCH_CYCLE) {
3670 ALOGD("channel '%s' ~ Could not publish event because the pipe is full, "
3671 "waiting for the application to catch up",
3672 connection->getInputChannelName().c_str());
3673 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003674 }
3675 } else {
3676 ALOGE("channel '%s' ~ Could not publish event due to an unexpected error, "
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +00003677 "status=%s(%d)",
3678 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3679 status);
Harry Cutts33476232023-01-30 19:57:29 +00003680 abortBrokenDispatchCycleLocked(currentTime, connection, /*notify=*/true);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003681 }
3682 return;
3683 }
3684
3685 // Re-enqueue the event on the wait queue.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003686 connection->outboundQueue.erase(std::remove(connection->outboundQueue.begin(),
3687 connection->outboundQueue.end(),
3688 dispatchEntry));
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003689 traceOutboundQueueLength(*connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003690 connection->waitQueue.push_back(dispatchEntry);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003691 if (connection->responsive) {
3692 mAnrTracker.insert(dispatchEntry->timeoutTime,
3693 connection->inputChannel->getConnectionToken());
3694 }
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003695 traceWaitQueueLength(*connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003696 }
3697}
3698
chaviw09c8d2d2020-08-24 15:48:26 -07003699std::array<uint8_t, 32> InputDispatcher::sign(const VerifiedInputEvent& event) const {
3700 size_t size;
3701 switch (event.type) {
3702 case VerifiedInputEvent::Type::KEY: {
3703 size = sizeof(VerifiedKeyEvent);
3704 break;
3705 }
3706 case VerifiedInputEvent::Type::MOTION: {
3707 size = sizeof(VerifiedMotionEvent);
3708 break;
3709 }
3710 }
3711 const uint8_t* start = reinterpret_cast<const uint8_t*>(&event);
3712 return mHmacKeyManager.sign(start, size);
3713}
3714
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003715const std::array<uint8_t, 32> InputDispatcher::getSignature(
3716 const MotionEntry& motionEntry, const DispatchEntry& dispatchEntry) const {
Siarhei Vishniakoubf880522023-05-01 11:03:22 -07003717 const int32_t actionMasked = MotionEvent::getActionMasked(dispatchEntry.resolvedAction);
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003718 if (actionMasked != AMOTION_EVENT_ACTION_UP && actionMasked != AMOTION_EVENT_ACTION_DOWN) {
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003719 // Only sign events up and down events as the purely move events
3720 // are tied to their up/down counterparts so signing would be redundant.
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003721 return INVALID_HMAC;
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003722 }
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003723
3724 VerifiedMotionEvent verifiedEvent =
3725 verifiedMotionEventFromMotionEntry(motionEntry, dispatchEntry.rawTransform);
3726 verifiedEvent.actionMasked = actionMasked;
3727 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_MOTION_EVENT_FLAGS;
3728 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003729}
3730
3731const std::array<uint8_t, 32> InputDispatcher::getSignature(
3732 const KeyEntry& keyEntry, const DispatchEntry& dispatchEntry) const {
3733 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEntry(keyEntry);
3734 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_KEY_EVENT_FLAGS;
3735 verifiedEvent.action = dispatchEntry.resolvedAction;
chaviw09c8d2d2020-08-24 15:48:26 -07003736 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003737}
3738
Michael Wrightd02c5b62014-02-10 15:10:22 -08003739void InputDispatcher::finishDispatchCycleLocked(nsecs_t currentTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003740 const std::shared_ptr<Connection>& connection,
3741 uint32_t seq, bool handled, nsecs_t consumeTime) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003742 if (DEBUG_DISPATCH_CYCLE) {
3743 ALOGD("channel '%s' ~ finishDispatchCycle - seq=%u, handled=%s",
3744 connection->getInputChannelName().c_str(), seq, toString(handled));
3745 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003746
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003747 if (connection->status == Connection::Status::BROKEN ||
3748 connection->status == Connection::Status::ZOMBIE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003749 return;
3750 }
3751
3752 // Notify other system components and prepare to start the next dispatch cycle.
Prabir Pradhancef936d2021-07-21 16:17:52 +00003753 auto command = [this, currentTime, connection, seq, handled, consumeTime]() REQUIRES(mLock) {
3754 doDispatchCycleFinishedCommand(currentTime, connection, seq, handled, consumeTime);
3755 };
3756 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003757}
3758
3759void InputDispatcher::abortBrokenDispatchCycleLocked(nsecs_t currentTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003760 const std::shared_ptr<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003761 bool notify) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003762 if (DEBUG_DISPATCH_CYCLE) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07003763 LOG(INFO) << "channel '" << connection->getInputChannelName() << "'~ " << __func__
3764 << " - notify=" << toString(notify);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003765 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003766
3767 // Clear the dispatch queues.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003768 drainDispatchQueue(connection->outboundQueue);
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003769 traceOutboundQueueLength(*connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003770 drainDispatchQueue(connection->waitQueue);
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003771 traceWaitQueueLength(*connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003772
3773 // The connection appears to be unrecoverably broken.
3774 // Ignore already broken or zombie connections.
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003775 if (connection->status == Connection::Status::NORMAL) {
3776 connection->status = Connection::Status::BROKEN;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003777
3778 if (notify) {
3779 // Notify other system components.
Prabir Pradhancef936d2021-07-21 16:17:52 +00003780 ALOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
3781 connection->getInputChannelName().c_str());
3782
3783 auto command = [this, connection]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00003784 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00003785 mPolicy.notifyInputChannelBroken(connection->inputChannel->getConnectionToken());
Prabir Pradhancef936d2021-07-21 16:17:52 +00003786 };
3787 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003788 }
3789 }
3790}
3791
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003792void InputDispatcher::drainDispatchQueue(std::deque<DispatchEntry*>& queue) {
3793 while (!queue.empty()) {
3794 DispatchEntry* dispatchEntry = queue.front();
3795 queue.pop_front();
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003796 releaseDispatchEntry(dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003797 }
3798}
3799
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003800void InputDispatcher::releaseDispatchEntry(DispatchEntry* dispatchEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003801 if (dispatchEntry->hasForegroundTarget()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003802 decrementPendingForegroundDispatches(*(dispatchEntry->eventEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003803 }
3804 delete dispatchEntry;
3805}
3806
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003807int InputDispatcher::handleReceiveCallback(int events, sp<IBinder> connectionToken) {
3808 std::scoped_lock _l(mLock);
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003809 std::shared_ptr<Connection> connection = getConnectionLocked(connectionToken);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003810 if (connection == nullptr) {
3811 ALOGW("Received looper callback for unknown input channel token %p. events=0x%x",
3812 connectionToken.get(), events);
3813 return 0; // remove the callback
3814 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003815
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003816 bool notify;
3817 if (!(events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP))) {
3818 if (!(events & ALOOPER_EVENT_INPUT)) {
3819 ALOGW("channel '%s' ~ Received spurious callback for unhandled poll event. "
3820 "events=0x%x",
3821 connection->getInputChannelName().c_str(), events);
3822 return 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003823 }
3824
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003825 nsecs_t currentTime = now();
3826 bool gotOne = false;
3827 status_t status = OK;
3828 for (;;) {
3829 Result<InputPublisher::ConsumerResponse> result =
3830 connection->inputPublisher.receiveConsumerResponse();
3831 if (!result.ok()) {
3832 status = result.error().code();
3833 break;
3834 }
3835
3836 if (std::holds_alternative<InputPublisher::Finished>(*result)) {
3837 const InputPublisher::Finished& finish =
3838 std::get<InputPublisher::Finished>(*result);
3839 finishDispatchCycleLocked(currentTime, connection, finish.seq, finish.handled,
3840 finish.consumeTime);
3841 } else if (std::holds_alternative<InputPublisher::Timeline>(*result)) {
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00003842 if (shouldReportMetricsForConnection(*connection)) {
3843 const InputPublisher::Timeline& timeline =
3844 std::get<InputPublisher::Timeline>(*result);
3845 mLatencyTracker
3846 .trackGraphicsLatency(timeline.inputEventId,
3847 connection->inputChannel->getConnectionToken(),
3848 std::move(timeline.graphicsTimeline));
3849 }
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003850 }
3851 gotOne = true;
3852 }
3853 if (gotOne) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00003854 runCommandsLockedInterruptable();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003855 if (status == WOULD_BLOCK) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003856 return 1;
3857 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003858 }
3859
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003860 notify = status != DEAD_OBJECT || !connection->monitor;
3861 if (notify) {
3862 ALOGE("channel '%s' ~ Failed to receive finished signal. status=%s(%d)",
3863 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3864 status);
3865 }
3866 } else {
3867 // Monitor channels are never explicitly unregistered.
3868 // We do it automatically when the remote endpoint is closed so don't warn about them.
3869 const bool stillHaveWindowHandle =
3870 getWindowHandleLocked(connection->inputChannel->getConnectionToken()) != nullptr;
3871 notify = !connection->monitor && stillHaveWindowHandle;
3872 if (notify) {
3873 ALOGW("channel '%s' ~ Consumer closed input channel or an error occurred. events=0x%x",
3874 connection->getInputChannelName().c_str(), events);
3875 }
3876 }
3877
3878 // Remove the channel.
3879 removeInputChannelLocked(connection->inputChannel->getConnectionToken(), notify);
3880 return 0; // remove the callback
Michael Wrightd02c5b62014-02-10 15:10:22 -08003881}
3882
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003883void InputDispatcher::synthesizeCancelationEventsForAllConnectionsLocked(
Michael Wrightd02c5b62014-02-10 15:10:22 -08003884 const CancelationOptions& options) {
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003885 for (const auto& [token, connection] : mConnectionsByToken) {
Siarhei Vishniakou2e2ea992020-12-15 02:57:19 +00003886 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003887 }
3888}
3889
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003890void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
Michael Wrightfa13dcf2015-06-12 13:25:11 +01003891 const CancelationOptions& options) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08003892 for (const auto& [_, monitors] : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003893 for (const Monitor& monitor : monitors) {
3894 synthesizeCancelationEventsForInputChannelLocked(monitor.inputChannel, options);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003895 }
Michael Wrightfa13dcf2015-06-12 13:25:11 +01003896 }
3897}
3898
Michael Wrightd02c5b62014-02-10 15:10:22 -08003899void InputDispatcher::synthesizeCancelationEventsForInputChannelLocked(
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05003900 const std::shared_ptr<InputChannel>& channel, const CancelationOptions& options) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003901 std::shared_ptr<Connection> connection = getConnectionLocked(channel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003902 if (connection == nullptr) {
3903 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003904 }
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003905
3906 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003907}
3908
3909void InputDispatcher::synthesizeCancelationEventsForConnectionLocked(
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003910 const std::shared_ptr<Connection>& connection, const CancelationOptions& options) {
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003911 if (connection->status == Connection::Status::BROKEN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003912 return;
3913 }
3914
3915 nsecs_t currentTime = now();
3916
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003917 std::vector<std::unique_ptr<EventEntry>> cancelationEvents =
Siarhei Vishniakou00fca7c2019-10-29 13:05:57 -07003918 connection->inputState.synthesizeCancelationEvents(currentTime, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003919
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003920 if (cancelationEvents.empty()) {
3921 return;
3922 }
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003923 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
3924 ALOGD("channel '%s' ~ Synthesized %zu cancelation events to bring channel back in sync "
Siarhei Vishniakou2e3e4432023-02-09 18:34:11 -08003925 "with reality: %s, mode=%s.",
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003926 connection->getInputChannelName().c_str(), cancelationEvents.size(), options.reason,
Siarhei Vishniakou2e3e4432023-02-09 18:34:11 -08003927 ftl::enum_string(options.mode).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003928 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08003929
Arthur Hungb3307ee2021-10-14 10:57:37 +00003930 std::string reason = std::string("reason=").append(options.reason);
3931 android_log_event_list(LOGTAG_INPUT_CANCEL)
3932 << connection->getInputChannelName().c_str() << reason << LOG_ID_EVENTS;
3933
Svet Ganov5d3bc372020-01-26 23:11:07 -08003934 InputTarget target;
chaviw98318de2021-05-19 16:45:23 -05003935 sp<WindowInfoHandle> windowHandle =
Svet Ganov5d3bc372020-01-26 23:11:07 -08003936 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
3937 if (windowHandle != nullptr) {
chaviw98318de2021-05-19 16:45:23 -05003938 const WindowInfo* windowInfo = windowHandle->getInfo();
chaviw1ff3d1e2020-07-01 15:53:47 -07003939 target.setDefaultPointerTransform(windowInfo->transform);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003940 target.globalScaleFactor = windowInfo->globalScaleFactor;
3941 }
3942 target.inputChannel = connection->inputChannel;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003943 target.flags = InputTarget::Flags::DISPATCH_AS_IS;
Svet Ganov5d3bc372020-01-26 23:11:07 -08003944
hongzuo liu95785e22022-09-06 02:51:35 +00003945 const bool wasEmpty = connection->outboundQueue.empty();
3946
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003947 for (size_t i = 0; i < cancelationEvents.size(); i++) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003948 std::unique_ptr<EventEntry> cancelationEventEntry = std::move(cancelationEvents[i]);
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003949 switch (cancelationEventEntry->type) {
3950 case EventEntry::Type::KEY: {
3951 logOutboundKeyDetails("cancel - ",
3952 static_cast<const KeyEntry&>(*cancelationEventEntry));
3953 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003954 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003955 case EventEntry::Type::MOTION: {
3956 logOutboundMotionDetails("cancel - ",
3957 static_cast<const MotionEntry&>(*cancelationEventEntry));
3958 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003959 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003960 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003961 case EventEntry::Type::TOUCH_MODE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08003962 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
3963 case EventEntry::Type::DRAG: {
Prabir Pradhan99987712020-11-10 18:43:05 -08003964 LOG_ALWAYS_FATAL("Canceling %s events is not supported",
Dominik Laskowski75788452021-02-09 18:51:25 -08003965 ftl::enum_string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003966 break;
3967 }
3968 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07003969 case EventEntry::Type::DEVICE_RESET:
3970 case EventEntry::Type::SENSOR: {
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003971 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Dominik Laskowski75788452021-02-09 18:51:25 -08003972 ftl::enum_string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003973 break;
3974 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003975 }
3976
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003977 enqueueDispatchEntryLocked(connection, std::move(cancelationEventEntry), target,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003978 InputTarget::Flags::DISPATCH_AS_IS);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003979 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003980
hongzuo liu95785e22022-09-06 02:51:35 +00003981 // If the outbound queue was previously empty, start the dispatch cycle going.
3982 if (wasEmpty && !connection->outboundQueue.empty()) {
3983 startDispatchCycleLocked(currentTime, connection);
3984 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003985}
3986
Svet Ganov5d3bc372020-01-26 23:11:07 -08003987void InputDispatcher::synthesizePointerDownEventsForConnectionLocked(
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003988 const nsecs_t downTime, const std::shared_ptr<Connection>& connection,
Arthur Hungc539dbb2022-12-08 07:45:36 +00003989 ftl::Flags<InputTarget::Flags> targetFlags) {
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003990 if (connection->status == Connection::Status::BROKEN) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003991 return;
3992 }
3993
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003994 std::vector<std::unique_ptr<EventEntry>> downEvents =
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00003995 connection->inputState.synthesizePointerDownEvents(downTime);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003996
3997 if (downEvents.empty()) {
3998 return;
3999 }
4000
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004001 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08004002 ALOGD("channel '%s' ~ Synthesized %zu down events to ensure consistent event stream.",
4003 connection->getInputChannelName().c_str(), downEvents.size());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004004 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08004005
4006 InputTarget target;
chaviw98318de2021-05-19 16:45:23 -05004007 sp<WindowInfoHandle> windowHandle =
Svet Ganov5d3bc372020-01-26 23:11:07 -08004008 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
4009 if (windowHandle != nullptr) {
chaviw98318de2021-05-19 16:45:23 -05004010 const WindowInfo* windowInfo = windowHandle->getInfo();
chaviw1ff3d1e2020-07-01 15:53:47 -07004011 target.setDefaultPointerTransform(windowInfo->transform);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004012 target.globalScaleFactor = windowInfo->globalScaleFactor;
4013 }
4014 target.inputChannel = connection->inputChannel;
Arthur Hungc539dbb2022-12-08 07:45:36 +00004015 target.flags = targetFlags;
Svet Ganov5d3bc372020-01-26 23:11:07 -08004016
hongzuo liu95785e22022-09-06 02:51:35 +00004017 const bool wasEmpty = connection->outboundQueue.empty();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004018 for (std::unique_ptr<EventEntry>& downEventEntry : downEvents) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08004019 switch (downEventEntry->type) {
4020 case EventEntry::Type::MOTION: {
4021 logOutboundMotionDetails("down - ",
4022 static_cast<const MotionEntry&>(*downEventEntry));
4023 break;
4024 }
4025
4026 case EventEntry::Type::KEY:
4027 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07004028 case EventEntry::Type::TOUCH_MODE_CHANGED:
Svet Ganov5d3bc372020-01-26 23:11:07 -08004029 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08004030 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07004031 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08004032 case EventEntry::Type::SENSOR:
4033 case EventEntry::Type::DRAG: {
Svet Ganov5d3bc372020-01-26 23:11:07 -08004034 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Dominik Laskowski75788452021-02-09 18:51:25 -08004035 ftl::enum_string(downEventEntry->type).c_str());
Svet Ganov5d3bc372020-01-26 23:11:07 -08004036 break;
4037 }
4038 }
4039
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004040 enqueueDispatchEntryLocked(connection, std::move(downEventEntry), target,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08004041 InputTarget::Flags::DISPATCH_AS_IS);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004042 }
4043
hongzuo liu95785e22022-09-06 02:51:35 +00004044 // If the outbound queue was previously empty, start the dispatch cycle going.
4045 if (wasEmpty && !connection->outboundQueue.empty()) {
4046 startDispatchCycleLocked(downTime, connection);
4047 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08004048}
4049
Arthur Hungc539dbb2022-12-08 07:45:36 +00004050void InputDispatcher::synthesizeCancelationEventsForWindowLocked(
4051 const sp<WindowInfoHandle>& windowHandle, const CancelationOptions& options) {
4052 if (windowHandle != nullptr) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07004053 std::shared_ptr<Connection> wallpaperConnection =
4054 getConnectionLocked(windowHandle->getToken());
Arthur Hungc539dbb2022-12-08 07:45:36 +00004055 if (wallpaperConnection != nullptr) {
4056 synthesizeCancelationEventsForConnectionLocked(wallpaperConnection, options);
4057 }
4058 }
4059}
4060
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004061std::unique_ptr<MotionEntry> InputDispatcher::splitMotionEvent(
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08004062 const MotionEntry& originalMotionEntry, std::bitset<MAX_POINTER_ID + 1> pointerIds,
4063 nsecs_t splitDownTime) {
4064 ALOG_ASSERT(pointerIds.any());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004065
4066 uint32_t splitPointerIndexMap[MAX_POINTERS];
4067 PointerProperties splitPointerProperties[MAX_POINTERS];
4068 PointerCoords splitPointerCoords[MAX_POINTERS];
4069
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07004070 uint32_t originalPointerCount = originalMotionEntry.pointerCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004071 uint32_t splitPointerCount = 0;
4072
4073 for (uint32_t originalPointerIndex = 0; originalPointerIndex < originalPointerCount;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004074 originalPointerIndex++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004075 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07004076 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08004077 uint32_t pointerId = uint32_t(pointerProperties.id);
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08004078 if (pointerIds.test(pointerId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004079 splitPointerIndexMap[splitPointerCount] = originalPointerIndex;
Siarhei Vishniakou73e6d372023-07-06 18:07:21 -07004080 splitPointerProperties[splitPointerCount] = pointerProperties;
4081 splitPointerCoords[splitPointerCount] =
4082 originalMotionEntry.pointerCoords[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08004083 splitPointerCount += 1;
4084 }
4085 }
4086
4087 if (splitPointerCount != pointerIds.count()) {
4088 // This is bad. We are missing some of the pointers that we expected to deliver.
4089 // Most likely this indicates that we received an ACTION_MOVE events that has
4090 // different pointer ids than we expected based on the previous ACTION_DOWN
4091 // or ACTION_POINTER_DOWN events that caused us to decide to split the pointers
4092 // in this way.
4093 ALOGW("Dropping split motion event because the pointer count is %d but "
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08004094 "we expected there to be %zu pointers. This probably means we received "
Siarhei Vishniakou16e4fa02023-02-16 17:48:56 -08004095 "a broken sequence of pointer ids from the input device: %s",
4096 splitPointerCount, pointerIds.count(), originalMotionEntry.getDescription().c_str());
Yi Kong9b14ac62018-07-17 13:48:38 -07004097 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004098 }
4099
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07004100 int32_t action = originalMotionEntry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004101 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004102 if (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN ||
4103 maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
Siarhei Vishniakou5b9766d2023-07-18 14:06:29 -07004104 int32_t originalPointerIndex = MotionEvent::getActionIndex(action);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004105 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07004106 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08004107 uint32_t pointerId = uint32_t(pointerProperties.id);
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08004108 if (pointerIds.test(pointerId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004109 if (pointerIds.count() == 1) {
4110 // The first/last pointer went down/up.
4111 action = maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004112 ? AMOTION_EVENT_ACTION_DOWN
arthurhungea3f4fc2020-12-21 23:18:53 +08004113 : (originalMotionEntry.flags & AMOTION_EVENT_FLAG_CANCELED) != 0
4114 ? AMOTION_EVENT_ACTION_CANCEL
4115 : AMOTION_EVENT_ACTION_UP;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004116 } else {
4117 // A secondary pointer went down/up.
4118 uint32_t splitPointerIndex = 0;
4119 while (pointerId != uint32_t(splitPointerProperties[splitPointerIndex].id)) {
4120 splitPointerIndex += 1;
4121 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004122 action = maskedAction |
4123 (splitPointerIndex << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004124 }
4125 } else {
4126 // An unrelated pointer changed.
4127 action = AMOTION_EVENT_ACTION_MOVE;
4128 }
4129 }
4130
Siarhei Vishniakou59e302b2023-06-05 08:04:53 -07004131 if (action == AMOTION_EVENT_ACTION_DOWN && splitDownTime != originalMotionEntry.eventTime) {
4132 logDispatchStateLocked();
4133 LOG_ALWAYS_FATAL("Split motion event has mismatching downTime and eventTime for "
4134 "ACTION_DOWN, motionEntry=%s, splitDownTime=%" PRId64,
4135 originalMotionEntry.getDescription().c_str(), splitDownTime);
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00004136 }
4137
Garfield Tanff1f1bb2020-01-28 13:24:04 -08004138 int32_t newId = mIdGenerator.nextId();
4139 if (ATRACE_ENABLED()) {
4140 std::string message = StringPrintf("Split MotionEvent(id=0x%" PRIx32
4141 ") to MotionEvent(id=0x%" PRIx32 ").",
4142 originalMotionEntry.id, newId);
4143 ATRACE_NAME(message.c_str());
4144 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004145 std::unique_ptr<MotionEntry> splitMotionEntry =
4146 std::make_unique<MotionEntry>(newId, originalMotionEntry.eventTime,
4147 originalMotionEntry.deviceId, originalMotionEntry.source,
4148 originalMotionEntry.displayId,
4149 originalMotionEntry.policyFlags, action,
4150 originalMotionEntry.actionButton,
4151 originalMotionEntry.flags, originalMotionEntry.metaState,
4152 originalMotionEntry.buttonState,
4153 originalMotionEntry.classification,
4154 originalMotionEntry.edgeFlags,
4155 originalMotionEntry.xPrecision,
4156 originalMotionEntry.yPrecision,
4157 originalMotionEntry.xCursorPosition,
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00004158 originalMotionEntry.yCursorPosition, splitDownTime,
4159 splitPointerCount, splitPointerProperties,
4160 splitPointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004161
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07004162 if (originalMotionEntry.injectionState) {
4163 splitMotionEntry->injectionState = originalMotionEntry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004164 splitMotionEntry->injectionState->refCount += 1;
4165 }
4166
4167 return splitMotionEntry;
4168}
4169
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004170void InputDispatcher::notifyConfigurationChanged(const NotifyConfigurationChangedArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004171 if (debugInboundEventDetails()) {
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004172 ALOGD("notifyConfigurationChanged - eventTime=%" PRId64, args.eventTime);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004173 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004174
Antonio Kantekf16f2832021-09-28 04:39:20 +00004175 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004176 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004177 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004178
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004179 std::unique_ptr<ConfigurationChangedEntry> newEntry =
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004180 std::make_unique<ConfigurationChangedEntry>(args.id, args.eventTime);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004181 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004182 } // release lock
4183
4184 if (needWake) {
4185 mLooper->wake();
4186 }
4187}
4188
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05004189/**
4190 * If one of the meta shortcuts is detected, process them here:
Vaibhav Devmurari34cd5b02023-02-23 14:51:18 +00004191 * Meta + Backspace; Meta + Grave; Meta + Left arrow -> generate BACK
4192 * Most System shortcuts are handled in PhoneWindowManager.java except 'Back' shortcuts. Unlike
4193 * Back, other shortcuts DO NOT need to be sent to applications and are fully handled by the system.
4194 * But for Back key and Back shortcuts, we need to send KEYCODE_BACK to applications which can
4195 * potentially handle the back key presses.
4196 * Note: We don't send any Meta based KeyEvents to applications, so we need to convert to a KeyEvent
4197 * where meta modifier is off before sending. Currently only use case is 'Back'.
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05004198 */
4199void InputDispatcher::accelerateMetaShortcuts(const int32_t deviceId, const int32_t action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004200 int32_t& keyCode, int32_t& metaState) {
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05004201 if (metaState & AMETA_META_ON && action == AKEY_EVENT_ACTION_DOWN) {
4202 int32_t newKeyCode = AKEYCODE_UNKNOWN;
Vaibhav Devmurari34cd5b02023-02-23 14:51:18 +00004203 if (keyCode == AKEYCODE_DEL || keyCode == AKEYCODE_GRAVE || keyCode == AKEYCODE_DPAD_LEFT) {
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05004204 newKeyCode = AKEYCODE_BACK;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05004205 }
4206 if (newKeyCode != AKEYCODE_UNKNOWN) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004207 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05004208 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004209 mReplacedKeys[replacement] = newKeyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05004210 keyCode = newKeyCode;
4211 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
4212 }
4213 } else if (action == AKEY_EVENT_ACTION_UP) {
4214 // In order to maintain a consistent stream of up and down events, check to see if the key
4215 // going up is one we've replaced in a down event and haven't yet replaced in an up event,
4216 // even if the modifier was released between the down and the up events.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004217 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05004218 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004219 auto replacementIt = mReplacedKeys.find(replacement);
4220 if (replacementIt != mReplacedKeys.end()) {
4221 keyCode = replacementIt->second;
4222 mReplacedKeys.erase(replacementIt);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05004223 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
4224 }
4225 }
4226}
4227
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004228void InputDispatcher::notifyKey(const NotifyKeyArgs& args) {
Prabir Pradhan96282b02023-02-24 22:36:17 +00004229 ALOGD_IF(debugInboundEventDetails(),
4230 "notifyKey - id=%" PRIx32 ", eventTime=%" PRId64
4231 ", deviceId=%d, source=%s, displayId=%" PRId32
4232 "policyFlags=0x%x, action=%s, flags=0x%x, keyCode=%s, scanCode=0x%x, metaState=0x%x, "
4233 "downTime=%" PRId64,
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004234 args.id, args.eventTime, args.deviceId, inputEventSourceToString(args.source).c_str(),
4235 args.displayId, args.policyFlags, KeyEvent::actionToString(args.action), args.flags,
4236 KeyEvent::getLabel(args.keyCode), args.scanCode, args.metaState, args.downTime);
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004237 Result<void> keyCheck = validateKeyEvent(args.action);
4238 if (!keyCheck.ok()) {
4239 LOG(ERROR) << "invalid key event: " << keyCheck.error();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004240 return;
4241 }
4242
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004243 uint32_t policyFlags = args.policyFlags;
4244 int32_t flags = args.flags;
4245 int32_t metaState = args.metaState;
Siarhei Vishniakou622bd322018-10-29 18:02:27 -07004246 // InputDispatcher tracks and generates key repeats on behalf of
4247 // whatever notifies it, so repeatCount should always be set to 0
4248 constexpr int32_t repeatCount = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004249 if ((policyFlags & POLICY_FLAG_VIRTUAL) || (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY)) {
4250 policyFlags |= POLICY_FLAG_VIRTUAL;
4251 flags |= AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
4252 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004253 if (policyFlags & POLICY_FLAG_FUNCTION) {
4254 metaState |= AMETA_FUNCTION_ON;
4255 }
4256
4257 policyFlags |= POLICY_FLAG_TRUSTED;
4258
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004259 int32_t keyCode = args.keyCode;
4260 accelerateMetaShortcuts(args.deviceId, args.action, keyCode, metaState);
Michael Wright78f24442014-08-06 15:55:28 -07004261
Michael Wrightd02c5b62014-02-10 15:10:22 -08004262 KeyEvent event;
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004263 event.initialize(args.id, args.deviceId, args.source, args.displayId, INVALID_HMAC, args.action,
4264 flags, keyCode, args.scanCode, metaState, repeatCount, args.downTime,
4265 args.eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004266
Michael Wright2b3c3302018-03-02 17:19:13 +00004267 android::base::Timer t;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004268 mPolicy.interceptKeyBeforeQueueing(event, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00004269 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4270 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004271 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00004272 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004273
Antonio Kantekf16f2832021-09-28 04:39:20 +00004274 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004275 { // acquire lock
4276 mLock.lock();
4277
4278 if (shouldSendKeyToInputFilterLocked(args)) {
4279 mLock.unlock();
4280
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004281 policyFlags |= POLICY_FLAG_FILTERED;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004282 if (!mPolicy.filterInputEvent(event, policyFlags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004283 return; // event was consumed by the filter
4284 }
4285
4286 mLock.lock();
4287 }
4288
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004289 std::unique_ptr<KeyEntry> newEntry =
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004290 std::make_unique<KeyEntry>(args.id, args.eventTime, args.deviceId, args.source,
4291 args.displayId, policyFlags, args.action, flags, keyCode,
4292 args.scanCode, metaState, repeatCount, args.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004293
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004294 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004295 mLock.unlock();
4296 } // release lock
4297
4298 if (needWake) {
4299 mLooper->wake();
4300 }
4301}
4302
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004303bool InputDispatcher::shouldSendKeyToInputFilterLocked(const NotifyKeyArgs& args) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004304 return mInputFilterEnabled;
4305}
4306
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004307void InputDispatcher::notifyMotion(const NotifyMotionArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004308 if (debugInboundEventDetails()) {
Prabir Pradhan96282b02023-02-24 22:36:17 +00004309 ALOGD("notifyMotion - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=%s, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004310 "displayId=%" PRId32 ", policyFlags=0x%x, "
Siarhei Vishniakou6ebd0692022-10-20 15:05:45 -07004311 "action=%s, actionButton=0x%x, flags=0x%x, metaState=0x%x, buttonState=0x%x, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004312 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, xCursorPosition=%f, "
4313 "yCursorPosition=%f, downTime=%" PRId64,
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004314 args.id, args.eventTime, args.deviceId, inputEventSourceToString(args.source).c_str(),
4315 args.displayId, args.policyFlags, MotionEvent::actionToString(args.action).c_str(),
4316 args.actionButton, args.flags, args.metaState, args.buttonState, args.edgeFlags,
4317 args.xPrecision, args.yPrecision, args.xCursorPosition, args.yCursorPosition,
4318 args.downTime);
Siarhei Vishniakou3218fc02023-06-15 20:41:02 -07004319 for (uint32_t i = 0; i < args.getPointerCount(); i++) {
Prabir Pradhan96282b02023-02-24 22:36:17 +00004320 ALOGD(" Pointer %d: id=%d, toolType=%s, x=%f, y=%f, pressure=%f, size=%f, "
4321 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, orientation=%f",
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004322 i, args.pointerProperties[i].id,
4323 ftl::enum_string(args.pointerProperties[i].toolType).c_str(),
4324 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
4325 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
4326 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
4327 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
4328 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
4329 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
4330 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
4331 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
4332 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004333 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004334 }
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004335
Siarhei Vishniakou3218fc02023-06-15 20:41:02 -07004336 Result<void> motionCheck =
4337 validateMotionEvent(args.action, args.actionButton, args.getPointerCount(),
4338 args.pointerProperties.data());
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004339 if (!motionCheck.ok()) {
4340 LOG(FATAL) << "Invalid event: " << args.dump() << "; reason: " << motionCheck.error();
4341 return;
4342 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004343
Siarhei Vishniakou5c02a712023-05-15 15:45:02 -07004344 if (DEBUG_VERIFY_EVENTS) {
4345 auto [it, _] =
4346 mVerifiersByDisplay.try_emplace(args.displayId,
4347 StringPrintf("display %" PRId32, args.displayId));
4348 Result<void> result =
Siarhei Vishniakou3218fc02023-06-15 20:41:02 -07004349 it->second.processMovement(args.deviceId, args.action, args.getPointerCount(),
4350 args.pointerProperties.data(), args.pointerCoords.data(),
4351 args.flags);
Siarhei Vishniakou5c02a712023-05-15 15:45:02 -07004352 if (!result.ok()) {
4353 LOG(FATAL) << "Bad stream: " << result.error() << " caused by " << args.dump();
4354 }
4355 }
4356
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004357 uint32_t policyFlags = args.policyFlags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004358 policyFlags |= POLICY_FLAG_TRUSTED;
Michael Wright2b3c3302018-03-02 17:19:13 +00004359
4360 android::base::Timer t;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004361 mPolicy.interceptMotionBeforeQueueing(args.displayId, args.eventTime, policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00004362 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4363 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004364 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00004365 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004366
Antonio Kantekf16f2832021-09-28 04:39:20 +00004367 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004368 { // acquire lock
4369 mLock.lock();
Siarhei Vishniakou5bf25d92023-02-08 15:43:38 -08004370 if (!(policyFlags & POLICY_FLAG_PASS_TO_USER)) {
4371 // Set the flag anyway if we already have an ongoing gesture. That would allow us to
4372 // complete the processing of the current stroke.
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004373 const auto touchStateIt = mTouchStatesByDisplay.find(args.displayId);
Siarhei Vishniakou5bf25d92023-02-08 15:43:38 -08004374 if (touchStateIt != mTouchStatesByDisplay.end()) {
4375 const TouchState& touchState = touchStateIt->second;
Siarhei Vishniakou45504fe2023-05-05 16:05:10 -07004376 if (touchState.hasTouchingPointers(args.deviceId)) {
Siarhei Vishniakou5bf25d92023-02-08 15:43:38 -08004377 policyFlags |= POLICY_FLAG_PASS_TO_USER;
4378 }
4379 }
4380 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004381
4382 if (shouldSendMotionToInputFilterLocked(args)) {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004383 ui::Transform displayTransform;
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004384 if (const auto it = mDisplayInfos.find(args.displayId); it != mDisplayInfos.end()) {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004385 displayTransform = it->second.transform;
4386 }
4387
Michael Wrightd02c5b62014-02-10 15:10:22 -08004388 mLock.unlock();
4389
4390 MotionEvent event;
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004391 event.initialize(args.id, args.deviceId, args.source, args.displayId, INVALID_HMAC,
4392 args.action, args.actionButton, args.flags, args.edgeFlags,
4393 args.metaState, args.buttonState, args.classification,
4394 displayTransform, args.xPrecision, args.yPrecision,
4395 args.xCursorPosition, args.yCursorPosition, displayTransform,
Siarhei Vishniakou3218fc02023-06-15 20:41:02 -07004396 args.downTime, args.eventTime, args.getPointerCount(),
4397 args.pointerProperties.data(), args.pointerCoords.data());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004398
4399 policyFlags |= POLICY_FLAG_FILTERED;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004400 if (!mPolicy.filterInputEvent(event, policyFlags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004401 return; // event was consumed by the filter
4402 }
4403
4404 mLock.lock();
4405 }
4406
4407 // Just enqueue a new motion event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004408 std::unique_ptr<MotionEntry> newEntry =
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004409 std::make_unique<MotionEntry>(args.id, args.eventTime, args.deviceId, args.source,
4410 args.displayId, policyFlags, args.action,
4411 args.actionButton, args.flags, args.metaState,
4412 args.buttonState, args.classification, args.edgeFlags,
4413 args.xPrecision, args.yPrecision,
4414 args.xCursorPosition, args.yCursorPosition,
Siarhei Vishniakou3218fc02023-06-15 20:41:02 -07004415 args.downTime, args.getPointerCount(),
4416 args.pointerProperties.data(),
4417 args.pointerCoords.data());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004418
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004419 if (args.id != android::os::IInputConstants::INVALID_INPUT_EVENT_ID &&
4420 IdGenerator::getSource(args.id) == IdGenerator::Source::INPUT_READER &&
Siarhei Vishniakou363e7292021-07-09 03:22:42 +00004421 !mInputFilterEnabled) {
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004422 const bool isDown = args.action == AMOTION_EVENT_ACTION_DOWN;
4423 mLatencyTracker.trackListener(args.id, isDown, args.eventTime, args.readTime);
Siarhei Vishniakou363e7292021-07-09 03:22:42 +00004424 }
4425
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004426 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004427 mLock.unlock();
4428 } // release lock
4429
4430 if (needWake) {
4431 mLooper->wake();
4432 }
4433}
4434
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004435void InputDispatcher::notifySensor(const NotifySensorArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004436 if (debugInboundEventDetails()) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004437 ALOGD("notifySensor - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=0x%x, "
4438 " sensorType=%s",
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004439 args.id, args.eventTime, args.deviceId, args.source,
4440 ftl::enum_string(args.sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004441 }
Chris Yef59a2f42020-10-16 12:55:26 -07004442
Antonio Kantekf16f2832021-09-28 04:39:20 +00004443 bool needWake = false;
Chris Yef59a2f42020-10-16 12:55:26 -07004444 { // acquire lock
4445 mLock.lock();
4446
4447 // Just enqueue a new sensor event.
4448 std::unique_ptr<SensorEntry> newEntry =
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004449 std::make_unique<SensorEntry>(args.id, args.eventTime, args.deviceId, args.source,
4450 /* policyFlags=*/0, args.hwTimestamp, args.sensorType,
4451 args.accuracy, args.accuracyChanged, args.values);
Chris Yef59a2f42020-10-16 12:55:26 -07004452
4453 needWake = enqueueInboundEventLocked(std::move(newEntry));
4454 mLock.unlock();
4455 } // release lock
4456
4457 if (needWake) {
4458 mLooper->wake();
4459 }
4460}
4461
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004462void InputDispatcher::notifyVibratorState(const NotifyVibratorStateArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004463 if (debugInboundEventDetails()) {
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004464 ALOGD("notifyVibratorState - eventTime=%" PRId64 ", device=%d, isOn=%d", args.eventTime,
4465 args.deviceId, args.isOn);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004466 }
Prabir Pradhana41d2442023-04-20 21:30:40 +00004467 mPolicy.notifyVibratorState(args.deviceId, args.isOn);
Chris Yefb552902021-02-03 17:18:37 -08004468}
4469
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004470bool InputDispatcher::shouldSendMotionToInputFilterLocked(const NotifyMotionArgs& args) {
Jackal Guof9696682018-10-05 12:23:23 +08004471 return mInputFilterEnabled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004472}
4473
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004474void InputDispatcher::notifySwitch(const NotifySwitchArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004475 if (debugInboundEventDetails()) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004476 ALOGD("notifySwitch - eventTime=%" PRId64 ", policyFlags=0x%x, switchValues=0x%08x, "
4477 "switchMask=0x%08x",
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004478 args.eventTime, args.policyFlags, args.switchValues, args.switchMask);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004479 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004480
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004481 uint32_t policyFlags = args.policyFlags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004482 policyFlags |= POLICY_FLAG_TRUSTED;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004483 mPolicy.notifySwitch(args.eventTime, args.switchValues, args.switchMask, policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004484}
4485
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004486void InputDispatcher::notifyDeviceReset(const NotifyDeviceResetArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004487 if (debugInboundEventDetails()) {
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004488 ALOGD("notifyDeviceReset - eventTime=%" PRId64 ", deviceId=%d", args.eventTime,
4489 args.deviceId);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004490 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004491
Antonio Kantekf16f2832021-09-28 04:39:20 +00004492 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004493 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004494 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004495
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004496 std::unique_ptr<DeviceResetEntry> newEntry =
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004497 std::make_unique<DeviceResetEntry>(args.id, args.eventTime, args.deviceId);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004498 needWake = enqueueInboundEventLocked(std::move(newEntry));
Siarhei Vishniakou1160ecd2023-06-28 15:57:47 -07004499
4500 for (auto& [_, verifier] : mVerifiersByDisplay) {
4501 verifier.resetDevice(args.deviceId);
4502 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004503 } // release lock
4504
4505 if (needWake) {
4506 mLooper->wake();
4507 }
4508}
4509
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004510void InputDispatcher::notifyPointerCaptureChanged(const NotifyPointerCaptureChangedArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004511 if (debugInboundEventDetails()) {
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004512 ALOGD("notifyPointerCaptureChanged - eventTime=%" PRId64 ", enabled=%s", args.eventTime,
4513 args.request.enable ? "true" : "false");
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004514 }
Prabir Pradhan7e186182020-11-10 13:56:45 -08004515
Antonio Kantekf16f2832021-09-28 04:39:20 +00004516 bool needWake = false;
Prabir Pradhan99987712020-11-10 18:43:05 -08004517 { // acquire lock
4518 std::scoped_lock _l(mLock);
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004519 auto entry =
4520 std::make_unique<PointerCaptureChangedEntry>(args.id, args.eventTime, args.request);
Prabir Pradhan99987712020-11-10 18:43:05 -08004521 needWake = enqueueInboundEventLocked(std::move(entry));
4522 } // release lock
4523
4524 if (needWake) {
4525 mLooper->wake();
4526 }
Prabir Pradhan7e186182020-11-10 13:56:45 -08004527}
4528
Prabir Pradhan5735a322022-04-11 17:23:34 +00004529InputEventInjectionResult InputDispatcher::injectInputEvent(const InputEvent* event,
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00004530 std::optional<gui::Uid> targetUid,
Prabir Pradhan5735a322022-04-11 17:23:34 +00004531 InputEventInjectionSync syncMode,
4532 std::chrono::milliseconds timeout,
4533 uint32_t policyFlags) {
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004534 Result<void> eventValidation = validateInputEvent(*event);
4535 if (!eventValidation.ok()) {
4536 LOG(INFO) << "Injection failed: invalid event: " << eventValidation.error();
4537 return InputEventInjectionResult::FAILED;
4538 }
4539
Prabir Pradhan65613802023-02-22 23:36:58 +00004540 if (debugInboundEventDetails()) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07004541 LOG(INFO) << __func__ << ": targetUid=" << toString(targetUid, &uidString)
4542 << ", syncMode=" << ftl::enum_string(syncMode) << ", timeout=" << timeout.count()
4543 << "ms, policyFlags=0x" << std::hex << policyFlags << std::dec
4544 << ", event=" << *event;
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004545 }
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07004546 nsecs_t endTime = now() + std::chrono::duration_cast<std::chrono::nanoseconds>(timeout).count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004547
Prabir Pradhan5735a322022-04-11 17:23:34 +00004548 policyFlags |= POLICY_FLAG_INJECTED | POLICY_FLAG_TRUSTED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004549
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004550 // For all injected events, set device id = VIRTUAL_KEYBOARD_ID. The only exception is events
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004551 // that have gone through the InputFilter. If the event passed through the InputFilter, assign
4552 // the provided device id. If the InputFilter is accessibility, and it modifies or synthesizes
4553 // the injected event, it is responsible for setting POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY.
4554 // For those events, we will set FLAG_IS_ACCESSIBILITY_EVENT to allow apps to distinguish them
4555 // from events that originate from actual hardware.
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004556 int32_t resolvedDeviceId = VIRTUAL_KEYBOARD_ID;
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004557 if (policyFlags & POLICY_FLAG_FILTERED) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004558 resolvedDeviceId = event->getDeviceId();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004559 }
4560
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004561 std::queue<std::unique_ptr<EventEntry>> injectedEntries;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004562 switch (event->getType()) {
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004563 case InputEventType::KEY: {
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004564 const KeyEvent& incomingKey = static_cast<const KeyEvent&>(*event);
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004565 const int32_t action = incomingKey.getAction();
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004566 int32_t flags = incomingKey.getFlags();
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004567 if (policyFlags & POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY) {
4568 flags |= AKEY_EVENT_FLAG_IS_ACCESSIBILITY_EVENT;
4569 }
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004570 int32_t keyCode = incomingKey.getKeyCode();
4571 int32_t metaState = incomingKey.getMetaState();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004572 accelerateMetaShortcuts(resolvedDeviceId, action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004573 /*byref*/ keyCode, /*byref*/ metaState);
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004574 KeyEvent keyEvent;
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004575 keyEvent.initialize(incomingKey.getId(), resolvedDeviceId, incomingKey.getSource(),
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004576 incomingKey.getDisplayId(), INVALID_HMAC, action, flags, keyCode,
4577 incomingKey.getScanCode(), metaState, incomingKey.getRepeatCount(),
4578 incomingKey.getDownTime(), incomingKey.getEventTime());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004579
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004580 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
4581 policyFlags |= POLICY_FLAG_VIRTUAL;
Michael Wright2b3c3302018-03-02 17:19:13 +00004582 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004583
4584 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
4585 android::base::Timer t;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004586 mPolicy.interceptKeyBeforeQueueing(keyEvent, /*byref*/ policyFlags);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004587 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4588 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
4589 std::to_string(t.duration().count()).c_str());
4590 }
4591 }
4592
4593 mLock.lock();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004594 std::unique_ptr<KeyEntry> injectedEntry =
4595 std::make_unique<KeyEntry>(incomingKey.getId(), incomingKey.getEventTime(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004596 resolvedDeviceId, incomingKey.getSource(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004597 incomingKey.getDisplayId(), policyFlags, action,
4598 flags, keyCode, incomingKey.getScanCode(), metaState,
4599 incomingKey.getRepeatCount(),
4600 incomingKey.getDownTime());
4601 injectedEntries.push(std::move(injectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004602 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004603 }
4604
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004605 case InputEventType::MOTION: {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004606 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(*event);
Prabir Pradhanaa561d12021-09-24 06:57:33 -07004607 const bool isPointerEvent =
4608 isFromSource(event->getSource(), AINPUT_SOURCE_CLASS_POINTER);
4609 // If a pointer event has no displayId specified, inject it to the default display.
4610 const uint32_t displayId = isPointerEvent && (event->getDisplayId() == ADISPLAY_ID_NONE)
4611 ? ADISPLAY_ID_DEFAULT
4612 : event->getDisplayId();
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004613 int32_t flags = motionEvent.getFlags();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004614
4615 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004616 nsecs_t eventTime = motionEvent.getEventTime();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004617 android::base::Timer t;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004618 mPolicy.interceptMotionBeforeQueueing(displayId, eventTime, /*byref*/ policyFlags);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004619 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4620 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
4621 std::to_string(t.duration().count()).c_str());
4622 }
4623 }
4624
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004625 if (policyFlags & POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY) {
4626 flags |= AMOTION_EVENT_FLAG_IS_ACCESSIBILITY_EVENT;
4627 }
4628
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004629 mLock.lock();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004630 const nsecs_t* sampleEventTimes = motionEvent.getSampleEventTimes();
4631 const PointerCoords* samplePointerCoords = motionEvent.getSamplePointerCoords();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004632 std::unique_ptr<MotionEntry> injectedEntry =
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004633 std::make_unique<MotionEntry>(motionEvent.getId(), *sampleEventTimes,
4634 resolvedDeviceId, motionEvent.getSource(),
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004635 displayId, policyFlags, motionEvent.getAction(),
4636 motionEvent.getActionButton(), flags,
4637 motionEvent.getMetaState(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004638 motionEvent.getButtonState(),
4639 motionEvent.getClassification(),
4640 motionEvent.getEdgeFlags(),
4641 motionEvent.getXPrecision(),
4642 motionEvent.getYPrecision(),
4643 motionEvent.getRawXCursorPosition(),
4644 motionEvent.getRawYCursorPosition(),
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004645 motionEvent.getDownTime(),
4646 motionEvent.getPointerCount(),
4647 motionEvent.getPointerProperties(),
4648 samplePointerCoords);
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004649 transformMotionEntryForInjectionLocked(*injectedEntry, motionEvent.getTransform());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004650 injectedEntries.push(std::move(injectedEntry));
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004651 for (size_t i = motionEvent.getHistorySize(); i > 0; i--) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004652 sampleEventTimes += 1;
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004653 samplePointerCoords += motionEvent.getPointerCount();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004654 std::unique_ptr<MotionEntry> nextInjectedEntry =
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004655 std::make_unique<MotionEntry>(motionEvent.getId(), *sampleEventTimes,
4656 resolvedDeviceId, motionEvent.getSource(),
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004657 displayId, policyFlags,
4658 motionEvent.getAction(),
4659 motionEvent.getActionButton(), flags,
4660 motionEvent.getMetaState(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004661 motionEvent.getButtonState(),
4662 motionEvent.getClassification(),
4663 motionEvent.getEdgeFlags(),
4664 motionEvent.getXPrecision(),
4665 motionEvent.getYPrecision(),
4666 motionEvent.getRawXCursorPosition(),
4667 motionEvent.getRawYCursorPosition(),
4668 motionEvent.getDownTime(),
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004669 motionEvent.getPointerCount(),
4670 motionEvent.getPointerProperties(),
Prabir Pradhan5beda762021-12-10 09:30:08 +00004671 samplePointerCoords);
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004672 transformMotionEntryForInjectionLocked(*nextInjectedEntry,
4673 motionEvent.getTransform());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004674 injectedEntries.push(std::move(nextInjectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004675 }
4676 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004677 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004678
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004679 default:
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004680 LOG(WARNING) << "Cannot inject " << ftl::enum_string(event->getType()) << " events";
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004681 return InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004682 }
4683
Prabir Pradhan5735a322022-04-11 17:23:34 +00004684 InjectionState* injectionState = new InjectionState(targetUid);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004685 if (syncMode == InputEventInjectionSync::NONE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004686 injectionState->injectionIsAsync = true;
4687 }
4688
4689 injectionState->refCount += 1;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004690 injectedEntries.back()->injectionState = injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004691
4692 bool needWake = false;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004693 while (!injectedEntries.empty()) {
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08004694 if (DEBUG_INJECTION) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07004695 LOG(INFO) << "Injecting " << injectedEntries.front()->getDescription();
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08004696 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004697 needWake |= enqueueInboundEventLocked(std::move(injectedEntries.front()));
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004698 injectedEntries.pop();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004699 }
4700
4701 mLock.unlock();
4702
4703 if (needWake) {
4704 mLooper->wake();
4705 }
4706
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004707 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004708 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004709 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004710
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004711 if (syncMode == InputEventInjectionSync::NONE) {
4712 injectionResult = InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004713 } else {
4714 for (;;) {
4715 injectionResult = injectionState->injectionResult;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004716 if (injectionResult != InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004717 break;
4718 }
4719
4720 nsecs_t remainingTimeout = endTime - now();
4721 if (remainingTimeout <= 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004722 if (DEBUG_INJECTION) {
4723 ALOGD("injectInputEvent - Timed out waiting for injection result "
4724 "to become available.");
4725 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004726 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004727 break;
4728 }
4729
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004730 mInjectionResultAvailable.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004731 }
4732
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004733 if (injectionResult == InputEventInjectionResult::SUCCEEDED &&
4734 syncMode == InputEventInjectionSync::WAIT_FOR_FINISHED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004735 while (injectionState->pendingForegroundDispatches != 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004736 if (DEBUG_INJECTION) {
4737 ALOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
4738 injectionState->pendingForegroundDispatches);
4739 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004740 nsecs_t remainingTimeout = endTime - now();
4741 if (remainingTimeout <= 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004742 if (DEBUG_INJECTION) {
4743 ALOGD("injectInputEvent - Timed out waiting for pending foreground "
4744 "dispatches to finish.");
4745 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004746 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004747 break;
4748 }
4749
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004750 mInjectionSyncFinished.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004751 }
4752 }
4753 }
4754
4755 injectionState->release();
4756 } // release lock
4757
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004758 if (DEBUG_INJECTION) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07004759 LOG(INFO) << "injectInputEvent - Finished with result "
4760 << ftl::enum_string(injectionResult);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004761 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004762
4763 return injectionResult;
4764}
4765
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004766std::unique_ptr<VerifiedInputEvent> InputDispatcher::verifyInputEvent(const InputEvent& event) {
Gang Wange9087892020-01-07 12:17:14 -05004767 std::array<uint8_t, 32> calculatedHmac;
4768 std::unique_ptr<VerifiedInputEvent> result;
4769 switch (event.getType()) {
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004770 case InputEventType::KEY: {
Gang Wange9087892020-01-07 12:17:14 -05004771 const KeyEvent& keyEvent = static_cast<const KeyEvent&>(event);
4772 VerifiedKeyEvent verifiedKeyEvent = verifiedKeyEventFromKeyEvent(keyEvent);
4773 result = std::make_unique<VerifiedKeyEvent>(verifiedKeyEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004774 calculatedHmac = sign(verifiedKeyEvent);
Gang Wange9087892020-01-07 12:17:14 -05004775 break;
4776 }
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004777 case InputEventType::MOTION: {
Gang Wange9087892020-01-07 12:17:14 -05004778 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(event);
4779 VerifiedMotionEvent verifiedMotionEvent =
4780 verifiedMotionEventFromMotionEvent(motionEvent);
4781 result = std::make_unique<VerifiedMotionEvent>(verifiedMotionEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004782 calculatedHmac = sign(verifiedMotionEvent);
Gang Wange9087892020-01-07 12:17:14 -05004783 break;
4784 }
4785 default: {
4786 ALOGE("Cannot verify events of type %" PRId32, event.getType());
4787 return nullptr;
4788 }
4789 }
4790 if (calculatedHmac == INVALID_HMAC) {
4791 return nullptr;
4792 }
tyiu1573a672023-02-21 22:38:32 +00004793 if (0 != CRYPTO_memcmp(calculatedHmac.data(), event.getHmac().data(), calculatedHmac.size())) {
Gang Wange9087892020-01-07 12:17:14 -05004794 return nullptr;
4795 }
4796 return result;
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004797}
4798
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004799void InputDispatcher::setInjectionResult(EventEntry& entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004800 InputEventInjectionResult injectionResult) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004801 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004802 if (injectionState) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004803 if (DEBUG_INJECTION) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07004804 LOG(INFO) << "Setting input event injection result to "
4805 << ftl::enum_string(injectionResult);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004806 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004807
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004808 if (injectionState->injectionIsAsync && !(entry.policyFlags & POLICY_FLAG_FILTERED)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004809 // Log the outcome since the injector did not wait for the injection result.
4810 switch (injectionResult) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004811 case InputEventInjectionResult::SUCCEEDED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004812 ALOGV("Asynchronous input event injection succeeded.");
4813 break;
Prabir Pradhan5735a322022-04-11 17:23:34 +00004814 case InputEventInjectionResult::TARGET_MISMATCH:
4815 ALOGV("Asynchronous input event injection target mismatch.");
4816 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004817 case InputEventInjectionResult::FAILED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004818 ALOGW("Asynchronous input event injection failed.");
4819 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004820 case InputEventInjectionResult::TIMED_OUT:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004821 ALOGW("Asynchronous input event injection timed out.");
4822 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004823 case InputEventInjectionResult::PENDING:
4824 ALOGE("Setting result to 'PENDING' for asynchronous injection");
4825 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004826 }
4827 }
4828
4829 injectionState->injectionResult = injectionResult;
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004830 mInjectionResultAvailable.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004831 }
4832}
4833
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004834void InputDispatcher::transformMotionEntryForInjectionLocked(
4835 MotionEntry& entry, const ui::Transform& injectedTransform) const {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004836 // Input injection works in the logical display coordinate space, but the input pipeline works
4837 // display space, so we need to transform the injected events accordingly.
4838 const auto it = mDisplayInfos.find(entry.displayId);
4839 if (it == mDisplayInfos.end()) return;
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004840 const auto& transformToDisplay = it->second.transform.inverse() * injectedTransform;
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004841
Prabir Pradhand9a2ebe2022-07-20 19:25:13 +00004842 if (entry.xCursorPosition != AMOTION_EVENT_INVALID_CURSOR_POSITION &&
4843 entry.yCursorPosition != AMOTION_EVENT_INVALID_CURSOR_POSITION) {
4844 const vec2 cursor =
4845 MotionEvent::calculateTransformedXY(entry.source, transformToDisplay,
4846 {entry.xCursorPosition, entry.yCursorPosition});
4847 entry.xCursorPosition = cursor.x;
4848 entry.yCursorPosition = cursor.y;
4849 }
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004850 for (uint32_t i = 0; i < entry.pointerCount; i++) {
Prabir Pradhan8e6ce222022-02-24 09:08:54 -08004851 entry.pointerCoords[i] =
4852 MotionEvent::calculateTransformedCoords(entry.source, transformToDisplay,
4853 entry.pointerCoords[i]);
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004854 }
4855}
4856
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004857void InputDispatcher::incrementPendingForegroundDispatches(EventEntry& entry) {
4858 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004859 if (injectionState) {
4860 injectionState->pendingForegroundDispatches += 1;
4861 }
4862}
4863
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004864void InputDispatcher::decrementPendingForegroundDispatches(EventEntry& entry) {
4865 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004866 if (injectionState) {
4867 injectionState->pendingForegroundDispatches -= 1;
4868
4869 if (injectionState->pendingForegroundDispatches == 0) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004870 mInjectionSyncFinished.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004871 }
4872 }
4873}
4874
chaviw98318de2021-05-19 16:45:23 -05004875const std::vector<sp<WindowInfoHandle>>& InputDispatcher::getWindowHandlesLocked(
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004876 int32_t displayId) const {
chaviw98318de2021-05-19 16:45:23 -05004877 static const std::vector<sp<WindowInfoHandle>> EMPTY_WINDOW_HANDLES;
Vishnu Nairad321cd2020-08-20 16:40:21 -07004878 auto it = mWindowHandlesByDisplay.find(displayId);
4879 return it != mWindowHandlesByDisplay.end() ? it->second : EMPTY_WINDOW_HANDLES;
Arthur Hungb92218b2018-08-14 12:00:21 +08004880}
4881
chaviw98318de2021-05-19 16:45:23 -05004882sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(
chaviwfbe5d9c2018-12-26 12:23:37 -08004883 const sp<IBinder>& windowHandleToken) const {
arthurhungbe737672020-06-24 12:29:21 +08004884 if (windowHandleToken == nullptr) {
4885 return nullptr;
4886 }
4887
Arthur Hungb92218b2018-08-14 12:00:21 +08004888 for (auto& it : mWindowHandlesByDisplay) {
chaviw98318de2021-05-19 16:45:23 -05004889 const std::vector<sp<WindowInfoHandle>>& windowHandles = it.second;
4890 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
chaviwfbe5d9c2018-12-26 12:23:37 -08004891 if (windowHandle->getToken() == windowHandleToken) {
Arthur Hungb92218b2018-08-14 12:00:21 +08004892 return windowHandle;
4893 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004894 }
4895 }
Yi Kong9b14ac62018-07-17 13:48:38 -07004896 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004897}
4898
chaviw98318de2021-05-19 16:45:23 -05004899sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(const sp<IBinder>& windowHandleToken,
4900 int displayId) const {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004901 if (windowHandleToken == nullptr) {
4902 return nullptr;
4903 }
4904
chaviw98318de2021-05-19 16:45:23 -05004905 for (const sp<WindowInfoHandle>& windowHandle : getWindowHandlesLocked(displayId)) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004906 if (windowHandle->getToken() == windowHandleToken) {
4907 return windowHandle;
4908 }
4909 }
4910 return nullptr;
4911}
4912
chaviw98318de2021-05-19 16:45:23 -05004913sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(
4914 const sp<WindowInfoHandle>& windowHandle) const {
Mady Mellor017bcd12020-06-23 19:12:00 +00004915 for (auto& it : mWindowHandlesByDisplay) {
chaviw98318de2021-05-19 16:45:23 -05004916 const std::vector<sp<WindowInfoHandle>>& windowHandles = it.second;
4917 for (const sp<WindowInfoHandle>& handle : windowHandles) {
arthurhungbe737672020-06-24 12:29:21 +08004918 if (handle->getId() == windowHandle->getId() &&
4919 handle->getToken() == windowHandle->getToken()) {
Mady Mellor017bcd12020-06-23 19:12:00 +00004920 if (windowHandle->getInfo()->displayId != it.first) {
4921 ALOGE("Found window %s in display %" PRId32
4922 ", but it should belong to display %" PRId32,
4923 windowHandle->getName().c_str(), it.first,
4924 windowHandle->getInfo()->displayId);
4925 }
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004926 return handle;
Arthur Hungb92218b2018-08-14 12:00:21 +08004927 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004928 }
4929 }
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004930 return nullptr;
4931}
4932
chaviw98318de2021-05-19 16:45:23 -05004933sp<WindowInfoHandle> InputDispatcher::getFocusedWindowHandleLocked(int displayId) const {
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004934 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(displayId);
4935 return getWindowHandleLocked(focusedToken, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004936}
4937
Prabir Pradhan33e3baa2022-12-06 20:30:22 +00004938ui::Transform InputDispatcher::getTransformLocked(int32_t displayId) const {
4939 auto displayInfoIt = mDisplayInfos.find(displayId);
4940 return displayInfoIt != mDisplayInfos.end() ? displayInfoIt->second.transform
4941 : kIdentityTransform;
4942}
4943
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004944bool InputDispatcher::canWindowReceiveMotionLocked(const sp<WindowInfoHandle>& window,
4945 const MotionEntry& motionEntry) const {
4946 const WindowInfo& info = *window->getInfo();
4947
4948 // Skip spy window targets that are not valid for targeted injection.
4949 if (const auto err = verifyTargetedInjection(window, motionEntry); err) {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004950 return false;
4951 }
4952
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004953 if (info.inputConfig.test(WindowInfo::InputConfig::PAUSE_DISPATCHING)) {
4954 ALOGI("Not sending touch event to %s because it is paused", window->getName().c_str());
4955 return false;
4956 }
4957
4958 if (info.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL)) {
4959 ALOGW("Not sending touch gesture to %s because it has config NO_INPUT_CHANNEL",
4960 window->getName().c_str());
4961 return false;
4962 }
4963
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07004964 std::shared_ptr<Connection> connection = getConnectionLocked(window->getToken());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004965 if (connection == nullptr) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004966 ALOGW("Not sending touch to %s because there's no corresponding connection",
4967 window->getName().c_str());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004968 return false;
4969 }
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004970
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004971 if (!connection->responsive) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004972 ALOGW("Not sending touch to %s because it is not responsive", window->getName().c_str());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004973 return false;
4974 }
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004975
4976 // Drop events that can't be trusted due to occlusion
4977 const auto [x, y] = resolveTouchedPosition(motionEntry);
4978 TouchOcclusionInfo occlusionInfo = computeTouchOcclusionInfoLocked(window, x, y);
4979 if (!isTouchTrustedLocked(occlusionInfo)) {
4980 if (DEBUG_TOUCH_OCCLUSION) {
Prabir Pradhan82e081e2022-12-06 09:50:09 +00004981 ALOGD("Stack of obscuring windows during untrusted touch (%.1f, %.1f):", x, y);
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004982 for (const auto& log : occlusionInfo.debugInfo) {
4983 ALOGD("%s", log.c_str());
4984 }
4985 }
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00004986 ALOGW("Dropping untrusted touch event due to %s/%s", occlusionInfo.obscuringPackage.c_str(),
4987 occlusionInfo.obscuringUid.toString().c_str());
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004988 return false;
4989 }
4990
4991 // Drop touch events if requested by input feature
4992 if (shouldDropInput(motionEntry, window)) {
4993 return false;
4994 }
4995
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004996 return true;
4997}
4998
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004999std::shared_ptr<InputChannel> InputDispatcher::getInputChannelLocked(
5000 const sp<IBinder>& token) const {
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005001 auto connectionIt = mConnectionsByToken.find(token);
5002 if (connectionIt == mConnectionsByToken.end()) {
Robert Carr5c8a0262018-10-03 16:30:44 -07005003 return nullptr;
5004 }
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005005 return connectionIt->second->inputChannel;
Robert Carr5c8a0262018-10-03 16:30:44 -07005006}
5007
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005008void InputDispatcher::updateWindowHandlesForDisplayLocked(
chaviw98318de2021-05-19 16:45:23 -05005009 const std::vector<sp<WindowInfoHandle>>& windowInfoHandles, int32_t displayId) {
5010 if (windowInfoHandles.empty()) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005011 // Remove all handles on a display if there are no windows left.
5012 mWindowHandlesByDisplay.erase(displayId);
5013 return;
5014 }
5015
5016 // Since we compare the pointer of input window handles across window updates, we need
5017 // to make sure the handle object for the same window stays unchanged across updates.
chaviw98318de2021-05-19 16:45:23 -05005018 const std::vector<sp<WindowInfoHandle>>& oldHandles = getWindowHandlesLocked(displayId);
5019 std::unordered_map<int32_t /*id*/, sp<WindowInfoHandle>> oldHandlesById;
5020 for (const sp<WindowInfoHandle>& handle : oldHandles) {
chaviwaf87b3e2019-10-01 16:59:28 -07005021 oldHandlesById[handle->getId()] = handle;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005022 }
5023
chaviw98318de2021-05-19 16:45:23 -05005024 std::vector<sp<WindowInfoHandle>> newHandles;
5025 for (const sp<WindowInfoHandle>& handle : windowInfoHandles) {
chaviw98318de2021-05-19 16:45:23 -05005026 const WindowInfo* info = handle->getInfo();
Siarhei Vishniakou64452932020-11-06 17:51:32 -06005027 if (getInputChannelLocked(handle->getToken()) == nullptr) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005028 const bool noInputChannel =
Prabir Pradhan51e7db02022-02-07 06:02:57 -08005029 info->inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005030 const bool canReceiveInput =
5031 !info->inputConfig.test(WindowInfo::InputConfig::NOT_TOUCHABLE) ||
5032 !info->inputConfig.test(WindowInfo::InputConfig::NOT_FOCUSABLE);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005033 if (canReceiveInput && !noInputChannel) {
John Recke0710582019-09-26 13:46:12 -07005034 ALOGV("Window handle %s has no registered input channel",
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005035 handle->getName().c_str());
Robert Carr2984b7a2020-04-13 17:06:45 -07005036 continue;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005037 }
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005038 }
5039
5040 if (info->displayId != displayId) {
5041 ALOGE("Window %s updated by wrong display %d, should belong to display %d",
5042 handle->getName().c_str(), displayId, info->displayId);
5043 continue;
5044 }
5045
Robert Carredd13602020-04-13 17:24:34 -07005046 if ((oldHandlesById.find(handle->getId()) != oldHandlesById.end()) &&
5047 (oldHandlesById.at(handle->getId())->getToken() == handle->getToken())) {
chaviw98318de2021-05-19 16:45:23 -05005048 const sp<WindowInfoHandle>& oldHandle = oldHandlesById.at(handle->getId());
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005049 oldHandle->updateFrom(handle);
5050 newHandles.push_back(oldHandle);
5051 } else {
5052 newHandles.push_back(handle);
5053 }
5054 }
5055
5056 // Insert or replace
5057 mWindowHandlesByDisplay[displayId] = newHandles;
5058}
5059
Arthur Hungb92218b2018-08-14 12:00:21 +08005060/**
5061 * Called from InputManagerService, update window handle list by displayId that can receive input.
5062 * A window handle contains information about InputChannel, Touch Region, Types, Focused,...
5063 * If set an empty list, remove all handles from the specific display.
5064 * For focused handle, check if need to change and send a cancel event to previous one.
5065 * For removed handle, check if need to send a cancel event if already in touch.
5066 */
Arthur Hung72d8dc32020-03-28 00:48:39 +00005067void InputDispatcher::setInputWindowsLocked(
chaviw98318de2021-05-19 16:45:23 -05005068 const std::vector<sp<WindowInfoHandle>>& windowInfoHandles, int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005069 if (DEBUG_FOCUS) {
5070 std::string windowList;
chaviw98318de2021-05-19 16:45:23 -05005071 for (const sp<WindowInfoHandle>& iwh : windowInfoHandles) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005072 windowList += iwh->getName() + " ";
5073 }
5074 ALOGD("setInputWindows displayId=%" PRId32 " %s", displayId, windowList.c_str());
5075 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005076
Prabir Pradhand65552b2021-10-07 11:23:50 -07005077 // Check preconditions for new input windows
chaviw98318de2021-05-19 16:45:23 -05005078 for (const sp<WindowInfoHandle>& window : windowInfoHandles) {
Prabir Pradhand65552b2021-10-07 11:23:50 -07005079 const WindowInfo& info = *window->getInfo();
5080
5081 // Ensure all tokens are null if the window has feature NO_INPUT_CHANNEL
Prabir Pradhan51e7db02022-02-07 06:02:57 -08005082 const bool noInputWindow = info.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005083 if (noInputWindow && window->getToken() != nullptr) {
5084 ALOGE("%s has feature NO_INPUT_WINDOW, but a non-null token. Clearing",
5085 window->getName().c_str());
5086 window->releaseChannel();
5087 }
Prabir Pradhand65552b2021-10-07 11:23:50 -07005088
Prabir Pradhan5c85e052021-12-22 02:27:12 -08005089 // Ensure all spy windows are trusted overlays
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005090 LOG_ALWAYS_FATAL_IF(info.isSpy() &&
5091 !info.inputConfig.test(
5092 WindowInfo::InputConfig::TRUSTED_OVERLAY),
Prabir Pradhan5c85e052021-12-22 02:27:12 -08005093 "%s has feature SPY, but is not a trusted overlay.",
5094 window->getName().c_str());
5095
Prabir Pradhand65552b2021-10-07 11:23:50 -07005096 // Ensure all stylus interceptors are trusted overlays
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005097 LOG_ALWAYS_FATAL_IF(info.interceptsStylus() &&
5098 !info.inputConfig.test(
5099 WindowInfo::InputConfig::TRUSTED_OVERLAY),
Prabir Pradhand65552b2021-10-07 11:23:50 -07005100 "%s has feature INTERCEPTS_STYLUS, but is not a trusted overlay.",
5101 window->getName().c_str());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005102 }
5103
Arthur Hung72d8dc32020-03-28 00:48:39 +00005104 // Copy old handles for release if they are no longer present.
chaviw98318de2021-05-19 16:45:23 -05005105 const std::vector<sp<WindowInfoHandle>> oldWindowHandles = getWindowHandlesLocked(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005106
chaviw98318de2021-05-19 16:45:23 -05005107 updateWindowHandlesForDisplayLocked(windowInfoHandles, displayId);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005108
chaviw98318de2021-05-19 16:45:23 -05005109 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Arthur Hung72d8dc32020-03-28 00:48:39 +00005110
Vishnu Nairc519ff72021-01-21 08:23:08 -08005111 std::optional<FocusResolver::FocusChanges> changes =
5112 mFocusResolver.setInputWindows(displayId, windowHandles);
5113 if (changes) {
5114 onFocusChangedLocked(*changes);
Arthur Hung72d8dc32020-03-28 00:48:39 +00005115 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005116
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005117 std::unordered_map<int32_t, TouchState>::iterator stateIt =
5118 mTouchStatesByDisplay.find(displayId);
5119 if (stateIt != mTouchStatesByDisplay.end()) {
5120 TouchState& state = stateIt->second;
Arthur Hung72d8dc32020-03-28 00:48:39 +00005121 for (size_t i = 0; i < state.windows.size();) {
5122 TouchedWindow& touchedWindow = state.windows[i];
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07005123 if (getWindowHandleLocked(touchedWindow.windowHandle) == nullptr) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005124 if (DEBUG_FOCUS) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00005125 ALOGD("Touched window was removed: %s in display %" PRId32,
5126 touchedWindow.windowHandle->getName().c_str(), displayId);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005127 }
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005128 std::shared_ptr<InputChannel> touchedInputChannel =
Arthur Hung72d8dc32020-03-28 00:48:39 +00005129 getInputChannelLocked(touchedWindow.windowHandle->getToken());
5130 if (touchedInputChannel != nullptr) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00005131 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
Arthur Hung72d8dc32020-03-28 00:48:39 +00005132 "touched window was removed");
5133 synthesizeCancelationEventsForInputChannelLocked(touchedInputChannel, options);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00005134 // Since we are about to drop the touch, cancel the events for the wallpaper as
5135 // well.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005136 if (touchedWindow.targetFlags.test(InputTarget::Flags::FOREGROUND) &&
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005137 touchedWindow.windowHandle->getInfo()->inputConfig.test(
5138 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER)) {
Siarhei Vishniakouca205502021-07-16 21:31:58 +00005139 sp<WindowInfoHandle> wallpaper = state.getWallpaperWindow();
Arthur Hungc539dbb2022-12-08 07:45:36 +00005140 synthesizeCancelationEventsForWindowLocked(wallpaper, options);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00005141 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005142 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00005143 state.windows.erase(state.windows.begin() + i);
5144 } else {
5145 ++i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005146 }
5147 }
arthurhungb89ccb02020-12-30 16:19:01 +08005148
arthurhung6d4bed92021-03-17 11:59:33 +08005149 // If drag window is gone, it would receive a cancel event and broadcast the DRAG_END. We
arthurhungb89ccb02020-12-30 16:19:01 +08005150 // could just clear the state here.
Arthur Hung3915c1f2022-05-31 07:17:17 +00005151 if (mDragState && mDragState->dragWindow->getInfo()->displayId == displayId &&
arthurhung6d4bed92021-03-17 11:59:33 +08005152 std::find(windowHandles.begin(), windowHandles.end(), mDragState->dragWindow) ==
arthurhungb89ccb02020-12-30 16:19:01 +08005153 windowHandles.end()) {
Arthur Hung3915c1f2022-05-31 07:17:17 +00005154 ALOGI("Drag window went away: %s", mDragState->dragWindow->getName().c_str());
5155 sendDropWindowCommandLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08005156 mDragState.reset();
arthurhungb89ccb02020-12-30 16:19:01 +08005157 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00005158 }
Arthur Hung25e2af12020-03-26 12:58:37 +00005159
Arthur Hung72d8dc32020-03-28 00:48:39 +00005160 // Release information for windows that are no longer present.
5161 // This ensures that unused input channels are released promptly.
5162 // Otherwise, they might stick around until the window handle is destroyed
5163 // which might not happen until the next GC.
chaviw98318de2021-05-19 16:45:23 -05005164 for (const sp<WindowInfoHandle>& oldWindowHandle : oldWindowHandles) {
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07005165 if (getWindowHandleLocked(oldWindowHandle) == nullptr) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00005166 if (DEBUG_FOCUS) {
5167 ALOGD("Window went away: %s", oldWindowHandle->getName().c_str());
Arthur Hung25e2af12020-03-26 12:58:37 +00005168 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00005169 oldWindowHandle->releaseChannel();
Arthur Hung25e2af12020-03-26 12:58:37 +00005170 }
chaviw291d88a2019-02-14 10:33:58 -08005171 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005172}
5173
5174void InputDispatcher::setFocusedApplication(
Chris Yea209fde2020-07-22 13:54:51 -07005175 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005176 if (DEBUG_FOCUS) {
5177 ALOGD("setFocusedApplication displayId=%" PRId32 " %s", displayId,
5178 inputApplicationHandle ? inputApplicationHandle->getName().c_str() : "<nullptr>");
5179 }
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05005180 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005181 std::scoped_lock _l(mLock);
Vishnu Nair599f1412021-06-21 10:39:58 -07005182 setFocusedApplicationLocked(displayId, inputApplicationHandle);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005183 } // release lock
5184
5185 // Wake up poll loop since it may need to make new input dispatching choices.
5186 mLooper->wake();
5187}
5188
Vishnu Nair599f1412021-06-21 10:39:58 -07005189void InputDispatcher::setFocusedApplicationLocked(
5190 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
5191 std::shared_ptr<InputApplicationHandle> oldFocusedApplicationHandle =
5192 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
5193
5194 if (sharedPointersEqual(oldFocusedApplicationHandle, inputApplicationHandle)) {
5195 return; // This application is already focused. No need to wake up or change anything.
5196 }
5197
5198 // Set the new application handle.
5199 if (inputApplicationHandle != nullptr) {
5200 mFocusedApplicationHandlesByDisplay[displayId] = inputApplicationHandle;
5201 } else {
5202 mFocusedApplicationHandlesByDisplay.erase(displayId);
5203 }
5204
5205 // No matter what the old focused application was, stop waiting on it because it is
5206 // no longer focused.
5207 resetNoFocusedWindowTimeoutLocked();
5208}
5209
Tiger Huang721e26f2018-07-24 22:26:19 +08005210/**
5211 * Sets the focused display, which is responsible for receiving focus-dispatched input events where
5212 * the display not specified.
5213 *
5214 * We track any unreleased events for each window. If a window loses the ability to receive the
5215 * released event, we will send a cancel event to it. So when the focused display is changed, we
5216 * cancel all the unreleased display-unspecified events for the focused window on the old focused
5217 * display. The display-specified events won't be affected.
5218 */
5219void InputDispatcher::setFocusedDisplay(int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005220 if (DEBUG_FOCUS) {
5221 ALOGD("setFocusedDisplay displayId=%" PRId32, displayId);
5222 }
Tiger Huang721e26f2018-07-24 22:26:19 +08005223 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005224 std::scoped_lock _l(mLock);
Tiger Huang721e26f2018-07-24 22:26:19 +08005225
5226 if (mFocusedDisplayId != displayId) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07005227 sp<IBinder> oldFocusedWindowToken =
Vishnu Nairc519ff72021-01-21 08:23:08 -08005228 mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07005229 if (oldFocusedWindowToken != nullptr) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005230 std::shared_ptr<InputChannel> inputChannel =
Vishnu Nairad321cd2020-08-20 16:40:21 -07005231 getInputChannelLocked(oldFocusedWindowToken);
Tiger Huang721e26f2018-07-24 22:26:19 +08005232 if (inputChannel != nullptr) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005233 CancelationOptions
Michael Wrightfb04fd52022-11-24 22:31:11 +00005234 options(CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005235 "The display which contains this window no longer has focus.");
Michael Wright3dd60e22019-03-27 22:06:44 +00005236 options.displayId = ADISPLAY_ID_NONE;
Tiger Huang721e26f2018-07-24 22:26:19 +08005237 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
5238 }
5239 }
5240 mFocusedDisplayId = displayId;
5241
Chris Ye3c2d6f52020-08-09 10:39:48 -07005242 // Find new focused window and validate
Vishnu Nairc519ff72021-01-21 08:23:08 -08005243 sp<IBinder> newFocusedWindowToken = mFocusResolver.getFocusedWindowToken(displayId);
Prabir Pradhancef936d2021-07-21 16:17:52 +00005244 sendFocusChangedCommandLocked(oldFocusedWindowToken, newFocusedWindowToken);
Robert Carrf759f162018-11-13 12:57:11 -08005245
Vishnu Nairad321cd2020-08-20 16:40:21 -07005246 if (newFocusedWindowToken == nullptr) {
Tiger Huang721e26f2018-07-24 22:26:19 +08005247 ALOGW("Focused display #%" PRId32 " does not have a focused window.", displayId);
Vishnu Nairc519ff72021-01-21 08:23:08 -08005248 if (mFocusResolver.hasFocusedWindowTokens()) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07005249 ALOGE("But another display has a focused window\n%s",
Vishnu Nairc519ff72021-01-21 08:23:08 -08005250 mFocusResolver.dumpFocusedWindows().c_str());
Tiger Huang721e26f2018-07-24 22:26:19 +08005251 }
5252 }
5253 }
Tiger Huang721e26f2018-07-24 22:26:19 +08005254 } // release lock
5255
5256 // Wake up poll loop since it may need to make new input dispatching choices.
5257 mLooper->wake();
5258}
5259
Michael Wrightd02c5b62014-02-10 15:10:22 -08005260void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005261 if (DEBUG_FOCUS) {
5262 ALOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
5263 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005264
5265 bool changed;
5266 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005267 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005268
5269 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
5270 if (mDispatchFrozen && !frozen) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005271 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005272 }
5273
5274 if (mDispatchEnabled && !enabled) {
5275 resetAndDropEverythingLocked("dispatcher is being disabled");
5276 }
5277
5278 mDispatchEnabled = enabled;
5279 mDispatchFrozen = frozen;
5280 changed = true;
5281 } else {
5282 changed = false;
5283 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005284 } // release lock
5285
5286 if (changed) {
5287 // Wake up poll loop since it may need to make new input dispatching choices.
5288 mLooper->wake();
5289 }
5290}
5291
5292void InputDispatcher::setInputFilterEnabled(bool enabled) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005293 if (DEBUG_FOCUS) {
5294 ALOGD("setInputFilterEnabled: enabled=%d", enabled);
5295 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005296
5297 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005298 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005299
5300 if (mInputFilterEnabled == enabled) {
5301 return;
5302 }
5303
5304 mInputFilterEnabled = enabled;
5305 resetAndDropEverythingLocked("input filter is being enabled or disabled");
5306 } // release lock
5307
5308 // Wake up poll loop since there might be work to do to drop everything.
5309 mLooper->wake();
5310}
5311
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005312bool InputDispatcher::setInTouchMode(bool inTouchMode, gui::Pid pid, gui::Uid uid,
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00005313 bool hasPermission, int32_t displayId) {
Antonio Kantekf16f2832021-09-28 04:39:20 +00005314 bool needWake = false;
5315 {
5316 std::scoped_lock lock(mLock);
Antonio Kantek15beb512022-06-13 22:35:41 +00005317 ALOGD_IF(DEBUG_TOUCH_MODE,
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005318 "Request to change touch mode to %s (calling pid=%s, uid=%s, "
Antonio Kantek15beb512022-06-13 22:35:41 +00005319 "hasPermission=%s, target displayId=%d, mTouchModePerDisplay[displayId]=%s)",
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005320 toString(inTouchMode), pid.toString().c_str(), uid.toString().c_str(),
5321 toString(hasPermission), displayId,
Antonio Kantek15beb512022-06-13 22:35:41 +00005322 mTouchModePerDisplay.count(displayId) == 0
5323 ? "not set"
5324 : std::to_string(mTouchModePerDisplay[displayId]).c_str());
5325
Antonio Kantek15beb512022-06-13 22:35:41 +00005326 auto touchModeIt = mTouchModePerDisplay.find(displayId);
5327 if (touchModeIt != mTouchModePerDisplay.end() && touchModeIt->second == inTouchMode) {
Antonio Kantekea47acb2021-12-23 12:41:25 -08005328 return false;
Antonio Kantekf16f2832021-09-28 04:39:20 +00005329 }
Antonio Kantekea47acb2021-12-23 12:41:25 -08005330 if (!hasPermission) {
Antonio Kantek48710e42022-03-24 14:19:30 -07005331 if (!focusedWindowIsOwnedByLocked(pid, uid) &&
5332 !recentWindowsAreOwnedByLocked(pid, uid)) {
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005333 ALOGD("Touch mode switch rejected, caller (pid=%s, uid=%s) doesn't own the focused "
Antonio Kantek48710e42022-03-24 14:19:30 -07005334 "window nor none of the previously interacted window",
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005335 pid.toString().c_str(), uid.toString().c_str());
Antonio Kantekea47acb2021-12-23 12:41:25 -08005336 return false;
5337 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00005338 }
Antonio Kantek15beb512022-06-13 22:35:41 +00005339 mTouchModePerDisplay[displayId] = inTouchMode;
5340 auto entry = std::make_unique<TouchModeEntry>(mIdGenerator.nextId(), now(), inTouchMode,
5341 displayId);
Antonio Kantekf16f2832021-09-28 04:39:20 +00005342 needWake = enqueueInboundEventLocked(std::move(entry));
5343 } // release lock
5344
5345 if (needWake) {
5346 mLooper->wake();
5347 }
Antonio Kantekea47acb2021-12-23 12:41:25 -08005348 return true;
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -08005349}
5350
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005351bool InputDispatcher::focusedWindowIsOwnedByLocked(gui::Pid pid, gui::Uid uid) {
Antonio Kantek48710e42022-03-24 14:19:30 -07005352 const sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
5353 if (focusedToken == nullptr) {
5354 return false;
5355 }
5356 sp<WindowInfoHandle> windowHandle = getWindowHandleLocked(focusedToken);
5357 return isWindowOwnedBy(windowHandle, pid, uid);
5358}
5359
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005360bool InputDispatcher::recentWindowsAreOwnedByLocked(gui::Pid pid, gui::Uid uid) {
Antonio Kantek48710e42022-03-24 14:19:30 -07005361 return std::find_if(mInteractionConnectionTokens.begin(), mInteractionConnectionTokens.end(),
5362 [&](const sp<IBinder>& connectionToken) REQUIRES(mLock) {
5363 const sp<WindowInfoHandle> windowHandle =
5364 getWindowHandleLocked(connectionToken);
5365 return isWindowOwnedBy(windowHandle, pid, uid);
5366 }) != mInteractionConnectionTokens.end();
5367}
5368
Bernardo Rufinoea97d182020-08-19 14:43:14 +01005369void InputDispatcher::setMaximumObscuringOpacityForTouch(float opacity) {
5370 if (opacity < 0 || opacity > 1) {
5371 LOG_ALWAYS_FATAL("Maximum obscuring opacity for touch should be >= 0 and <= 1");
5372 return;
5373 }
5374
5375 std::scoped_lock lock(mLock);
5376 mMaximumObscuringOpacityForTouch = opacity;
5377}
5378
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005379std::tuple<TouchState*, TouchedWindow*, int32_t /*displayId*/>
5380InputDispatcher::findTouchStateWindowAndDisplayLocked(const sp<IBinder>& token) {
Arthur Hungabbb9d82021-09-01 14:52:30 +00005381 for (auto& [displayId, state] : mTouchStatesByDisplay) {
5382 for (TouchedWindow& w : state.windows) {
5383 if (w.windowHandle->getToken() == token) {
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005384 return std::make_tuple(&state, &w, displayId);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005385 }
5386 }
5387 }
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005388 return std::make_tuple(nullptr, nullptr, ADISPLAY_ID_DEFAULT);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005389}
5390
arthurhungb89ccb02020-12-30 16:19:01 +08005391bool InputDispatcher::transferTouchFocus(const sp<IBinder>& fromToken, const sp<IBinder>& toToken,
5392 bool isDragDrop) {
chaviwfbe5d9c2018-12-26 12:23:37 -08005393 if (fromToken == toToken) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005394 if (DEBUG_FOCUS) {
5395 ALOGD("Trivial transfer to same window.");
5396 }
chaviwfbe5d9c2018-12-26 12:23:37 -08005397 return true;
5398 }
5399
Michael Wrightd02c5b62014-02-10 15:10:22 -08005400 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005401 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005402
Arthur Hungabbb9d82021-09-01 14:52:30 +00005403 // Find the target touch state and touched window by fromToken.
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005404 auto [state, touchedWindow, displayId] = findTouchStateWindowAndDisplayLocked(fromToken);
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005405
Arthur Hungabbb9d82021-09-01 14:52:30 +00005406 if (state == nullptr || touchedWindow == nullptr) {
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005407 ALOGD("Touch transfer failed because from window is not being touched.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005408 return false;
5409 }
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005410 std::set<int32_t> deviceIds = touchedWindow->getTouchingDeviceIds();
5411 if (deviceIds.size() != 1) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07005412 LOG(INFO) << "Can't transfer touch. Currently touching devices: " << dumpSet(deviceIds)
5413 << " for window: " << touchedWindow->dump();
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005414 return false;
5415 }
5416 const int32_t deviceId = *deviceIds.begin();
Arthur Hungabbb9d82021-09-01 14:52:30 +00005417
Arthur Hungabbb9d82021-09-01 14:52:30 +00005418 sp<WindowInfoHandle> toWindowHandle = getWindowHandleLocked(toToken, displayId);
5419 if (toWindowHandle == nullptr) {
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005420 ALOGW("Cannot transfer touch because to window not found.");
Arthur Hungabbb9d82021-09-01 14:52:30 +00005421 return false;
5422 }
5423
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005424 if (DEBUG_FOCUS) {
5425 ALOGD("transferTouchFocus: fromWindowHandle=%s, toWindowHandle=%s",
Arthur Hungabbb9d82021-09-01 14:52:30 +00005426 touchedWindow->windowHandle->getName().c_str(),
5427 toWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005428 }
5429
Arthur Hungabbb9d82021-09-01 14:52:30 +00005430 // Erase old window.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005431 ftl::Flags<InputTarget::Flags> oldTargetFlags = touchedWindow->targetFlags;
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005432 std::bitset<MAX_POINTER_ID + 1> pointerIds = touchedWindow->getTouchingPointers(deviceId);
Arthur Hungc539dbb2022-12-08 07:45:36 +00005433 sp<WindowInfoHandle> fromWindowHandle = touchedWindow->windowHandle;
Arthur Hungabbb9d82021-09-01 14:52:30 +00005434 state->removeWindowByToken(fromToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005435
Arthur Hungabbb9d82021-09-01 14:52:30 +00005436 // Add new window.
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00005437 nsecs_t downTimeInTarget = now();
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005438 ftl::Flags<InputTarget::Flags> newTargetFlags =
5439 oldTargetFlags & (InputTarget::Flags::SPLIT | InputTarget::Flags::DISPATCH_AS_IS);
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00005440 if (canReceiveForegroundTouches(*toWindowHandle->getInfo())) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005441 newTargetFlags |= InputTarget::Flags::FOREGROUND;
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00005442 }
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005443 state->addOrUpdateWindow(toWindowHandle, newTargetFlags, deviceId, pointerIds,
5444 downTimeInTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005445
Arthur Hungabbb9d82021-09-01 14:52:30 +00005446 // Store the dragging window.
5447 if (isDragDrop) {
Arthur Hungb75c2aa2022-07-15 09:35:36 +00005448 if (pointerIds.count() != 1) {
5449 ALOGW("The drag and drop cannot be started when there is no pointer or more than 1"
5450 " pointer on the window.");
Arthur Hung54745652022-04-20 07:17:41 +00005451 return false;
5452 }
Arthur Hungb75c2aa2022-07-15 09:35:36 +00005453 // Track the pointer id for drag window and generate the drag state.
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08005454 const size_t id = firstMarkedBit(pointerIds);
Arthur Hung54745652022-04-20 07:17:41 +00005455 mDragState = std::make_unique<DragState>(toWindowHandle, id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005456 }
5457
Arthur Hungabbb9d82021-09-01 14:52:30 +00005458 // Synthesize cancel for old window and down for new window.
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07005459 std::shared_ptr<Connection> fromConnection = getConnectionLocked(fromToken);
5460 std::shared_ptr<Connection> toConnection = getConnectionLocked(toToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005461 if (fromConnection != nullptr && toConnection != nullptr) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08005462 fromConnection->inputState.mergePointerStateTo(toConnection->inputState);
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005463 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
5464 "transferring touch from this window to another window");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005465 synthesizeCancelationEventsForConnectionLocked(fromConnection, options);
Arthur Hungc539dbb2022-12-08 07:45:36 +00005466 synthesizePointerDownEventsForConnectionLocked(downTimeInTarget, toConnection,
5467 newTargetFlags);
5468
5469 // Check if the wallpaper window should deliver the corresponding event.
5470 transferWallpaperTouch(oldTargetFlags, newTargetFlags, fromWindowHandle, toWindowHandle,
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005471 *state, deviceId, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005472 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005473 } // release lock
5474
5475 // Wake up poll loop since it may need to make new input dispatching choices.
5476 mLooper->wake();
5477 return true;
5478}
5479
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005480/**
5481 * Get the touched foreground window on the given display.
5482 * Return null if there are no windows touched on that display, or if more than one foreground
5483 * window is being touched.
5484 */
5485sp<WindowInfoHandle> InputDispatcher::findTouchedForegroundWindowLocked(int32_t displayId) const {
5486 auto stateIt = mTouchStatesByDisplay.find(displayId);
5487 if (stateIt == mTouchStatesByDisplay.end()) {
5488 ALOGI("No touch state on display %" PRId32, displayId);
5489 return nullptr;
5490 }
5491
5492 const TouchState& state = stateIt->second;
5493 sp<WindowInfoHandle> touchedForegroundWindow;
5494 // If multiple foreground windows are touched, return nullptr
5495 for (const TouchedWindow& window : state.windows) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005496 if (window.targetFlags.test(InputTarget::Flags::FOREGROUND)) {
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005497 if (touchedForegroundWindow != nullptr) {
5498 ALOGI("Two or more foreground windows: %s and %s",
5499 touchedForegroundWindow->getName().c_str(),
5500 window.windowHandle->getName().c_str());
5501 return nullptr;
5502 }
5503 touchedForegroundWindow = window.windowHandle;
5504 }
5505 }
5506 return touchedForegroundWindow;
5507}
5508
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005509// Binder call
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005510bool InputDispatcher::transferTouch(const sp<IBinder>& destChannelToken, int32_t displayId) {
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005511 sp<IBinder> fromToken;
5512 { // acquire lock
5513 std::scoped_lock _l(mLock);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005514 sp<WindowInfoHandle> toWindowHandle = getWindowHandleLocked(destChannelToken, displayId);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005515 if (toWindowHandle == nullptr) {
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005516 ALOGW("Could not find window associated with token=%p on display %" PRId32,
5517 destChannelToken.get(), displayId);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005518 return false;
5519 }
5520
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005521 sp<WindowInfoHandle> from = findTouchedForegroundWindowLocked(displayId);
5522 if (from == nullptr) {
5523 ALOGE("Could not find a source window in %s for %p", __func__, destChannelToken.get());
5524 return false;
5525 }
5526
5527 fromToken = from->getToken();
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005528 } // release lock
5529
5530 return transferTouchFocus(fromToken, destChannelToken);
5531}
5532
Michael Wrightd02c5b62014-02-10 15:10:22 -08005533void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005534 if (DEBUG_FOCUS) {
5535 ALOGD("Resetting and dropping all events (%s).", reason);
5536 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005537
Michael Wrightfb04fd52022-11-24 22:31:11 +00005538 CancelationOptions options(CancelationOptions::Mode::CANCEL_ALL_EVENTS, reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005539 synthesizeCancelationEventsForAllConnectionsLocked(options);
5540
5541 resetKeyRepeatLocked();
5542 releasePendingEventLocked();
5543 drainInboundQueueLocked();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005544 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005545
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005546 mAnrTracker.clear();
Jeff Brownf086ddb2014-02-11 14:28:48 -08005547 mTouchStatesByDisplay.clear();
Michael Wright78f24442014-08-06 15:55:28 -07005548 mReplacedKeys.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005549}
5550
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005551void InputDispatcher::logDispatchStateLocked() const {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005552 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005553 dumpDispatchStateLocked(dump);
5554
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005555 std::istringstream stream(dump);
5556 std::string line;
5557
5558 while (std::getline(stream, line, '\n')) {
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07005559 ALOGI("%s", line.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005560 }
5561}
5562
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005563std::string InputDispatcher::dumpPointerCaptureStateLocked() const {
Prabir Pradhan99987712020-11-10 18:43:05 -08005564 std::string dump;
5565
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005566 dump += StringPrintf(INDENT "Pointer Capture Requested: %s\n",
5567 toString(mCurrentPointerCaptureRequest.enable));
Prabir Pradhan99987712020-11-10 18:43:05 -08005568
5569 std::string windowName = "None";
5570 if (mWindowTokenWithPointerCapture) {
chaviw98318de2021-05-19 16:45:23 -05005571 const sp<WindowInfoHandle> captureWindowHandle =
Prabir Pradhan99987712020-11-10 18:43:05 -08005572 getWindowHandleLocked(mWindowTokenWithPointerCapture);
5573 windowName = captureWindowHandle ? captureWindowHandle->getName().c_str()
5574 : "token has capture without window";
5575 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005576 dump += StringPrintf(INDENT "Current Window with Pointer Capture: %s\n", windowName.c_str());
Prabir Pradhan99987712020-11-10 18:43:05 -08005577
5578 return dump;
5579}
5580
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005581void InputDispatcher::dumpDispatchStateLocked(std::string& dump) const {
Siarhei Vishniakou043a3ec2019-05-01 11:30:46 -07005582 dump += StringPrintf(INDENT "DispatchEnabled: %s\n", toString(mDispatchEnabled));
5583 dump += StringPrintf(INDENT "DispatchFrozen: %s\n", toString(mDispatchFrozen));
5584 dump += StringPrintf(INDENT "InputFilterEnabled: %s\n", toString(mInputFilterEnabled));
Tiger Huang721e26f2018-07-24 22:26:19 +08005585 dump += StringPrintf(INDENT "FocusedDisplayId: %" PRId32 "\n", mFocusedDisplayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005586
Tiger Huang721e26f2018-07-24 22:26:19 +08005587 if (!mFocusedApplicationHandlesByDisplay.empty()) {
5588 dump += StringPrintf(INDENT "FocusedApplications:\n");
5589 for (auto& it : mFocusedApplicationHandlesByDisplay) {
5590 const int32_t displayId = it.first;
Chris Yea209fde2020-07-22 13:54:51 -07005591 const std::shared_ptr<InputApplicationHandle>& applicationHandle = it.second;
Siarhei Vishniakou70622952020-07-30 11:17:23 -05005592 const std::chrono::duration timeout =
5593 applicationHandle->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005594 dump += StringPrintf(INDENT2 "displayId=%" PRId32
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005595 ", name='%s', dispatchingTimeout=%" PRId64 "ms\n",
Siarhei Vishniakou70622952020-07-30 11:17:23 -05005596 displayId, applicationHandle->getName().c_str(), millis(timeout));
Tiger Huang721e26f2018-07-24 22:26:19 +08005597 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005598 } else {
Tiger Huang721e26f2018-07-24 22:26:19 +08005599 dump += StringPrintf(INDENT "FocusedApplications: <none>\n");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005600 }
Tiger Huang721e26f2018-07-24 22:26:19 +08005601
Vishnu Nairc519ff72021-01-21 08:23:08 -08005602 dump += mFocusResolver.dump();
Prabir Pradhan99987712020-11-10 18:43:05 -08005603 dump += dumpPointerCaptureStateLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005604
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005605 if (!mTouchStatesByDisplay.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005606 dump += StringPrintf(INDENT "TouchStatesByDisplay:\n");
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005607 for (const auto& [displayId, state] : mTouchStatesByDisplay) {
Siarhei Vishniakou6e1e9872022-11-08 17:51:35 -08005608 std::string touchStateDump = addLinePrefix(state.dump(), INDENT2);
5609 dump += INDENT2 + std::to_string(displayId) + " : " + touchStateDump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005610 }
5611 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005612 dump += INDENT "TouchStates: <no displays touched>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005613 }
5614
arthurhung6d4bed92021-03-17 11:59:33 +08005615 if (mDragState) {
5616 dump += StringPrintf(INDENT "DragState:\n");
5617 mDragState->dump(dump, INDENT2);
5618 }
5619
Arthur Hungb92218b2018-08-14 12:00:21 +08005620 if (!mWindowHandlesByDisplay.empty()) {
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005621 for (const auto& [displayId, windowHandles] : mWindowHandlesByDisplay) {
5622 dump += StringPrintf(INDENT "Display: %" PRId32 "\n", displayId);
5623 if (const auto& it = mDisplayInfos.find(displayId); it != mDisplayInfos.end()) {
5624 const auto& displayInfo = it->second;
5625 dump += StringPrintf(INDENT2 "logicalSize=%dx%d\n", displayInfo.logicalWidth,
5626 displayInfo.logicalHeight);
5627 displayInfo.transform.dump(dump, "transform", INDENT4);
5628 } else {
5629 dump += INDENT2 "No DisplayInfo found!\n";
5630 }
5631
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08005632 if (!windowHandles.empty()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08005633 dump += INDENT2 "Windows:\n";
5634 for (size_t i = 0; i < windowHandles.size(); i++) {
chaviw98318de2021-05-19 16:45:23 -05005635 const sp<WindowInfoHandle>& windowHandle = windowHandles[i];
5636 const WindowInfo* windowInfo = windowHandle->getInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005637
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00005638 dump += StringPrintf(INDENT3 "%zu: name='%s', id=%" PRId32 ", displayId=%d, "
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005639 "inputConfig=%s, alpha=%.2f, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005640 "frame=[%d,%d][%d,%d], globalScale=%f, "
Bernardo Rufino49d99e42021-01-18 15:16:59 +00005641 "applicationInfo.name=%s, "
5642 "applicationInfo.token=%s, "
chaviw1ff3d1e2020-07-01 15:53:47 -07005643 "touchableRegion=",
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00005644 i, windowInfo->name.c_str(), windowInfo->id,
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005645 windowInfo->displayId,
5646 windowInfo->inputConfig.string().c_str(),
5647 windowInfo->alpha, windowInfo->frameLeft,
5648 windowInfo->frameTop, windowInfo->frameRight,
5649 windowInfo->frameBottom, windowInfo->globalScaleFactor,
Bernardo Rufino49d99e42021-01-18 15:16:59 +00005650 windowInfo->applicationInfo.name.c_str(),
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07005651 binderToString(windowInfo->applicationInfo.token).c_str());
Bernardo Rufino53fc31e2020-11-03 11:01:07 +00005652 dump += dumpRegion(windowInfo->touchableRegion);
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005653 dump += StringPrintf(", ownerPid=%s, ownerUid=%s, dispatchingTimeout=%" PRId64
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005654 "ms, hasToken=%s, "
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005655 "touchOcclusionMode=%s\n",
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005656 windowInfo->ownerPid.toString().c_str(),
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00005657 windowInfo->ownerUid.toString().c_str(),
Bernardo Rufinoc2f1fad2020-11-04 17:30:57 +00005658 millis(windowInfo->dispatchingTimeout),
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07005659 binderToString(windowInfo->token).c_str(),
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005660 toString(windowInfo->touchOcclusionMode).c_str());
chaviw85b44202020-07-24 11:46:21 -07005661 windowInfo->transform.dump(dump, "transform", INDENT4);
Arthur Hungb92218b2018-08-14 12:00:21 +08005662 }
5663 } else {
5664 dump += INDENT2 "Windows: <none>\n";
5665 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005666 }
5667 } else {
Arthur Hungb92218b2018-08-14 12:00:21 +08005668 dump += INDENT "Displays: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005669 }
5670
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005671 if (!mGlobalMonitorsByDisplay.empty()) {
5672 for (const auto& [displayId, monitors] : mGlobalMonitorsByDisplay) {
5673 dump += StringPrintf(INDENT "Global monitors on display %d:\n", displayId);
Michael Wright3dd60e22019-03-27 22:06:44 +00005674 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005675 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005676 } else {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005677 dump += INDENT "Global Monitors: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005678 }
5679
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005680 const nsecs_t currentTime = now();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005681
5682 // Dump recently dispatched or dropped events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005683 if (!mRecentQueue.empty()) {
5684 dump += StringPrintf(INDENT "RecentQueue: length=%zu\n", mRecentQueue.size());
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005685 for (const std::shared_ptr<EventEntry>& entry : mRecentQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005686 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005687 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005688 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005689 }
5690 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005691 dump += INDENT "RecentQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005692 }
5693
5694 // Dump event currently being dispatched.
5695 if (mPendingEvent) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005696 dump += INDENT "PendingEvent:\n";
5697 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005698 dump += mPendingEvent->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005699 dump += StringPrintf(", age=%" PRId64 "ms\n",
5700 ns2ms(currentTime - mPendingEvent->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005701 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005702 dump += INDENT "PendingEvent: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005703 }
5704
5705 // Dump inbound events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005706 if (!mInboundQueue.empty()) {
5707 dump += StringPrintf(INDENT "InboundQueue: length=%zu\n", mInboundQueue.size());
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005708 for (const std::shared_ptr<EventEntry>& entry : mInboundQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005709 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005710 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005711 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005712 }
5713 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005714 dump += INDENT "InboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005715 }
5716
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005717 if (!mReplacedKeys.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005718 dump += INDENT "ReplacedKeys:\n";
Michael Wright3cec4462022-11-24 22:05:46 +00005719 for (const auto& [replacement, newKeyCode] : mReplacedKeys) {
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005720 dump += StringPrintf(INDENT2 "originalKeyCode=%d, deviceId=%d -> newKeyCode=%d\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005721 replacement.keyCode, replacement.deviceId, newKeyCode);
Michael Wright78f24442014-08-06 15:55:28 -07005722 }
5723 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005724 dump += INDENT "ReplacedKeys: <empty>\n";
Michael Wright78f24442014-08-06 15:55:28 -07005725 }
5726
Prabir Pradhancef936d2021-07-21 16:17:52 +00005727 if (!mCommandQueue.empty()) {
5728 dump += StringPrintf(INDENT "CommandQueue: size=%zu\n", mCommandQueue.size());
5729 } else {
5730 dump += INDENT "CommandQueue: <empty>\n";
5731 }
5732
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005733 if (!mConnectionsByToken.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005734 dump += INDENT "Connections:\n";
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005735 for (const auto& [token, connection] : mConnectionsByToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005736 dump += StringPrintf(INDENT2 "%i: channelName='%s', windowName='%s', "
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005737 "status=%s, monitor=%s, responsive=%s\n",
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005738 connection->inputChannel->getFd().get(),
5739 connection->getInputChannelName().c_str(),
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08005740 connection->getWindowName().c_str(),
5741 ftl::enum_string(connection->status).c_str(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005742 toString(connection->monitor), toString(connection->responsive));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005743
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005744 if (!connection->outboundQueue.empty()) {
5745 dump += StringPrintf(INDENT3 "OutboundQueue: length=%zu\n",
5746 connection->outboundQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005747 dump += dumpQueue(connection->outboundQueue, currentTime);
5748
Michael Wrightd02c5b62014-02-10 15:10:22 -08005749 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005750 dump += INDENT3 "OutboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005751 }
5752
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005753 if (!connection->waitQueue.empty()) {
5754 dump += StringPrintf(INDENT3 "WaitQueue: length=%zu\n",
5755 connection->waitQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005756 dump += dumpQueue(connection->waitQueue, currentTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005757 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005758 dump += INDENT3 "WaitQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005759 }
Siarhei Vishniakoud38a1e02023-07-18 11:55:17 -07005760 std::stringstream inputStateDump;
5761 inputStateDump << connection->inputState;
5762 if (!isEmpty(inputStateDump)) {
5763 dump += INDENT3 "InputState: ";
5764 dump += inputStateDump.str() + "\n";
5765 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005766 }
5767 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005768 dump += INDENT "Connections: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005769 }
5770
5771 if (isAppSwitchPendingLocked()) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005772 dump += StringPrintf(INDENT "AppSwitch: pending, due in %" PRId64 "ms\n",
5773 ns2ms(mAppSwitchDueTime - now()));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005774 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005775 dump += INDENT "AppSwitch: not pending\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005776 }
5777
Antonio Kantek15beb512022-06-13 22:35:41 +00005778 if (!mTouchModePerDisplay.empty()) {
5779 dump += INDENT "TouchModePerDisplay:\n";
5780 for (const auto& [displayId, touchMode] : mTouchModePerDisplay) {
5781 dump += StringPrintf(INDENT2 "Display: %" PRId32 " TouchMode: %s\n", displayId,
5782 std::to_string(touchMode).c_str());
5783 }
5784 } else {
5785 dump += INDENT "TouchModePerDisplay: <none>\n";
5786 }
5787
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005788 dump += INDENT "Configuration:\n";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005789 dump += StringPrintf(INDENT2 "KeyRepeatDelay: %" PRId64 "ms\n", ns2ms(mConfig.keyRepeatDelay));
5790 dump += StringPrintf(INDENT2 "KeyRepeatTimeout: %" PRId64 "ms\n",
5791 ns2ms(mConfig.keyRepeatTimeout));
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00005792 dump += mLatencyTracker.dump(INDENT2);
Siarhei Vishniakoua04181f2021-03-26 05:56:49 +00005793 dump += mLatencyAggregator.dump(INDENT2);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005794}
5795
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005796void InputDispatcher::dumpMonitors(std::string& dump, const std::vector<Monitor>& monitors) const {
Michael Wright3dd60e22019-03-27 22:06:44 +00005797 const size_t numMonitors = monitors.size();
5798 for (size_t i = 0; i < numMonitors; i++) {
5799 const Monitor& monitor = monitors[i];
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005800 const std::shared_ptr<InputChannel>& channel = monitor.inputChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005801 dump += StringPrintf(INDENT2 "%zu: '%s', ", i, channel->getName().c_str());
5802 dump += "\n";
5803 }
5804}
5805
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005806class LooperEventCallback : public LooperCallback {
5807public:
5808 LooperEventCallback(std::function<int(int events)> callback) : mCallback(callback) {}
5809 int handleEvent(int /*fd*/, int events, void* /*data*/) override { return mCallback(events); }
5810
5811private:
5812 std::function<int(int events)> mCallback;
5813};
5814
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005815Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputChannel(const std::string& name) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00005816 if (DEBUG_CHANNEL_CREATION) {
5817 ALOGD("channel '%s' ~ createInputChannel", name.c_str());
5818 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005819
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005820 std::unique_ptr<InputChannel> serverChannel;
Garfield Tan15601662020-09-22 15:32:38 -07005821 std::unique_ptr<InputChannel> clientChannel;
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005822 status_t result = InputChannel::openInputChannelPair(name, serverChannel, clientChannel);
Garfield Tan15601662020-09-22 15:32:38 -07005823
5824 if (result) {
5825 return base::Error(result) << "Failed to open input channel pair with name " << name;
5826 }
5827
Michael Wrightd02c5b62014-02-10 15:10:22 -08005828 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005829 std::scoped_lock _l(mLock);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005830 const sp<IBinder>& token = serverChannel->getConnectionToken();
Garfield Tan15601662020-09-22 15:32:38 -07005831 int fd = serverChannel->getFd();
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07005832 std::shared_ptr<Connection> connection =
5833 std::make_shared<Connection>(std::move(serverChannel), /*monitor=*/false,
5834 mIdGenerator);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005835
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005836 if (mConnectionsByToken.find(token) != mConnectionsByToken.end()) {
5837 ALOGE("Created a new connection, but the token %p is already known", token.get());
5838 }
5839 mConnectionsByToken.emplace(token, connection);
5840
5841 std::function<int(int events)> callback = std::bind(&InputDispatcher::handleReceiveCallback,
5842 this, std::placeholders::_1, token);
5843
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005844 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, sp<LooperEventCallback>::make(callback),
5845 nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005846 } // release lock
5847
5848 // Wake the looper because some connections have changed.
5849 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07005850 return clientChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005851}
5852
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005853Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputMonitor(int32_t displayId,
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005854 const std::string& name,
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005855 gui::Pid pid) {
Garfield Tan15601662020-09-22 15:32:38 -07005856 std::shared_ptr<InputChannel> serverChannel;
5857 std::unique_ptr<InputChannel> clientChannel;
5858 status_t result = openInputChannelPair(name, serverChannel, clientChannel);
5859 if (result) {
5860 return base::Error(result) << "Failed to open input channel pair with name " << name;
5861 }
5862
Michael Wright3dd60e22019-03-27 22:06:44 +00005863 { // acquire lock
5864 std::scoped_lock _l(mLock);
5865
5866 if (displayId < 0) {
Garfield Tan15601662020-09-22 15:32:38 -07005867 return base::Error(BAD_VALUE) << "Attempted to create input monitor with name " << name
5868 << " without a specified display.";
Michael Wright3dd60e22019-03-27 22:06:44 +00005869 }
5870
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07005871 std::shared_ptr<Connection> connection =
5872 std::make_shared<Connection>(serverChannel, /*monitor=*/true, mIdGenerator);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005873 const sp<IBinder>& token = serverChannel->getConnectionToken();
Garfield Tan15601662020-09-22 15:32:38 -07005874 const int fd = serverChannel->getFd();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005875
5876 if (mConnectionsByToken.find(token) != mConnectionsByToken.end()) {
5877 ALOGE("Created a new connection, but the token %p is already known", token.get());
5878 }
5879 mConnectionsByToken.emplace(token, connection);
5880 std::function<int(int events)> callback = std::bind(&InputDispatcher::handleReceiveCallback,
5881 this, std::placeholders::_1, token);
Michael Wright3dd60e22019-03-27 22:06:44 +00005882
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005883 mGlobalMonitorsByDisplay[displayId].emplace_back(serverChannel, pid);
Michael Wright3dd60e22019-03-27 22:06:44 +00005884
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005885 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, sp<LooperEventCallback>::make(callback),
5886 nullptr);
Michael Wright3dd60e22019-03-27 22:06:44 +00005887 }
Garfield Tan15601662020-09-22 15:32:38 -07005888
Michael Wright3dd60e22019-03-27 22:06:44 +00005889 // Wake the looper because some connections have changed.
5890 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07005891 return clientChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005892}
5893
Garfield Tan15601662020-09-22 15:32:38 -07005894status_t InputDispatcher::removeInputChannel(const sp<IBinder>& connectionToken) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005895 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005896 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005897
Harry Cutts33476232023-01-30 19:57:29 +00005898 status_t status = removeInputChannelLocked(connectionToken, /*notify=*/false);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005899 if (status) {
5900 return status;
5901 }
5902 } // release lock
5903
5904 // Wake the poll loop because removing the connection may have changed the current
5905 // synchronization state.
5906 mLooper->wake();
5907 return OK;
5908}
5909
Garfield Tan15601662020-09-22 15:32:38 -07005910status_t InputDispatcher::removeInputChannelLocked(const sp<IBinder>& connectionToken,
5911 bool notify) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07005912 std::shared_ptr<Connection> connection = getConnectionLocked(connectionToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005913 if (connection == nullptr) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005914 // Connection can be removed via socket hang up or an explicit call to 'removeInputChannel'
Michael Wrightd02c5b62014-02-10 15:10:22 -08005915 return BAD_VALUE;
5916 }
5917
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005918 removeConnectionLocked(connection);
Robert Carr5c8a0262018-10-03 16:30:44 -07005919
Michael Wrightd02c5b62014-02-10 15:10:22 -08005920 if (connection->monitor) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005921 removeMonitorChannelLocked(connectionToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005922 }
5923
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005924 mLooper->removeFd(connection->inputChannel->getFd());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005925
5926 nsecs_t currentTime = now();
5927 abortBrokenDispatchCycleLocked(currentTime, connection, notify);
5928
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08005929 connection->status = Connection::Status::ZOMBIE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005930 return OK;
5931}
5932
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005933void InputDispatcher::removeMonitorChannelLocked(const sp<IBinder>& connectionToken) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005934 for (auto it = mGlobalMonitorsByDisplay.begin(); it != mGlobalMonitorsByDisplay.end();) {
5935 auto& [displayId, monitors] = *it;
5936 std::erase_if(monitors, [connectionToken](const Monitor& monitor) {
5937 return monitor.inputChannel->getConnectionToken() == connectionToken;
5938 });
Michael Wright3dd60e22019-03-27 22:06:44 +00005939
Michael Wright3dd60e22019-03-27 22:06:44 +00005940 if (monitors.empty()) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005941 it = mGlobalMonitorsByDisplay.erase(it);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005942 } else {
5943 ++it;
5944 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005945 }
5946}
5947
Michael Wright3dd60e22019-03-27 22:06:44 +00005948status_t InputDispatcher::pilferPointers(const sp<IBinder>& token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005949 std::scoped_lock _l(mLock);
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00005950 return pilferPointersLocked(token);
5951}
Michael Wright3dd60e22019-03-27 22:06:44 +00005952
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00005953status_t InputDispatcher::pilferPointersLocked(const sp<IBinder>& token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005954 const std::shared_ptr<InputChannel> requestingChannel = getInputChannelLocked(token);
5955 if (!requestingChannel) {
5956 ALOGW("Attempted to pilfer pointers from an un-registered channel or invalid token");
5957 return BAD_VALUE;
Michael Wright3dd60e22019-03-27 22:06:44 +00005958 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005959
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005960 auto [statePtr, windowPtr, displayId] = findTouchStateWindowAndDisplayLocked(token);
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005961 if (statePtr == nullptr || windowPtr == nullptr) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005962 ALOGW("Attempted to pilfer points from a channel without any on-going pointer streams."
5963 " Ignoring.");
5964 return BAD_VALUE;
5965 }
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005966 std::set<int32_t> deviceIds = windowPtr->getTouchingDeviceIds();
5967 if (deviceIds.size() != 1) {
5968 LOG(WARNING) << "Can't pilfer. Currently touching devices: " << dumpSet(deviceIds)
5969 << " in window: " << windowPtr->dump();
5970 return BAD_VALUE;
5971 }
5972 const int32_t deviceId = *deviceIds.begin();
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005973
5974 TouchState& state = *statePtr;
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00005975 TouchedWindow& window = *windowPtr;
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005976 // Send cancel events to all the input channels we're stealing from.
Michael Wrightfb04fd52022-11-24 22:31:11 +00005977 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005978 "input channel stole pointer stream");
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005979 options.deviceId = deviceId;
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005980 options.displayId = displayId;
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005981 std::bitset<MAX_POINTER_ID + 1> pointerIds = window.getTouchingPointers(deviceId);
5982 options.pointerIds = pointerIds;
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005983 std::string canceledWindows;
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00005984 for (const TouchedWindow& w : state.windows) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005985 const std::shared_ptr<InputChannel> channel =
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00005986 getInputChannelLocked(w.windowHandle->getToken());
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005987 if (channel != nullptr && channel->getConnectionToken() != token) {
5988 synthesizeCancelationEventsForInputChannelLocked(channel, options);
5989 canceledWindows += canceledWindows.empty() ? "[" : ", ";
5990 canceledWindows += channel->getName();
5991 }
5992 }
5993 canceledWindows += canceledWindows.empty() ? "[]" : "]";
5994 ALOGI("Channel %s is stealing touch from %s", requestingChannel->getName().c_str(),
5995 canceledWindows.c_str());
5996
Prabir Pradhane680f9b2022-02-04 04:24:00 -08005997 // Prevent the gesture from being sent to any other windows.
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00005998 // This only blocks relevant pointers to be sent to other windows
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005999 window.addPilferingPointers(deviceId, pointerIds);
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00006000
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07006001 state.cancelPointersForWindowsExcept(deviceId, pointerIds, token);
Michael Wright3dd60e22019-03-27 22:06:44 +00006002 return OK;
6003}
6004
Prabir Pradhan99987712020-11-10 18:43:05 -08006005void InputDispatcher::requestPointerCapture(const sp<IBinder>& windowToken, bool enabled) {
6006 { // acquire lock
6007 std::scoped_lock _l(mLock);
6008 if (DEBUG_FOCUS) {
chaviw98318de2021-05-19 16:45:23 -05006009 const sp<WindowInfoHandle> windowHandle = getWindowHandleLocked(windowToken);
Prabir Pradhan99987712020-11-10 18:43:05 -08006010 ALOGI("Request to %s Pointer Capture from: %s.", enabled ? "enable" : "disable",
6011 windowHandle != nullptr ? windowHandle->getName().c_str()
6012 : "token without window");
6013 }
6014
Vishnu Nairc519ff72021-01-21 08:23:08 -08006015 const sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Prabir Pradhan99987712020-11-10 18:43:05 -08006016 if (focusedToken != windowToken) {
6017 ALOGW("Ignoring request to %s Pointer Capture: window does not have focus.",
6018 enabled ? "enable" : "disable");
6019 return;
6020 }
6021
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006022 if (enabled == mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006023 ALOGW("Ignoring request to %s Pointer Capture: "
6024 "window has %s requested pointer capture.",
6025 enabled ? "enable" : "disable", enabled ? "already" : "not");
6026 return;
6027 }
6028
Christine Franksb768bb42021-11-29 12:11:31 -08006029 if (enabled) {
6030 if (std::find(mIneligibleDisplaysForPointerCapture.begin(),
6031 mIneligibleDisplaysForPointerCapture.end(),
6032 mFocusedDisplayId) != mIneligibleDisplaysForPointerCapture.end()) {
6033 ALOGW("Ignoring request to enable Pointer Capture: display is not eligible");
6034 return;
6035 }
6036 }
6037
Prabir Pradhan99987712020-11-10 18:43:05 -08006038 setPointerCaptureLocked(enabled);
6039 } // release lock
6040
6041 // Wake the thread to process command entries.
6042 mLooper->wake();
6043}
6044
Christine Franksb768bb42021-11-29 12:11:31 -08006045void InputDispatcher::setDisplayEligibilityForPointerCapture(int32_t displayId, bool isEligible) {
6046 { // acquire lock
6047 std::scoped_lock _l(mLock);
6048 std::erase(mIneligibleDisplaysForPointerCapture, displayId);
6049 if (!isEligible) {
6050 mIneligibleDisplaysForPointerCapture.push_back(displayId);
6051 }
6052 } // release lock
6053}
6054
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00006055std::optional<gui::Pid> InputDispatcher::findMonitorPidByTokenLocked(const sp<IBinder>& token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006056 for (const auto& [_, monitors] : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00006057 for (const Monitor& monitor : monitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07006058 if (monitor.inputChannel->getConnectionToken() == token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006059 return monitor.pid;
Michael Wright3dd60e22019-03-27 22:06:44 +00006060 }
6061 }
6062 }
6063 return std::nullopt;
6064}
6065
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006066std::shared_ptr<Connection> InputDispatcher::getConnectionLocked(
6067 const sp<IBinder>& inputConnectionToken) const {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07006068 if (inputConnectionToken == nullptr) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07006069 return nullptr;
Arthur Hung3b413f22018-10-26 18:05:34 +08006070 }
6071
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00006072 for (const auto& [token, connection] : mConnectionsByToken) {
6073 if (token == inputConnectionToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07006074 return connection;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006075 }
6076 }
Robert Carr4e670e52018-08-15 13:26:12 -07006077
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07006078 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006079}
6080
Siarhei Vishniakouad991402020-10-28 11:40:09 -05006081std::string InputDispatcher::getConnectionNameLocked(const sp<IBinder>& connectionToken) const {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006082 std::shared_ptr<Connection> connection = getConnectionLocked(connectionToken);
Siarhei Vishniakouad991402020-10-28 11:40:09 -05006083 if (connection == nullptr) {
6084 return "<nullptr>";
6085 }
6086 return connection->getInputChannelName();
6087}
6088
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006089void InputDispatcher::removeConnectionLocked(const std::shared_ptr<Connection>& connection) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006090 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00006091 mConnectionsByToken.erase(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07006092}
6093
Prabir Pradhancef936d2021-07-21 16:17:52 +00006094void InputDispatcher::doDispatchCycleFinishedCommand(nsecs_t finishTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006095 const std::shared_ptr<Connection>& connection,
6096 uint32_t seq, bool handled,
6097 nsecs_t consumeTime) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006098 // Handle post-event policy actions.
6099 std::deque<DispatchEntry*>::iterator dispatchEntryIt = connection->findWaitQueueEntry(seq);
6100 if (dispatchEntryIt == connection->waitQueue.end()) {
6101 return;
6102 }
6103 DispatchEntry* dispatchEntry = *dispatchEntryIt;
6104 const nsecs_t eventDuration = finishTime - dispatchEntry->deliveryTime;
6105 if (eventDuration > SLOW_EVENT_PROCESSING_WARNING_TIMEOUT) {
6106 ALOGI("%s spent %" PRId64 "ms processing %s", connection->getWindowName().c_str(),
6107 ns2ms(eventDuration), dispatchEntry->eventEntry->getDescription().c_str());
6108 }
6109 if (shouldReportFinishedEvent(*dispatchEntry, *connection)) {
6110 mLatencyTracker.trackFinishedEvent(dispatchEntry->eventEntry->id,
6111 connection->inputChannel->getConnectionToken(),
6112 dispatchEntry->deliveryTime, consumeTime, finishTime);
6113 }
6114
6115 bool restartEvent;
6116 if (dispatchEntry->eventEntry->type == EventEntry::Type::KEY) {
6117 KeyEntry& keyEntry = static_cast<KeyEntry&>(*(dispatchEntry->eventEntry));
6118 restartEvent =
6119 afterKeyEventLockedInterruptable(connection, dispatchEntry, keyEntry, handled);
6120 } else if (dispatchEntry->eventEntry->type == EventEntry::Type::MOTION) {
6121 MotionEntry& motionEntry = static_cast<MotionEntry&>(*(dispatchEntry->eventEntry));
6122 restartEvent = afterMotionEventLockedInterruptable(connection, dispatchEntry, motionEntry,
6123 handled);
6124 } else {
6125 restartEvent = false;
6126 }
6127
6128 // Dequeue the event and start the next cycle.
6129 // Because the lock might have been released, it is possible that the
6130 // contents of the wait queue to have been drained, so we need to double-check
6131 // a few things.
6132 dispatchEntryIt = connection->findWaitQueueEntry(seq);
6133 if (dispatchEntryIt != connection->waitQueue.end()) {
6134 dispatchEntry = *dispatchEntryIt;
6135 connection->waitQueue.erase(dispatchEntryIt);
6136 const sp<IBinder>& connectionToken = connection->inputChannel->getConnectionToken();
6137 mAnrTracker.erase(dispatchEntry->timeoutTime, connectionToken);
6138 if (!connection->responsive) {
6139 connection->responsive = isConnectionResponsive(*connection);
6140 if (connection->responsive) {
6141 // The connection was unresponsive, and now it's responsive.
6142 processConnectionResponsiveLocked(*connection);
6143 }
6144 }
6145 traceWaitQueueLength(*connection);
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08006146 if (restartEvent && connection->status == Connection::Status::NORMAL) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006147 connection->outboundQueue.push_front(dispatchEntry);
6148 traceOutboundQueueLength(*connection);
6149 } else {
6150 releaseDispatchEntry(dispatchEntry);
6151 }
6152 }
6153
6154 // Start the next dispatch cycle for this connection.
6155 startDispatchCycleLocked(now(), connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006156}
6157
Prabir Pradhancef936d2021-07-21 16:17:52 +00006158void InputDispatcher::sendFocusChangedCommandLocked(const sp<IBinder>& oldToken,
6159 const sp<IBinder>& newToken) {
6160 auto command = [this, oldToken, newToken]() REQUIRES(mLock) {
6161 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00006162 mPolicy.notifyFocusChanged(oldToken, newToken);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006163 };
6164 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08006165}
6166
Prabir Pradhancef936d2021-07-21 16:17:52 +00006167void InputDispatcher::sendDropWindowCommandLocked(const sp<IBinder>& token, float x, float y) {
6168 auto command = [this, token, x, y]() REQUIRES(mLock) {
6169 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00006170 mPolicy.notifyDropWindow(token, x, y);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006171 };
6172 postCommandLocked(std::move(command));
Robert Carrf759f162018-11-13 12:57:11 -08006173}
6174
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006175void InputDispatcher::onAnrLocked(const std::shared_ptr<Connection>& connection) {
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006176 if (connection == nullptr) {
6177 LOG_ALWAYS_FATAL("Caller must check for nullness");
6178 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006179 // Since we are allowing the policy to extend the timeout, maybe the waitQueue
6180 // is already healthy again. Don't raise ANR in this situation
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006181 if (connection->waitQueue.empty()) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006182 ALOGI("Not raising ANR because the connection %s has recovered",
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006183 connection->inputChannel->getName().c_str());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006184 return;
6185 }
6186 /**
6187 * The "oldestEntry" is the entry that was first sent to the application. That entry, however,
6188 * may not be the one that caused the timeout to occur. One possibility is that window timeout
6189 * has changed. This could cause newer entries to time out before the already dispatched
6190 * entries. In that situation, the newest entries caused ANR. But in all likelihood, the app
6191 * processes the events linearly. So providing information about the oldest entry seems to be
6192 * most useful.
6193 */
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006194 DispatchEntry* oldestEntry = *connection->waitQueue.begin();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006195 const nsecs_t currentWait = now() - oldestEntry->deliveryTime;
6196 std::string reason =
6197 android::base::StringPrintf("%s is not responding. Waited %" PRId64 "ms for %s",
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006198 connection->inputChannel->getName().c_str(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006199 ns2ms(currentWait),
6200 oldestEntry->eventEntry->getDescription().c_str());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006201 sp<IBinder> connectionToken = connection->inputChannel->getConnectionToken();
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -06006202 updateLastAnrStateLocked(getWindowHandleLocked(connectionToken), reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006203
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006204 processConnectionUnresponsiveLocked(*connection, std::move(reason));
6205
6206 // Stop waking up for events on this connection, it is already unresponsive
6207 cancelEventsForAnrLocked(connection);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006208}
6209
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05006210void InputDispatcher::onAnrLocked(std::shared_ptr<InputApplicationHandle> application) {
6211 std::string reason =
6212 StringPrintf("%s does not have a focused window", application->getName().c_str());
6213 updateLastAnrStateLocked(*application, reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006214
Yabin Cui8eb9c552023-06-08 18:05:07 +00006215 auto command = [this, app = std::move(application)]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006216 scoped_unlock unlock(mLock);
Yabin Cuiced952f2023-06-09 21:12:51 +00006217 mPolicy.notifyNoFocusedWindowAnr(app);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006218 };
6219 postCommandLocked(std::move(command));
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00006220}
6221
chaviw98318de2021-05-19 16:45:23 -05006222void InputDispatcher::updateLastAnrStateLocked(const sp<WindowInfoHandle>& window,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006223 const std::string& reason) {
6224 const std::string windowLabel = getApplicationWindowLabel(nullptr, window);
6225 updateLastAnrStateLocked(windowLabel, reason);
6226}
6227
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05006228void InputDispatcher::updateLastAnrStateLocked(const InputApplicationHandle& application,
6229 const std::string& reason) {
6230 const std::string windowLabel = getApplicationWindowLabel(&application, nullptr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006231 updateLastAnrStateLocked(windowLabel, reason);
6232}
6233
6234void InputDispatcher::updateLastAnrStateLocked(const std::string& windowLabel,
6235 const std::string& reason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006236 // Capture a record of the InputDispatcher state at the time of the ANR.
Yi Kong9b14ac62018-07-17 13:48:38 -07006237 time_t t = time(nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006238 struct tm tm;
6239 localtime_r(&t, &tm);
6240 char timestr[64];
6241 strftime(timestr, sizeof(timestr), "%F %T", &tm);
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006242 mLastAnrState.clear();
6243 mLastAnrState += INDENT "ANR:\n";
6244 mLastAnrState += StringPrintf(INDENT2 "Time: %s\n", timestr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006245 mLastAnrState += StringPrintf(INDENT2 "Reason: %s\n", reason.c_str());
6246 mLastAnrState += StringPrintf(INDENT2 "Window: %s\n", windowLabel.c_str());
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006247 dumpDispatchStateLocked(mLastAnrState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006248}
6249
Prabir Pradhancef936d2021-07-21 16:17:52 +00006250void InputDispatcher::doInterceptKeyBeforeDispatchingCommand(const sp<IBinder>& focusedWindowToken,
6251 KeyEntry& entry) {
6252 const KeyEvent event = createKeyEvent(entry);
6253 nsecs_t delay = 0;
6254 { // release lock
6255 scoped_unlock unlock(mLock);
6256 android::base::Timer t;
Prabir Pradhana41d2442023-04-20 21:30:40 +00006257 delay = mPolicy.interceptKeyBeforeDispatching(focusedWindowToken, event, entry.policyFlags);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006258 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
6259 ALOGW("Excessive delay in interceptKeyBeforeDispatching; took %s ms",
6260 std::to_string(t.duration().count()).c_str());
6261 }
6262 } // acquire lock
Michael Wrightd02c5b62014-02-10 15:10:22 -08006263
6264 if (delay < 0) {
Michael Wright5caf55a2022-11-24 22:31:42 +00006265 entry.interceptKeyResult = KeyEntry::InterceptKeyResult::SKIP;
Prabir Pradhancef936d2021-07-21 16:17:52 +00006266 } else if (delay == 0) {
Michael Wright5caf55a2022-11-24 22:31:42 +00006267 entry.interceptKeyResult = KeyEntry::InterceptKeyResult::CONTINUE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006268 } else {
Michael Wright5caf55a2022-11-24 22:31:42 +00006269 entry.interceptKeyResult = KeyEntry::InterceptKeyResult::TRY_AGAIN_LATER;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006270 entry.interceptKeyWakeupTime = now() + delay;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006271 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006272}
6273
Prabir Pradhancef936d2021-07-21 16:17:52 +00006274void InputDispatcher::sendWindowUnresponsiveCommandLocked(const sp<IBinder>& token,
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00006275 std::optional<gui::Pid> pid,
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006276 std::string reason) {
Yabin Cui8eb9c552023-06-08 18:05:07 +00006277 auto command = [this, token, pid, r = std::move(reason)]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006278 scoped_unlock unlock(mLock);
Yabin Cuiced952f2023-06-09 21:12:51 +00006279 mPolicy.notifyWindowUnresponsive(token, pid, r);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006280 };
6281 postCommandLocked(std::move(command));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006282}
6283
Prabir Pradhanedd96402022-02-15 01:46:16 -08006284void InputDispatcher::sendWindowResponsiveCommandLocked(const sp<IBinder>& token,
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00006285 std::optional<gui::Pid> pid) {
Prabir Pradhanedd96402022-02-15 01:46:16 -08006286 auto command = [this, token, pid]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006287 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00006288 mPolicy.notifyWindowResponsive(token, pid);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006289 };
6290 postCommandLocked(std::move(command));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006291}
6292
6293/**
6294 * Tell the policy that a connection has become unresponsive so that it can start ANR.
6295 * Check whether the connection of interest is a monitor or a window, and add the corresponding
6296 * command entry to the command queue.
6297 */
6298void InputDispatcher::processConnectionUnresponsiveLocked(const Connection& connection,
6299 std::string reason) {
6300 const sp<IBinder>& connectionToken = connection.inputChannel->getConnectionToken();
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00006301 std::optional<gui::Pid> pid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006302 if (connection.monitor) {
6303 ALOGW("Monitor %s is unresponsive: %s", connection.inputChannel->getName().c_str(),
6304 reason.c_str());
Prabir Pradhanedd96402022-02-15 01:46:16 -08006305 pid = findMonitorPidByTokenLocked(connectionToken);
6306 } else {
6307 // The connection is a window
6308 ALOGW("Window %s is unresponsive: %s", connection.inputChannel->getName().c_str(),
6309 reason.c_str());
6310 const sp<WindowInfoHandle> handle = getWindowHandleLocked(connectionToken);
6311 if (handle != nullptr) {
6312 pid = handle->getInfo()->ownerPid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006313 }
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006314 }
Prabir Pradhanedd96402022-02-15 01:46:16 -08006315 sendWindowUnresponsiveCommandLocked(connectionToken, pid, std::move(reason));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006316}
6317
6318/**
6319 * Tell the policy that a connection has become responsive so that it can stop ANR.
6320 */
6321void InputDispatcher::processConnectionResponsiveLocked(const Connection& connection) {
6322 const sp<IBinder>& connectionToken = connection.inputChannel->getConnectionToken();
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00006323 std::optional<gui::Pid> pid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006324 if (connection.monitor) {
Prabir Pradhanedd96402022-02-15 01:46:16 -08006325 pid = findMonitorPidByTokenLocked(connectionToken);
6326 } else {
6327 // The connection is a window
6328 const sp<WindowInfoHandle> handle = getWindowHandleLocked(connectionToken);
6329 if (handle != nullptr) {
6330 pid = handle->getInfo()->ownerPid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006331 }
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006332 }
Prabir Pradhanedd96402022-02-15 01:46:16 -08006333 sendWindowResponsiveCommandLocked(connectionToken, pid);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006334}
6335
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006336bool InputDispatcher::afterKeyEventLockedInterruptable(
6337 const std::shared_ptr<Connection>& connection, DispatchEntry* dispatchEntry,
6338 KeyEntry& keyEntry, bool handled) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006339 if (keyEntry.flags & AKEY_EVENT_FLAG_FALLBACK) {
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006340 if (!handled) {
6341 // Report the key as unhandled, since the fallback was not handled.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006342 mReporter->reportUnhandledKey(keyEntry.id);
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006343 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006344 return false;
6345 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006346
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006347 // Get the fallback key state.
6348 // Clear it out after dispatching the UP.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006349 int32_t originalKeyCode = keyEntry.keyCode;
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006350 std::optional<int32_t> fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006351 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006352 connection->inputState.removeFallbackKey(originalKeyCode);
6353 }
6354
6355 if (handled || !dispatchEntry->hasForegroundTarget()) {
6356 // If the application handles the original key for which we previously
6357 // generated a fallback or if the window is not a foreground window,
6358 // then cancel the associated fallback key, if any.
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006359 if (fallbackKeyCode) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006360 // Dispatch the unhandled key to the policy with the cancel flag.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006361 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6362 ALOGD("Unhandled key event: Asking policy to cancel fallback action. "
6363 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6364 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount,
6365 keyEntry.policyFlags);
6366 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006367 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006368 event.setFlags(event.getFlags() | AKEY_EVENT_FLAG_CANCELED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006369
6370 mLock.unlock();
6371
Prabir Pradhana41d2442023-04-20 21:30:40 +00006372 if (const auto unhandledKeyFallback =
6373 mPolicy.dispatchUnhandledKey(connection->inputChannel->getConnectionToken(),
6374 event, keyEntry.policyFlags);
6375 unhandledKeyFallback) {
6376 event = *unhandledKeyFallback;
6377 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006378
6379 mLock.lock();
6380
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006381 // Cancel the fallback key.
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006382 if (*fallbackKeyCode != AKEYCODE_UNKNOWN) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00006383 CancelationOptions options(CancelationOptions::Mode::CANCEL_FALLBACK_EVENTS,
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006384 "application handled the original non-fallback key "
6385 "or is no longer a foreground target, "
6386 "canceling previously dispatched fallback key");
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006387 options.keyCode = *fallbackKeyCode;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006388 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006389 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006390 connection->inputState.removeFallbackKey(originalKeyCode);
6391 }
6392 } else {
6393 // If the application did not handle a non-fallback key, first check
6394 // that we are in a good state to perform unhandled key event processing
6395 // Then ask the policy what to do with it.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006396 bool initialDown = keyEntry.action == AKEY_EVENT_ACTION_DOWN && keyEntry.repeatCount == 0;
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006397 if (!fallbackKeyCode && !initialDown) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006398 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6399 ALOGD("Unhandled key event: Skipping unhandled key event processing "
6400 "since this is not an initial down. "
6401 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6402 originalKeyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
6403 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006404 return false;
6405 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006406
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006407 // Dispatch the unhandled key to the policy.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006408 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6409 ALOGD("Unhandled key event: Asking policy to perform fallback action. "
6410 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6411 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
6412 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006413 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006414
6415 mLock.unlock();
6416
Prabir Pradhana41d2442023-04-20 21:30:40 +00006417 bool fallback = false;
6418 if (auto fb = mPolicy.dispatchUnhandledKey(connection->inputChannel->getConnectionToken(),
6419 event, keyEntry.policyFlags);
6420 fb) {
6421 fallback = true;
6422 event = *fb;
6423 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006424
6425 mLock.lock();
6426
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08006427 if (connection->status != Connection::Status::NORMAL) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006428 connection->inputState.removeFallbackKey(originalKeyCode);
6429 return false;
6430 }
6431
6432 // Latch the fallback keycode for this key on an initial down.
6433 // The fallback keycode cannot change at any other point in the lifecycle.
6434 if (initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006435 if (fallback) {
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006436 *fallbackKeyCode = event.getKeyCode();
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006437 } else {
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006438 *fallbackKeyCode = AKEYCODE_UNKNOWN;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006439 }
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006440 connection->inputState.setFallbackKey(originalKeyCode, *fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006441 }
6442
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006443 ALOG_ASSERT(fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006444
6445 // Cancel the fallback key if the policy decides not to send it anymore.
6446 // We will continue to dispatch the key to the policy but we will no
6447 // longer dispatch a fallback key to the application.
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006448 if (*fallbackKeyCode != AKEYCODE_UNKNOWN &&
6449 (!fallback || *fallbackKeyCode != event.getKeyCode())) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006450 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6451 if (fallback) {
6452 ALOGD("Unhandled key event: Policy requested to send key %d"
6453 "as a fallback for %d, but on the DOWN it had requested "
6454 "to send %d instead. Fallback canceled.",
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006455 event.getKeyCode(), originalKeyCode, *fallbackKeyCode);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006456 } else {
6457 ALOGD("Unhandled key event: Policy did not request fallback for %d, "
6458 "but on the DOWN it had requested to send %d. "
6459 "Fallback canceled.",
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006460 originalKeyCode, *fallbackKeyCode);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006461 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006462 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006463
Michael Wrightfb04fd52022-11-24 22:31:11 +00006464 CancelationOptions options(CancelationOptions::Mode::CANCEL_FALLBACK_EVENTS,
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006465 "canceling fallback, policy no longer desires it");
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006466 options.keyCode = *fallbackKeyCode;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006467 synthesizeCancelationEventsForConnectionLocked(connection, options);
6468
6469 fallback = false;
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006470 *fallbackKeyCode = AKEYCODE_UNKNOWN;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006471 if (keyEntry.action != AKEY_EVENT_ACTION_UP) {
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006472 connection->inputState.setFallbackKey(originalKeyCode, *fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006473 }
6474 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006475
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006476 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6477 {
6478 std::string msg;
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006479 const std::map<int32_t, int32_t>& fallbackKeys =
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006480 connection->inputState.getFallbackKeys();
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006481 for (const auto& [key, value] : fallbackKeys) {
6482 msg += StringPrintf(", %d->%d", key, value);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006483 }
6484 ALOGD("Unhandled key event: %zu currently tracked fallback keys%s.",
6485 fallbackKeys.size(), msg.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006486 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006487 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006488
6489 if (fallback) {
6490 // Restart the dispatch cycle using the fallback key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006491 keyEntry.eventTime = event.getEventTime();
6492 keyEntry.deviceId = event.getDeviceId();
6493 keyEntry.source = event.getSource();
6494 keyEntry.displayId = event.getDisplayId();
6495 keyEntry.flags = event.getFlags() | AKEY_EVENT_FLAG_FALLBACK;
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006496 keyEntry.keyCode = *fallbackKeyCode;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006497 keyEntry.scanCode = event.getScanCode();
6498 keyEntry.metaState = event.getMetaState();
6499 keyEntry.repeatCount = event.getRepeatCount();
6500 keyEntry.downTime = event.getDownTime();
6501 keyEntry.syntheticRepeat = false;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006502
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006503 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6504 ALOGD("Unhandled key event: Dispatching fallback key. "
6505 "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006506 originalKeyCode, *fallbackKeyCode, keyEntry.metaState);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006507 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006508 return true; // restart the event
6509 } else {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006510 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6511 ALOGD("Unhandled key event: No fallback key.");
6512 }
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006513
6514 // Report the key as unhandled, since there is no fallback key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006515 mReporter->reportUnhandledKey(keyEntry.id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006516 }
6517 }
6518 return false;
6519}
6520
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006521bool InputDispatcher::afterMotionEventLockedInterruptable(
6522 const std::shared_ptr<Connection>& connection, DispatchEntry* dispatchEntry,
6523 MotionEntry& motionEntry, bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006524 return false;
6525}
6526
Michael Wrightd02c5b62014-02-10 15:10:22 -08006527void InputDispatcher::traceInboundQueueLengthLocked() {
6528 if (ATRACE_ENABLED()) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07006529 ATRACE_INT("iq", mInboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006530 }
6531}
6532
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006533void InputDispatcher::traceOutboundQueueLength(const Connection& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006534 if (ATRACE_ENABLED()) {
6535 char counterName[40];
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006536 snprintf(counterName, sizeof(counterName), "oq:%s", connection.getWindowName().c_str());
6537 ATRACE_INT(counterName, connection.outboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006538 }
6539}
6540
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006541void InputDispatcher::traceWaitQueueLength(const Connection& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006542 if (ATRACE_ENABLED()) {
6543 char counterName[40];
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006544 snprintf(counterName, sizeof(counterName), "wq:%s", connection.getWindowName().c_str());
6545 ATRACE_INT(counterName, connection.waitQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006546 }
6547}
6548
Siarhei Vishniakou5e20f272023-06-08 17:24:44 -07006549void InputDispatcher::dump(std::string& dump) const {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006550 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006551
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006552 dump += "Input Dispatcher State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08006553 dumpDispatchStateLocked(dump);
6554
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006555 if (!mLastAnrState.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006556 dump += "\nInput Dispatcher State at time of last ANR:\n";
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006557 dump += mLastAnrState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006558 }
6559}
6560
6561void InputDispatcher::monitor() {
6562 // Acquire and release the lock to ensure that the dispatcher has not deadlocked.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006563 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006564 mLooper->wake();
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006565 mDispatcherIsAlive.wait(_l);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006566}
6567
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08006568/**
6569 * Wake up the dispatcher and wait until it processes all events and commands.
6570 * The notification of mDispatcherEnteredIdle is guaranteed to happen after wake(), so
6571 * this method can be safely called from any thread, as long as you've ensured that
6572 * the work you are interested in completing has already been queued.
6573 */
Siarhei Vishniakoua66d65e2023-06-16 10:32:51 -07006574bool InputDispatcher::waitForIdle() const {
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08006575 /**
6576 * Timeout should represent the longest possible time that a device might spend processing
6577 * events and commands.
6578 */
6579 constexpr std::chrono::duration TIMEOUT = 100ms;
6580 std::unique_lock lock(mLock);
6581 mLooper->wake();
6582 std::cv_status result = mDispatcherEnteredIdle.wait_for(lock, TIMEOUT);
6583 return result == std::cv_status::no_timeout;
6584}
6585
Vishnu Naire798b472020-07-23 13:52:21 -07006586/**
6587 * Sets focus to the window identified by the token. This must be called
6588 * after updating any input window handles.
6589 *
6590 * Params:
6591 * request.token - input channel token used to identify the window that should gain focus.
6592 * request.focusedToken - the token that the caller expects currently to be focused. If the
6593 * specified token does not match the currently focused window, this request will be dropped.
6594 * If the specified focused token matches the currently focused window, the call will succeed.
6595 * Set this to "null" if this call should succeed no matter what the currently focused token is.
6596 * request.timestamp - SYSTEM_TIME_MONOTONIC timestamp in nanos set by the client (wm)
6597 * when requesting the focus change. This determines which request gets
6598 * precedence if there is a focus change request from another source such as pointer down.
6599 */
Vishnu Nair958da932020-08-21 17:12:37 -07006600void InputDispatcher::setFocusedWindow(const FocusRequest& request) {
6601 { // acquire lock
6602 std::scoped_lock _l(mLock);
Vishnu Nairc519ff72021-01-21 08:23:08 -08006603 std::optional<FocusResolver::FocusChanges> changes =
6604 mFocusResolver.setFocusedWindow(request, getWindowHandlesLocked(request.displayId));
6605 if (changes) {
6606 onFocusChangedLocked(*changes);
Vishnu Nair958da932020-08-21 17:12:37 -07006607 }
6608 } // release lock
6609 // Wake up poll loop since it may need to make new input dispatching choices.
6610 mLooper->wake();
6611}
6612
Vishnu Nairc519ff72021-01-21 08:23:08 -08006613void InputDispatcher::onFocusChangedLocked(const FocusResolver::FocusChanges& changes) {
6614 if (changes.oldFocus) {
6615 std::shared_ptr<InputChannel> focusedInputChannel = getInputChannelLocked(changes.oldFocus);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006616 if (focusedInputChannel) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00006617 CancelationOptions options(CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS,
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006618 "focus left window");
6619 synthesizeCancelationEventsForInputChannelLocked(focusedInputChannel, options);
Harry Cutts33476232023-01-30 19:57:29 +00006620 enqueueFocusEventLocked(changes.oldFocus, /*hasFocus=*/false, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006621 }
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006622 }
Vishnu Nairc519ff72021-01-21 08:23:08 -08006623 if (changes.newFocus) {
Harry Cutts33476232023-01-30 19:57:29 +00006624 enqueueFocusEventLocked(changes.newFocus, /*hasFocus=*/true, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006625 }
6626
Prabir Pradhan99987712020-11-10 18:43:05 -08006627 // If a window has pointer capture, then it must have focus. We need to ensure that this
6628 // contract is upheld when pointer capture is being disabled due to a loss of window focus.
6629 // If the window loses focus before it loses pointer capture, then the window can be in a state
6630 // where it has pointer capture but not focus, violating the contract. Therefore we must
6631 // dispatch the pointer capture event before the focus event. Since focus events are added to
6632 // the front of the queue (above), we add the pointer capture event to the front of the queue
6633 // after the focus events are added. This ensures the pointer capture event ends up at the
6634 // front.
6635 disablePointerCaptureForcedLocked();
6636
Vishnu Nairc519ff72021-01-21 08:23:08 -08006637 if (mFocusedDisplayId == changes.displayId) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006638 sendFocusChangedCommandLocked(changes.oldFocus, changes.newFocus);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006639 }
6640}
Vishnu Nair958da932020-08-21 17:12:37 -07006641
Prabir Pradhan99987712020-11-10 18:43:05 -08006642void InputDispatcher::disablePointerCaptureForcedLocked() {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006643 if (!mCurrentPointerCaptureRequest.enable && !mWindowTokenWithPointerCapture) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006644 return;
6645 }
6646
6647 ALOGD_IF(DEBUG_FOCUS, "Disabling Pointer Capture because the window lost focus.");
6648
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006649 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006650 setPointerCaptureLocked(false);
6651 }
6652
6653 if (!mWindowTokenWithPointerCapture) {
6654 // No need to send capture changes because no window has capture.
6655 return;
6656 }
6657
6658 if (mPendingEvent != nullptr) {
6659 // Move the pending event to the front of the queue. This will give the chance
6660 // for the pending event to be dropped if it is a captured event.
6661 mInboundQueue.push_front(mPendingEvent);
6662 mPendingEvent = nullptr;
6663 }
6664
6665 auto entry = std::make_unique<PointerCaptureChangedEntry>(mIdGenerator.nextId(), now(),
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006666 mCurrentPointerCaptureRequest);
Prabir Pradhan99987712020-11-10 18:43:05 -08006667 mInboundQueue.push_front(std::move(entry));
6668}
6669
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006670void InputDispatcher::setPointerCaptureLocked(bool enable) {
6671 mCurrentPointerCaptureRequest.enable = enable;
6672 mCurrentPointerCaptureRequest.seq++;
6673 auto command = [this, request = mCurrentPointerCaptureRequest]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006674 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00006675 mPolicy.setPointerCapture(request);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006676 };
6677 postCommandLocked(std::move(command));
Prabir Pradhan99987712020-11-10 18:43:05 -08006678}
6679
Vishnu Nair599f1412021-06-21 10:39:58 -07006680void InputDispatcher::displayRemoved(int32_t displayId) {
6681 { // acquire lock
6682 std::scoped_lock _l(mLock);
6683 // Set an empty list to remove all handles from the specific display.
Harry Cutts101ee9b2023-07-06 18:04:14 +00006684 setInputWindowsLocked(/*windowInfoHandles=*/{}, displayId);
Vishnu Nair599f1412021-06-21 10:39:58 -07006685 setFocusedApplicationLocked(displayId, nullptr);
6686 // Call focus resolver to clean up stale requests. This must be called after input windows
6687 // have been removed for the removed display.
6688 mFocusResolver.displayRemoved(displayId);
Christine Franksb768bb42021-11-29 12:11:31 -08006689 // Reset pointer capture eligibility, regardless of previous state.
6690 std::erase(mIneligibleDisplaysForPointerCapture, displayId);
Antonio Kantek15beb512022-06-13 22:35:41 +00006691 // Remove the associated touch mode state.
6692 mTouchModePerDisplay.erase(displayId);
Siarhei Vishniakou5c02a712023-05-15 15:45:02 -07006693 mVerifiersByDisplay.erase(displayId);
Vishnu Nair599f1412021-06-21 10:39:58 -07006694 } // release lock
6695
6696 // Wake up poll loop since it may need to make new input dispatching choices.
6697 mLooper->wake();
6698}
6699
Patrick Williamsd828f302023-04-28 17:52:08 -05006700void InputDispatcher::onWindowInfosChanged(const gui::WindowInfosUpdate& update) {
chaviw15fab6f2021-06-07 14:15:52 -05006701 // The listener sends the windows as a flattened array. Separate the windows by display for
6702 // more convenient parsing.
6703 std::unordered_map<int32_t, std::vector<sp<WindowInfoHandle>>> handlesPerDisplay;
Patrick Williamsd828f302023-04-28 17:52:08 -05006704 for (const auto& info : update.windowInfos) {
chaviw15fab6f2021-06-07 14:15:52 -05006705 handlesPerDisplay.emplace(info.displayId, std::vector<sp<WindowInfoHandle>>());
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07006706 handlesPerDisplay[info.displayId].push_back(sp<WindowInfoHandle>::make(info));
chaviw15fab6f2021-06-07 14:15:52 -05006707 }
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006708
6709 { // acquire lock
6710 std::scoped_lock _l(mLock);
Prabir Pradhan814fe082022-07-22 20:22:18 +00006711
6712 // Ensure that we have an entry created for all existing displays so that if a displayId has
6713 // no windows, we can tell that the windows were removed from the display.
6714 for (const auto& [displayId, _] : mWindowHandlesByDisplay) {
6715 handlesPerDisplay[displayId];
6716 }
6717
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006718 mDisplayInfos.clear();
Patrick Williamsd828f302023-04-28 17:52:08 -05006719 for (const auto& displayInfo : update.displayInfos) {
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006720 mDisplayInfos.emplace(displayInfo.displayId, displayInfo);
6721 }
6722
6723 for (const auto& [displayId, handles] : handlesPerDisplay) {
6724 setInputWindowsLocked(handles, displayId);
6725 }
Patrick Williams9464b2c2023-05-23 11:22:04 -05006726
6727 if (update.vsyncId < mWindowInfosVsyncId) {
6728 ALOGE("Received out of order window infos update. Last update vsync id: %" PRId64
6729 ", current update vsync id: %" PRId64,
6730 mWindowInfosVsyncId, update.vsyncId);
6731 }
6732 mWindowInfosVsyncId = update.vsyncId;
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006733 }
6734 // Wake up poll loop since it may need to make new input dispatching choices.
6735 mLooper->wake();
chaviw15fab6f2021-06-07 14:15:52 -05006736}
6737
Vishnu Nair062a8672021-09-03 16:07:44 -07006738bool InputDispatcher::shouldDropInput(
6739 const EventEntry& entry, const sp<android::gui::WindowInfoHandle>& windowHandle) const {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006740 if (windowHandle->getInfo()->inputConfig.test(WindowInfo::InputConfig::DROP_INPUT) ||
6741 (windowHandle->getInfo()->inputConfig.test(
6742 WindowInfo::InputConfig::DROP_INPUT_IF_OBSCURED) &&
Vishnu Nair062a8672021-09-03 16:07:44 -07006743 isWindowObscuredLocked(windowHandle))) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006744 ALOGW("Dropping %s event targeting %s as requested by the input configuration {%s} on "
6745 "display %" PRId32 ".",
Vishnu Nair062a8672021-09-03 16:07:44 -07006746 ftl::enum_string(entry.type).c_str(), windowHandle->getName().c_str(),
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006747 windowHandle->getInfo()->inputConfig.string().c_str(),
Vishnu Nair062a8672021-09-03 16:07:44 -07006748 windowHandle->getInfo()->displayId);
6749 return true;
6750 }
6751 return false;
6752}
6753
Siarhei Vishniakou18050092021-09-01 13:32:49 -07006754void InputDispatcher::DispatcherWindowListener::onWindowInfosChanged(
Patrick Williamsd828f302023-04-28 17:52:08 -05006755 const gui::WindowInfosUpdate& update) {
6756 mDispatcher.onWindowInfosChanged(update);
Siarhei Vishniakou18050092021-09-01 13:32:49 -07006757}
6758
Arthur Hungdfd528e2021-12-08 13:23:04 +00006759void InputDispatcher::cancelCurrentTouch() {
6760 {
6761 std::scoped_lock _l(mLock);
6762 ALOGD("Canceling all ongoing pointer gestures on all displays.");
Michael Wrightfb04fd52022-11-24 22:31:11 +00006763 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
Arthur Hungdfd528e2021-12-08 13:23:04 +00006764 "cancel current touch");
6765 synthesizeCancelationEventsForAllConnectionsLocked(options);
6766
6767 mTouchStatesByDisplay.clear();
Arthur Hungdfd528e2021-12-08 13:23:04 +00006768 }
6769 // Wake up poll loop since there might be work to do.
6770 mLooper->wake();
6771}
6772
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006773void InputDispatcher::setMonitorDispatchingTimeoutForTest(std::chrono::nanoseconds timeout) {
6774 std::scoped_lock _l(mLock);
6775 mMonitorDispatchingTimeout = timeout;
6776}
6777
Arthur Hungc539dbb2022-12-08 07:45:36 +00006778void InputDispatcher::slipWallpaperTouch(ftl::Flags<InputTarget::Flags> targetFlags,
6779 const sp<WindowInfoHandle>& oldWindowHandle,
6780 const sp<WindowInfoHandle>& newWindowHandle,
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07006781 TouchState& state, int32_t deviceId, int32_t pointerId,
Siarhei Vishniakoubf880522023-05-01 11:03:22 -07006782 std::vector<InputTarget>& targets) const {
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08006783 std::bitset<MAX_POINTER_ID + 1> pointerIds;
6784 pointerIds.set(pointerId);
Arthur Hungc539dbb2022-12-08 07:45:36 +00006785 const bool oldHasWallpaper = oldWindowHandle->getInfo()->inputConfig.test(
6786 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
6787 const bool newHasWallpaper = targetFlags.test(InputTarget::Flags::FOREGROUND) &&
6788 newWindowHandle->getInfo()->inputConfig.test(
6789 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
6790 const sp<WindowInfoHandle> oldWallpaper =
6791 oldHasWallpaper ? state.getWallpaperWindow() : nullptr;
6792 const sp<WindowInfoHandle> newWallpaper =
6793 newHasWallpaper ? findWallpaperWindowBelow(newWindowHandle) : nullptr;
6794 if (oldWallpaper == newWallpaper) {
6795 return;
6796 }
6797
6798 if (oldWallpaper != nullptr) {
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08006799 const TouchedWindow& oldTouchedWindow = state.getTouchedWindow(oldWallpaper);
6800 addWindowTargetLocked(oldWallpaper,
6801 oldTouchedWindow.targetFlags |
6802 InputTarget::Flags::DISPATCH_AS_SLIPPERY_EXIT,
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07006803 pointerIds, oldTouchedWindow.getDownTimeInTarget(deviceId), targets);
6804 state.removeTouchingPointerFromWindow(deviceId, pointerId, oldWallpaper);
Arthur Hungc539dbb2022-12-08 07:45:36 +00006805 }
6806
6807 if (newWallpaper != nullptr) {
6808 state.addOrUpdateWindow(newWallpaper,
6809 InputTarget::Flags::DISPATCH_AS_SLIPPERY_ENTER |
6810 InputTarget::Flags::WINDOW_IS_OBSCURED |
6811 InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED,
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07006812 deviceId, pointerIds);
Arthur Hungc539dbb2022-12-08 07:45:36 +00006813 }
6814}
6815
6816void InputDispatcher::transferWallpaperTouch(ftl::Flags<InputTarget::Flags> oldTargetFlags,
6817 ftl::Flags<InputTarget::Flags> newTargetFlags,
6818 const sp<WindowInfoHandle> fromWindowHandle,
6819 const sp<WindowInfoHandle> toWindowHandle,
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07006820 TouchState& state, int32_t deviceId,
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08006821 std::bitset<MAX_POINTER_ID + 1> pointerIds) {
Arthur Hungc539dbb2022-12-08 07:45:36 +00006822 const bool oldHasWallpaper = oldTargetFlags.test(InputTarget::Flags::FOREGROUND) &&
6823 fromWindowHandle->getInfo()->inputConfig.test(
6824 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
6825 const bool newHasWallpaper = newTargetFlags.test(InputTarget::Flags::FOREGROUND) &&
6826 toWindowHandle->getInfo()->inputConfig.test(
6827 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
6828
6829 const sp<WindowInfoHandle> oldWallpaper =
6830 oldHasWallpaper ? state.getWallpaperWindow() : nullptr;
6831 const sp<WindowInfoHandle> newWallpaper =
6832 newHasWallpaper ? findWallpaperWindowBelow(toWindowHandle) : nullptr;
6833 if (oldWallpaper == newWallpaper) {
6834 return;
6835 }
6836
6837 if (oldWallpaper != nullptr) {
6838 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
6839 "transferring touch focus to another window");
6840 state.removeWindowByToken(oldWallpaper->getToken());
6841 synthesizeCancelationEventsForWindowLocked(oldWallpaper, options);
6842 }
6843
6844 if (newWallpaper != nullptr) {
6845 nsecs_t downTimeInTarget = now();
6846 ftl::Flags<InputTarget::Flags> wallpaperFlags =
6847 oldTargetFlags & (InputTarget::Flags::SPLIT | InputTarget::Flags::DISPATCH_AS_IS);
6848 wallpaperFlags |= InputTarget::Flags::WINDOW_IS_OBSCURED |
6849 InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED;
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07006850 state.addOrUpdateWindow(newWallpaper, wallpaperFlags, deviceId, pointerIds,
6851 downTimeInTarget);
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006852 std::shared_ptr<Connection> wallpaperConnection =
6853 getConnectionLocked(newWallpaper->getToken());
Arthur Hungc539dbb2022-12-08 07:45:36 +00006854 if (wallpaperConnection != nullptr) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006855 std::shared_ptr<Connection> toConnection =
6856 getConnectionLocked(toWindowHandle->getToken());
Arthur Hungc539dbb2022-12-08 07:45:36 +00006857 toConnection->inputState.mergePointerStateTo(wallpaperConnection->inputState);
6858 synthesizePointerDownEventsForConnectionLocked(downTimeInTarget, wallpaperConnection,
6859 wallpaperFlags);
6860 }
6861 }
6862}
6863
6864sp<WindowInfoHandle> InputDispatcher::findWallpaperWindowBelow(
6865 const sp<WindowInfoHandle>& windowHandle) const {
6866 const std::vector<sp<WindowInfoHandle>>& windowHandles =
6867 getWindowHandlesLocked(windowHandle->getInfo()->displayId);
6868 bool foundWindow = false;
6869 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
6870 if (!foundWindow && otherHandle != windowHandle) {
6871 continue;
6872 }
6873 if (windowHandle == otherHandle) {
6874 foundWindow = true;
6875 continue;
6876 }
6877
6878 if (otherHandle->getInfo()->inputConfig.test(WindowInfo::InputConfig::IS_WALLPAPER)) {
6879 return otherHandle;
6880 }
6881 }
6882 return nullptr;
6883}
6884
Nergi Rahardi730cf3c2023-04-13 12:41:17 +09006885void InputDispatcher::setKeyRepeatConfiguration(nsecs_t timeout, nsecs_t delay) {
6886 std::scoped_lock _l(mLock);
6887
6888 mConfig.keyRepeatTimeout = timeout;
6889 mConfig.keyRepeatDelay = delay;
6890}
6891
Garfield Tane84e6f92019-08-29 17:28:41 -07006892} // namespace android::inputdispatcher