blob: 7fbd3223859b4d289e2c10031dbb8cf0d56438ae [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>
Prabir Pradhana37bad12023-08-18 15:55:32 +000035#include <input/TraceTools.h>
tyiu1573a672023-02-21 22:38:32 +000036#include <openssl/mem.h>
Garfield Tan0fc2fa72019-08-29 17:22:15 -070037#include <powermanager/PowerManager.h>
Michael Wright44753b12020-07-08 13:48:11 +010038#include <unistd.h>
Garfield Tan0fc2fa72019-08-29 17:22:15 -070039#include <utils/Trace.h>
Michael Wrightd02c5b62014-02-10 15:10:22 -080040
Michael Wright44753b12020-07-08 13:48:11 +010041#include <cerrno>
42#include <cinttypes>
43#include <climits>
44#include <cstddef>
45#include <ctime>
46#include <queue>
47#include <sstream>
48
49#include "Connection.h"
Arthur Hung1a1007b2022-05-11 07:15:01 +000050#include "DebugConfig.h"
Chris Yef59a2f42020-10-16 12:55:26 -070051#include "InputDispatcher.h"
Michael Wright44753b12020-07-08 13:48:11 +010052
Michael Wrightd02c5b62014-02-10 15:10:22 -080053#define INDENT " "
54#define INDENT2 " "
55#define INDENT3 " "
56#define INDENT4 " "
57
Siarhei Vishniakou253f4642022-11-09 13:42:06 -080058using namespace android::ftl::flag_operators;
Siarhei Vishniakou23740b92023-04-21 11:30:20 -070059using android::base::Error;
Peter Collingbourneb04b9b82021-02-08 12:09:47 -080060using android::base::HwTimeoutMultiplier;
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +000061using android::base::Result;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080062using android::base::StringPrintf;
Prabir Pradhan48f8cb92021-08-26 14:05:36 -070063using android::gui::DisplayInfo;
chaviw98318de2021-05-19 16:45:23 -050064using android::gui::FocusRequest;
65using android::gui::TouchOcclusionMode;
66using android::gui::WindowInfo;
67using android::gui::WindowInfoHandle;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -080068using android::os::InputEventInjectionResult;
69using android::os::InputEventInjectionSync;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080070
Garfield Tane84e6f92019-08-29 17:28:41 -070071namespace android::inputdispatcher {
Michael Wrightd02c5b62014-02-10 15:10:22 -080072
Prabir Pradhancef936d2021-07-21 16:17:52 +000073namespace {
Prabir Pradhancef936d2021-07-21 16:17:52 +000074// Temporarily releases a held mutex for the lifetime of the instance.
75// Named to match std::scoped_lock
76class scoped_unlock {
77public:
78 explicit scoped_unlock(std::mutex& mutex) : mMutex(mutex) { mMutex.unlock(); }
79 ~scoped_unlock() { mMutex.lock(); }
80
81private:
82 std::mutex& mMutex;
83};
84
Michael Wrightd02c5b62014-02-10 15:10:22 -080085// Default input dispatching timeout if there is no focused application or paused window
86// from which to determine an appropriate dispatching timeout.
Peter Collingbourneb04b9b82021-02-08 12:09:47 -080087const std::chrono::duration DEFAULT_INPUT_DISPATCHING_TIMEOUT = std::chrono::milliseconds(
88 android::os::IInputConstants::UNMULTIPLIED_DEFAULT_DISPATCHING_TIMEOUT_MILLIS *
89 HwTimeoutMultiplier());
Michael Wrightd02c5b62014-02-10 15:10:22 -080090
91// Amount of time to allow for all pending events to be processed when an app switch
92// key is on the way. This is used to preempt input dispatch and drop input events
93// when an application takes too long to respond and the user has pressed an app switch key.
Michael Wright2b3c3302018-03-02 17:19:13 +000094constexpr nsecs_t APP_SWITCH_TIMEOUT = 500 * 1000000LL; // 0.5sec
Michael Wrightd02c5b62014-02-10 15:10:22 -080095
Siarhei Vishniakou289e9242022-02-15 14:50:16 -080096const std::chrono::duration STALE_EVENT_TIMEOUT = std::chrono::seconds(10) * HwTimeoutMultiplier();
Michael Wrightd02c5b62014-02-10 15:10:22 -080097
Michael Wrightd02c5b62014-02-10 15:10:22 -080098// 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 +000099constexpr nsecs_t SLOW_EVENT_PROCESSING_WARNING_TIMEOUT = 2000 * 1000000LL; // 2sec
100
101// Log a warning when an interception call takes longer than this to process.
102constexpr std::chrono::milliseconds SLOW_INTERCEPTION_THRESHOLD = 50ms;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800103
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700104// Additional key latency in case a connection is still processing some motion events.
105// This will help with the case when a user touched a button that opens a new window,
106// and gives us the chance to dispatch the key to this new window.
107constexpr std::chrono::nanoseconds KEY_WAITING_FOR_EVENTS_TIMEOUT = 500ms;
108
Michael Wrightd02c5b62014-02-10 15:10:22 -0800109// Number of recent events to keep for debugging purposes.
Michael Wright2b3c3302018-03-02 17:19:13 +0000110constexpr size_t RECENT_QUEUE_MAX_SIZE = 10;
111
Antonio Kantekea47acb2021-12-23 12:41:25 -0800112// Event log tags. See EventLogTags.logtags for reference.
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +0000113constexpr int LOGTAG_INPUT_INTERACTION = 62000;
114constexpr int LOGTAG_INPUT_FOCUS = 62001;
Arthur Hungb3307ee2021-10-14 10:57:37 +0000115constexpr int LOGTAG_INPUT_CANCEL = 62003;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +0000116
Prabir Pradhan33e3baa2022-12-06 20:30:22 +0000117const ui::Transform kIdentityTransform;
118
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000119inline nsecs_t now() {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800120 return systemTime(SYSTEM_TIME_MONOTONIC);
121}
122
Siarhei Vishniakoud38a1e02023-07-18 11:55:17 -0700123bool isEmpty(const std::stringstream& ss) {
124 return ss.rdbuf()->in_avail() == 0;
125}
126
Siarhei Vishniakou63b63612023-04-12 11:00:23 -0700127inline const std::string binderToString(const sp<IBinder>& binder) {
Bernardo Rufino49d99e42021-01-18 15:16:59 +0000128 if (binder == nullptr) {
129 return "<null>";
130 }
131 return StringPrintf("%p", binder.get());
132}
133
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +0000134static std::string uidString(const gui::Uid& uid) {
135 return uid.toString();
136}
137
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700138Result<void> checkKeyAction(int32_t action) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800139 switch (action) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700140 case AKEY_EVENT_ACTION_DOWN:
141 case AKEY_EVENT_ACTION_UP:
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700142 return {};
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700143 default:
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700144 return Error() << "Key event has invalid action code " << action;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800145 }
146}
147
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700148Result<void> validateKeyEvent(int32_t action) {
149 return checkKeyAction(action);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800150}
151
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700152Result<void> checkMotionAction(int32_t action, int32_t actionButton, int32_t pointerCount) {
Siarhei Vishniakou2f61bdc2022-12-02 08:55:51 -0800153 switch (MotionEvent::getActionMasked(action)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700154 case AMOTION_EVENT_ACTION_DOWN:
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700155 case AMOTION_EVENT_ACTION_UP: {
156 if (pointerCount != 1) {
157 return Error() << "invalid pointer count " << pointerCount;
158 }
159 return {};
160 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700161 case AMOTION_EVENT_ACTION_MOVE:
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700162 case AMOTION_EVENT_ACTION_HOVER_ENTER:
163 case AMOTION_EVENT_ACTION_HOVER_MOVE:
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700164 case AMOTION_EVENT_ACTION_HOVER_EXIT: {
165 if (pointerCount < 1) {
166 return Error() << "invalid pointer count " << pointerCount;
167 }
168 return {};
169 }
Siarhei Vishniakou2f61bdc2022-12-02 08:55:51 -0800170 case AMOTION_EVENT_ACTION_CANCEL:
171 case AMOTION_EVENT_ACTION_OUTSIDE:
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700172 case AMOTION_EVENT_ACTION_SCROLL:
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700173 return {};
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700174 case AMOTION_EVENT_ACTION_POINTER_DOWN:
175 case AMOTION_EVENT_ACTION_POINTER_UP: {
Siarhei Vishniakou2f61bdc2022-12-02 08:55:51 -0800176 const int32_t index = MotionEvent::getActionIndex(action);
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700177 if (index < 0) {
178 return Error() << "invalid index " << index << " for "
179 << MotionEvent::actionToString(action);
180 }
181 if (index >= pointerCount) {
182 return Error() << "invalid index " << index << " for pointerCount " << pointerCount;
183 }
184 if (pointerCount <= 1) {
185 return Error() << "invalid pointer count " << pointerCount << " for "
186 << MotionEvent::actionToString(action);
187 }
188 return {};
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700189 }
190 case AMOTION_EVENT_ACTION_BUTTON_PRESS:
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700191 case AMOTION_EVENT_ACTION_BUTTON_RELEASE: {
192 if (actionButton == 0) {
193 return Error() << "action button should be nonzero for "
194 << MotionEvent::actionToString(action);
195 }
196 return {};
197 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700198 default:
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700199 return Error() << "invalid action " << action;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800200 }
201}
202
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000203int64_t millis(std::chrono::nanoseconds t) {
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -0500204 return std::chrono::duration_cast<std::chrono::milliseconds>(t).count();
205}
206
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700207Result<void> validateMotionEvent(int32_t action, int32_t actionButton, size_t pointerCount,
208 const PointerProperties* pointerProperties) {
209 Result<void> actionCheck = checkMotionAction(action, actionButton, pointerCount);
210 if (!actionCheck.ok()) {
211 return actionCheck;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800212 }
213 if (pointerCount < 1 || pointerCount > MAX_POINTERS) {
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700214 return Error() << "Motion event has invalid pointer count " << pointerCount
215 << "; value must be between 1 and " << MAX_POINTERS << ".";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800216 }
Siarhei Vishniakou8a878352023-01-30 14:05:01 -0800217 std::bitset<MAX_POINTER_ID + 1> pointerIdBits;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800218 for (size_t i = 0; i < pointerCount; i++) {
219 int32_t id = pointerProperties[i].id;
220 if (id < 0 || id > MAX_POINTER_ID) {
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700221 return Error() << "Motion event has invalid pointer id " << id
222 << "; value must be between 0 and " << MAX_POINTER_ID;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800223 }
Siarhei Vishniakou8a878352023-01-30 14:05:01 -0800224 if (pointerIdBits.test(id)) {
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700225 return Error() << "Motion event has duplicate pointer id " << id;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800226 }
Siarhei Vishniakou8a878352023-01-30 14:05:01 -0800227 pointerIdBits.set(id);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800228 }
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700229 return {};
230}
231
232Result<void> validateInputEvent(const InputEvent& event) {
233 switch (event.getType()) {
234 case InputEventType::KEY: {
235 const KeyEvent& key = static_cast<const KeyEvent&>(event);
236 const int32_t action = key.getAction();
237 return validateKeyEvent(action);
238 }
239 case InputEventType::MOTION: {
240 const MotionEvent& motion = static_cast<const MotionEvent&>(event);
241 const int32_t action = motion.getAction();
242 const size_t pointerCount = motion.getPointerCount();
243 const PointerProperties* pointerProperties = motion.getPointerProperties();
244 const int32_t actionButton = motion.getActionButton();
245 return validateMotionEvent(action, actionButton, pointerCount, pointerProperties);
246 }
247 default: {
248 return {};
249 }
250 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800251}
252
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000253std::string dumpRegion(const Region& region) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800254 if (region.isEmpty()) {
Bernardo Rufino53fc31e2020-11-03 11:01:07 +0000255 return "<empty>";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800256 }
257
Bernardo Rufino53fc31e2020-11-03 11:01:07 +0000258 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800259 bool first = true;
260 Region::const_iterator cur = region.begin();
261 Region::const_iterator const tail = region.end();
262 while (cur != tail) {
263 if (first) {
264 first = false;
265 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800266 dump += "|";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800267 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800268 dump += StringPrintf("[%d,%d][%d,%d]", cur->left, cur->top, cur->right, cur->bottom);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800269 cur++;
270 }
Bernardo Rufino53fc31e2020-11-03 11:01:07 +0000271 return dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800272}
273
Prabir Pradhan8c90d782023-09-15 21:16:44 +0000274std::string dumpQueue(const std::deque<std::unique_ptr<DispatchEntry>>& queue,
275 nsecs_t currentTime) {
Siarhei Vishniakou14411c92020-09-18 21:15:05 -0500276 constexpr size_t maxEntries = 50; // max events to print
277 constexpr size_t skipBegin = maxEntries / 2;
278 const size_t skipEnd = queue.size() - maxEntries / 2;
279 // skip from maxEntries / 2 ... size() - maxEntries/2
280 // only print from 0 .. skipBegin and then from skipEnd .. size()
281
282 std::string dump;
283 for (size_t i = 0; i < queue.size(); i++) {
284 const DispatchEntry& entry = *queue[i];
285 if (i >= skipBegin && i < skipEnd) {
286 dump += StringPrintf(INDENT4 "<skipped %zu entries>\n", skipEnd - skipBegin);
287 i = skipEnd - 1; // it will be incremented to "skipEnd" by 'continue'
288 continue;
289 }
290 dump.append(INDENT4);
291 dump += entry.eventEntry->getDescription();
Siarhei Vishniakou253f4642022-11-09 13:42:06 -0800292 dump += StringPrintf(", seq=%" PRIu32 ", targetFlags=%s, resolvedAction=%d, age=%" PRId64
293 "ms",
294 entry.seq, entry.targetFlags.string().c_str(), entry.resolvedAction,
Siarhei Vishniakou14411c92020-09-18 21:15:05 -0500295 ns2ms(currentTime - entry.eventEntry->eventTime));
296 if (entry.deliveryTime != 0) {
297 // This entry was delivered, so add information on how long we've been waiting
298 dump += StringPrintf(", wait=%" PRId64 "ms", ns2ms(currentTime - entry.deliveryTime));
299 }
300 dump.append("\n");
301 }
302 return dump;
303}
304
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -0700305/**
306 * Find the entry in std::unordered_map by key, and return it.
307 * If the entry is not found, return a default constructed entry.
308 *
309 * Useful when the entries are vectors, since an empty vector will be returned
310 * if the entry is not found.
311 * Also useful when the entries are sp<>. If an entry is not found, nullptr is returned.
312 */
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700313template <typename K, typename V>
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000314V getValueByKey(const std::unordered_map<K, V>& map, K key) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -0700315 auto it = map.find(key);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700316 return it != map.end() ? it->second : V{};
Tiger Huang721e26f2018-07-24 22:26:19 +0800317}
318
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000319bool haveSameToken(const sp<WindowInfoHandle>& first, const sp<WindowInfoHandle>& second) {
chaviwaf87b3e2019-10-01 16:59:28 -0700320 if (first == second) {
321 return true;
322 }
323
324 if (first == nullptr || second == nullptr) {
325 return false;
326 }
327
328 return first->getToken() == second->getToken();
329}
330
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000331bool haveSameApplicationToken(const WindowInfo* first, const WindowInfo* second) {
Bernardo Rufino1ff9d592021-01-18 16:58:57 +0000332 if (first == nullptr || second == nullptr) {
333 return false;
334 }
335 return first->applicationInfo.token != nullptr &&
336 first->applicationInfo.token == second->applicationInfo.token;
337}
338
Siarhei Vishniakou8a878352023-01-30 14:05:01 -0800339template <typename T>
340size_t firstMarkedBit(T set) {
341 // TODO: replace with std::countr_zero from <bit> when that's available
342 LOG_ALWAYS_FATAL_IF(set.none());
343 size_t i = 0;
344 while (!set.test(i)) {
345 i++;
346 }
347 return i;
348}
349
Siarhei Vishniakou253f4642022-11-09 13:42:06 -0800350std::unique_ptr<DispatchEntry> createDispatchEntry(
351 const InputTarget& inputTarget, std::shared_ptr<EventEntry> eventEntry,
352 ftl::Flags<InputTarget::Flags> inputTargetFlags) {
chaviw1ff3d1e2020-07-01 15:53:47 -0700353 if (inputTarget.useDefaultPointerTransform()) {
354 const ui::Transform& transform = inputTarget.getDefaultPointerTransform();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700355 return std::make_unique<DispatchEntry>(eventEntry, inputTargetFlags, transform,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700356 inputTarget.displayTransform,
357 inputTarget.globalScaleFactor);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000358 }
359
360 ALOG_ASSERT(eventEntry->type == EventEntry::Type::MOTION);
361 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(*eventEntry);
362
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700363 std::vector<PointerCoords> pointerCoords;
364 pointerCoords.resize(motionEntry.pointerCount);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000365
366 // Use the first pointer information to normalize all other pointers. This could be any pointer
367 // as long as all other pointers are normalized to the same value and the final DispatchEntry
chaviw1ff3d1e2020-07-01 15:53:47 -0700368 // uses the transform for the normalized pointer.
369 const ui::Transform& firstPointerTransform =
Siarhei Vishniakou8a878352023-01-30 14:05:01 -0800370 inputTarget.pointerTransforms[firstMarkedBit(inputTarget.pointerIds)];
chaviw1ff3d1e2020-07-01 15:53:47 -0700371 ui::Transform inverseFirstTransform = firstPointerTransform.inverse();
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000372
373 // Iterate through all pointers in the event to normalize against the first.
374 for (uint32_t pointerIndex = 0; pointerIndex < motionEntry.pointerCount; pointerIndex++) {
375 const PointerProperties& pointerProperties = motionEntry.pointerProperties[pointerIndex];
376 uint32_t pointerId = uint32_t(pointerProperties.id);
chaviw1ff3d1e2020-07-01 15:53:47 -0700377 const ui::Transform& currTransform = inputTarget.pointerTransforms[pointerId];
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000378
379 pointerCoords[pointerIndex].copyFrom(motionEntry.pointerCoords[pointerIndex]);
chaviw1ff3d1e2020-07-01 15:53:47 -0700380 // First, apply the current pointer's transform to update the coordinates into
381 // window space.
382 pointerCoords[pointerIndex].transform(currTransform);
383 // Next, apply the inverse transform of the normalized coordinates so the
384 // current coordinates are transformed into the normalized coordinate space.
385 pointerCoords[pointerIndex].transform(inverseFirstTransform);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000386 }
387
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700388 std::unique_ptr<MotionEntry> combinedMotionEntry =
389 std::make_unique<MotionEntry>(motionEntry.id, motionEntry.eventTime,
390 motionEntry.deviceId, motionEntry.source,
391 motionEntry.displayId, motionEntry.policyFlags,
392 motionEntry.action, motionEntry.actionButton,
393 motionEntry.flags, motionEntry.metaState,
394 motionEntry.buttonState, motionEntry.classification,
395 motionEntry.edgeFlags, motionEntry.xPrecision,
396 motionEntry.yPrecision, motionEntry.xCursorPosition,
397 motionEntry.yCursorPosition, motionEntry.downTime,
398 motionEntry.pointerCount, motionEntry.pointerProperties,
Prabir Pradhan5beda762021-12-10 09:30:08 +0000399 pointerCoords.data());
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000400
401 if (motionEntry.injectionState) {
402 combinedMotionEntry->injectionState = motionEntry.injectionState;
403 combinedMotionEntry->injectionState->refCount += 1;
404 }
405
406 std::unique_ptr<DispatchEntry> dispatchEntry =
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700407 std::make_unique<DispatchEntry>(std::move(combinedMotionEntry), inputTargetFlags,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700408 firstPointerTransform, inputTarget.displayTransform,
409 inputTarget.globalScaleFactor);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000410 return dispatchEntry;
411}
412
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000413status_t openInputChannelPair(const std::string& name, std::shared_ptr<InputChannel>& serverChannel,
414 std::unique_ptr<InputChannel>& clientChannel) {
Garfield Tan15601662020-09-22 15:32:38 -0700415 std::unique_ptr<InputChannel> uniqueServerChannel;
416 status_t result = InputChannel::openInputChannelPair(name, uniqueServerChannel, clientChannel);
417
418 serverChannel = std::move(uniqueServerChannel);
419 return result;
420}
421
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -0500422template <typename T>
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000423bool sharedPointersEqual(const std::shared_ptr<T>& lhs, const std::shared_ptr<T>& rhs) {
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -0500424 if (lhs == nullptr && rhs == nullptr) {
425 return true;
426 }
427 if (lhs == nullptr || rhs == nullptr) {
428 return false;
429 }
430 return *lhs == *rhs;
431}
432
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000433KeyEvent createKeyEvent(const KeyEntry& entry) {
Siarhei Vishniakou2e2ea992020-12-15 02:57:19 +0000434 KeyEvent event;
435 event.initialize(entry.id, entry.deviceId, entry.source, entry.displayId, INVALID_HMAC,
436 entry.action, entry.flags, entry.keyCode, entry.scanCode, entry.metaState,
437 entry.repeatCount, entry.downTime, entry.eventTime);
438 return event;
439}
440
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000441bool shouldReportMetricsForConnection(const Connection& connection) {
Siarhei Vishniakouf2652122021-03-05 21:39:46 +0000442 // Do not keep track of gesture monitors. They receive every event and would disproportionately
443 // affect the statistics.
444 if (connection.monitor) {
445 return false;
446 }
447 // If the connection is experiencing ANR, let's skip it. We have separate ANR metrics
448 if (!connection.responsive) {
449 return false;
450 }
451 return true;
452}
453
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000454bool shouldReportFinishedEvent(const DispatchEntry& dispatchEntry, const Connection& connection) {
Siarhei Vishniakouf2652122021-03-05 21:39:46 +0000455 const EventEntry& eventEntry = *dispatchEntry.eventEntry;
456 const int32_t& inputEventId = eventEntry.id;
457 if (inputEventId != dispatchEntry.resolvedEventId) {
458 // Event was transmuted
459 return false;
460 }
461 if (inputEventId == android::os::IInputConstants::INVALID_INPUT_EVENT_ID) {
462 return false;
463 }
464 // Only track latency for events that originated from hardware
465 if (eventEntry.isSynthesized()) {
466 return false;
467 }
468 const EventEntry::Type& inputEventEntryType = eventEntry.type;
469 if (inputEventEntryType == EventEntry::Type::KEY) {
470 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
471 if (keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) {
472 return false;
473 }
474 } else if (inputEventEntryType == EventEntry::Type::MOTION) {
475 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
476 if (motionEntry.action == AMOTION_EVENT_ACTION_CANCEL ||
477 motionEntry.action == AMOTION_EVENT_ACTION_HOVER_EXIT) {
478 return false;
479 }
480 } else {
481 // Not a key or a motion
482 return false;
483 }
484 if (!shouldReportMetricsForConnection(connection)) {
485 return false;
486 }
487 return true;
488}
489
Prabir Pradhancef936d2021-07-21 16:17:52 +0000490/**
491 * Connection is responsive if it has no events in the waitQueue that are older than the
492 * current time.
493 */
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000494bool isConnectionResponsive(const Connection& connection) {
Prabir Pradhancef936d2021-07-21 16:17:52 +0000495 const nsecs_t currentTime = now();
Prabir Pradhan8c90d782023-09-15 21:16:44 +0000496 for (const auto& dispatchEntry : connection.waitQueue) {
497 if (dispatchEntry->timeoutTime < currentTime) {
Prabir Pradhancef936d2021-07-21 16:17:52 +0000498 return false;
499 }
500 }
501 return true;
502}
503
Antonio Kantekf16f2832021-09-28 04:39:20 +0000504// Returns true if the event type passed as argument represents a user activity.
505bool isUserActivityEvent(const EventEntry& eventEntry) {
506 switch (eventEntry.type) {
Josep del Riob3981622023-04-18 15:49:45 +0000507 case EventEntry::Type::CONFIGURATION_CHANGED:
508 case EventEntry::Type::DEVICE_RESET:
509 case EventEntry::Type::DRAG:
Antonio Kantekf16f2832021-09-28 04:39:20 +0000510 case EventEntry::Type::FOCUS:
511 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
Antonio Kantekf16f2832021-09-28 04:39:20 +0000512 case EventEntry::Type::SENSOR:
Josep del Riob3981622023-04-18 15:49:45 +0000513 case EventEntry::Type::TOUCH_MODE_CHANGED:
Antonio Kantekf16f2832021-09-28 04:39:20 +0000514 return false;
Antonio Kantekf16f2832021-09-28 04:39:20 +0000515 case EventEntry::Type::KEY:
516 case EventEntry::Type::MOTION:
517 return true;
518 }
519}
520
Prabir Pradhan3f90d312021-11-19 03:57:24 -0800521// Returns true if the given window can accept pointer events at the given display location.
Prabir Pradhan82e081e2022-12-06 09:50:09 +0000522bool windowAcceptsTouchAt(const WindowInfo& windowInfo, int32_t displayId, float x, float y,
Prabir Pradhan33e3baa2022-12-06 20:30:22 +0000523 bool isStylus, const ui::Transform& displayTransform) {
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -0800524 const auto inputConfig = windowInfo.inputConfig;
525 if (windowInfo.displayId != displayId ||
526 inputConfig.test(WindowInfo::InputConfig::NOT_VISIBLE)) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -0800527 return false;
528 }
Prabir Pradhand65552b2021-10-07 11:23:50 -0700529 const bool windowCanInterceptTouch = isStylus && windowInfo.interceptsStylus();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -0800530 if (inputConfig.test(WindowInfo::InputConfig::NOT_TOUCHABLE) && !windowCanInterceptTouch) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -0800531 return false;
532 }
Prabir Pradhan33e3baa2022-12-06 20:30:22 +0000533
534 // Window Manager works in the logical display coordinate space. When it specifies bounds for a
535 // window as (l, t, r, b), the range of x in [l, r) and y in [t, b) are considered to be inside
536 // the window. Points on the right and bottom edges should not be inside the window, so we need
537 // to be careful about performing a hit test when the display is rotated, since the "right" and
538 // "bottom" of the window will be different in the display (un-rotated) space compared to in the
539 // logical display in which WM determined the bounds. Perform the hit test in the logical
540 // display space to ensure these edges are considered correctly in all orientations.
541 const auto touchableRegion = displayTransform.transform(windowInfo.touchableRegion);
542 const auto p = displayTransform.transform(x, y);
543 if (!touchableRegion.contains(std::floor(p.x), std::floor(p.y))) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -0800544 return false;
545 }
546 return true;
547}
548
Prabir Pradhand65552b2021-10-07 11:23:50 -0700549bool isPointerFromStylus(const MotionEntry& entry, int32_t pointerIndex) {
550 return isFromSource(entry.source, AINPUT_SOURCE_STYLUS) &&
Prabir Pradhane5626962022-10-27 20:30:53 +0000551 isStylusToolType(entry.pointerProperties[pointerIndex].toolType);
Prabir Pradhand65552b2021-10-07 11:23:50 -0700552}
553
Siarhei Vishniakou253f4642022-11-09 13:42:06 -0800554// Determines if the given window can be targeted as InputTarget::Flags::FOREGROUND.
Prabir Pradhan6dfbf262022-03-14 15:24:30 +0000555// Foreground events are only sent to "foreground targetable" windows, but not all gestures sent to
556// such window are necessarily targeted with the flag. For example, an event with ACTION_OUTSIDE can
557// be sent to such a window, but it is not a foreground event and doesn't use
Siarhei Vishniakou253f4642022-11-09 13:42:06 -0800558// InputTarget::Flags::FOREGROUND.
Prabir Pradhan6dfbf262022-03-14 15:24:30 +0000559bool canReceiveForegroundTouches(const WindowInfo& info) {
560 // A non-touchable window can still receive touch events (e.g. in the case of
561 // STYLUS_INTERCEPTOR), so prevent such windows from receiving foreground events for touches.
562 return !info.inputConfig.test(gui::WindowInfo::InputConfig::NOT_TOUCHABLE) && !info.isSpy();
563}
564
Prabir Pradhanaeebeb42023-06-13 19:53:03 +0000565bool isWindowOwnedBy(const sp<WindowInfoHandle>& windowHandle, gui::Pid pid, gui::Uid uid) {
Antonio Kantek48710e42022-03-24 14:19:30 -0700566 if (windowHandle == nullptr) {
567 return false;
568 }
569 const WindowInfo* windowInfo = windowHandle->getInfo();
570 if (pid == windowInfo->ownerPid && uid == windowInfo->ownerUid) {
571 return true;
572 }
573 return false;
574}
575
Prabir Pradhan5735a322022-04-11 17:23:34 +0000576// Checks targeted injection using the window's owner's uid.
577// Returns an empty string if an entry can be sent to the given window, or an error message if the
578// entry is a targeted injection whose uid target doesn't match the window owner.
579std::optional<std::string> verifyTargetedInjection(const sp<WindowInfoHandle>& window,
580 const EventEntry& entry) {
581 if (entry.injectionState == nullptr || !entry.injectionState->targetUid) {
582 // The event was not injected, or the injected event does not target a window.
583 return {};
584 }
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +0000585 const auto uid = *entry.injectionState->targetUid;
Prabir Pradhan5735a322022-04-11 17:23:34 +0000586 if (window == nullptr) {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +0000587 return StringPrintf("No valid window target for injection into uid %s.",
588 uid.toString().c_str());
Prabir Pradhan5735a322022-04-11 17:23:34 +0000589 }
590 if (entry.injectionState->targetUid != window->getInfo()->ownerUid) {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +0000591 return StringPrintf("Injected event targeted at uid %s would be dispatched to window '%s' "
592 "owned by uid %s.",
593 uid.toString().c_str(), window->getName().c_str(),
594 window->getInfo()->ownerUid.toString().c_str());
Prabir Pradhan5735a322022-04-11 17:23:34 +0000595 }
596 return {};
597}
598
Prabir Pradhan82e081e2022-12-06 09:50:09 +0000599std::pair<float, float> resolveTouchedPosition(const MotionEntry& entry) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -0700600 const bool isFromMouse = isFromSource(entry.source, AINPUT_SOURCE_MOUSE);
601 // Always dispatch mouse events to cursor position.
602 if (isFromMouse) {
Prabir Pradhan82e081e2022-12-06 09:50:09 +0000603 return {entry.xCursorPosition, entry.yCursorPosition};
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -0700604 }
605
Siarhei Vishniakou5b9766d2023-07-18 14:06:29 -0700606 const int32_t pointerIndex = MotionEvent::getActionIndex(entry.action);
Prabir Pradhan82e081e2022-12-06 09:50:09 +0000607 return {entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_X),
608 entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_Y)};
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -0700609}
610
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -0700611std::optional<nsecs_t> getDownTime(const EventEntry& eventEntry) {
612 if (eventEntry.type == EventEntry::Type::KEY) {
613 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
614 return keyEntry.downTime;
615 } else if (eventEntry.type == EventEntry::Type::MOTION) {
616 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
617 return motionEntry.downTime;
618 }
619 return std::nullopt;
620}
621
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000622/**
623 * Compare the old touch state to the new touch state, and generate the corresponding touched
624 * windows (== input targets).
625 * If a window had the hovering pointer, but now it doesn't, produce HOVER_EXIT for that window.
626 * If the pointer just entered the new window, produce HOVER_ENTER.
627 * For pointers remaining in the window, produce HOVER_MOVE.
628 */
629std::vector<TouchedWindow> getHoveringWindowsLocked(const TouchState* oldState,
630 const TouchState& newTouchState,
631 const MotionEntry& entry) {
632 std::vector<TouchedWindow> out;
633 const int32_t maskedAction = MotionEvent::getActionMasked(entry.action);
634 if (maskedAction != AMOTION_EVENT_ACTION_HOVER_ENTER &&
635 maskedAction != AMOTION_EVENT_ACTION_HOVER_MOVE &&
636 maskedAction != AMOTION_EVENT_ACTION_HOVER_EXIT) {
637 // Not a hover event - don't need to do anything
638 return out;
639 }
640
641 // We should consider all hovering pointers here. But for now, just use the first one
642 const int32_t pointerId = entry.pointerProperties[0].id;
643
644 std::set<sp<WindowInfoHandle>> oldWindows;
645 if (oldState != nullptr) {
646 oldWindows = oldState->getWindowsWithHoveringPointer(entry.deviceId, pointerId);
647 }
648
649 std::set<sp<WindowInfoHandle>> newWindows =
650 newTouchState.getWindowsWithHoveringPointer(entry.deviceId, pointerId);
651
652 // If the pointer is no longer in the new window set, send HOVER_EXIT.
653 for (const sp<WindowInfoHandle>& oldWindow : oldWindows) {
654 if (newWindows.find(oldWindow) == newWindows.end()) {
655 TouchedWindow touchedWindow;
656 touchedWindow.windowHandle = oldWindow;
657 touchedWindow.targetFlags = InputTarget::Flags::DISPATCH_AS_HOVER_EXIT;
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000658 out.push_back(touchedWindow);
659 }
660 }
661
662 for (const sp<WindowInfoHandle>& newWindow : newWindows) {
663 TouchedWindow touchedWindow;
664 touchedWindow.windowHandle = newWindow;
665 if (oldWindows.find(newWindow) == oldWindows.end()) {
666 // Any windows that have this pointer now, and didn't have it before, should get
667 // HOVER_ENTER
668 touchedWindow.targetFlags = InputTarget::Flags::DISPATCH_AS_HOVER_ENTER;
669 } else {
670 // This pointer was already sent to the window. Use ACTION_HOVER_MOVE.
Siarhei Vishniakouc2eb8502023-04-11 18:33:36 -0700671 if (CC_UNLIKELY(maskedAction != AMOTION_EVENT_ACTION_HOVER_MOVE)) {
Daniel Norman7487dfa2023-08-02 16:39:45 -0700672 android::base::LogSeverity severity = android::base::LogSeverity::FATAL;
673 if (entry.flags & AMOTION_EVENT_FLAG_IS_ACCESSIBILITY_EVENT) {
674 // The Accessibility injected touch exploration event stream
675 // has known inconsistencies, so log ERROR instead of
676 // crashing the device with FATAL.
677 // TODO(b/299977100): Move a11y severity back to FATAL.
678 severity = android::base::LogSeverity::ERROR;
679 }
680 LOG(severity) << "Expected ACTION_HOVER_MOVE instead of " << entry.getDescription();
Siarhei Vishniakouc2eb8502023-04-11 18:33:36 -0700681 }
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000682 touchedWindow.targetFlags = InputTarget::Flags::DISPATCH_AS_IS;
683 }
Siarhei Vishniakou0836a302023-05-03 13:54:30 -0700684 touchedWindow.addHoveringPointer(entry.deviceId, pointerId);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000685 if (canReceiveForegroundTouches(*newWindow->getInfo())) {
686 touchedWindow.targetFlags |= InputTarget::Flags::FOREGROUND;
687 }
688 out.push_back(touchedWindow);
689 }
690 return out;
691}
692
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -0800693template <typename T>
694std::vector<T>& operator+=(std::vector<T>& left, const std::vector<T>& right) {
695 left.insert(left.end(), right.begin(), right.end());
696 return left;
697}
698
Harry Cuttsb166c002023-05-09 13:06:05 +0000699// Filter windows in a TouchState and targets in a vector to remove untrusted windows/targets from
700// both.
701void filterUntrustedTargets(TouchState& touchState, std::vector<InputTarget>& targets) {
702 std::erase_if(touchState.windows, [&](const TouchedWindow& window) {
703 if (!window.windowHandle->getInfo()->inputConfig.test(
704 WindowInfo::InputConfig::TRUSTED_OVERLAY)) {
705 // In addition to TouchState, erase this window from the input targets! We don't have a
706 // good way to do this today except by adding a nested loop.
707 // TODO(b/282025641): simplify this code once InputTargets are being identified
708 // separately from TouchedWindows.
709 std::erase_if(targets, [&](const InputTarget& target) {
710 return target.inputChannel->getConnectionToken() == window.windowHandle->getToken();
711 });
712 return true;
713 }
714 return false;
715 });
716}
717
Siarhei Vishniakouce1fd472023-09-18 18:38:07 -0700718/**
719 * In general, touch should be always split between windows. Some exceptions:
720 * 1. Don't split touch if all of the below is true:
721 * (a) we have an active pointer down *and*
722 * (b) a new pointer is going down that's from the same device *and*
723 * (c) the window that's receiving the current pointer does not support split touch.
724 * 2. Don't split mouse events
725 */
726bool shouldSplitTouch(const TouchState& touchState, const MotionEntry& entry) {
727 if (isFromSource(entry.source, AINPUT_SOURCE_MOUSE)) {
728 // We should never split mouse events
729 return false;
730 }
731 for (const TouchedWindow& touchedWindow : touchState.windows) {
732 if (touchedWindow.windowHandle->getInfo()->isSpy()) {
733 // Spy windows should not affect whether or not touch is split.
734 continue;
735 }
736 if (touchedWindow.windowHandle->getInfo()->supportsSplitTouch()) {
737 continue;
738 }
739 if (touchedWindow.windowHandle->getInfo()->inputConfig.test(
740 gui::WindowInfo::InputConfig::IS_WALLPAPER)) {
741 // Wallpaper window should not affect whether or not touch is split
742 continue;
743 }
744
745 if (touchedWindow.hasTouchingPointers(entry.deviceId)) {
746 return false;
747 }
748 }
749 return true;
750}
751
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000752} // namespace
753
Michael Wrightd02c5b62014-02-10 15:10:22 -0800754// --- InputDispatcher ---
755
Prabir Pradhana41d2442023-04-20 21:30:40 +0000756InputDispatcher::InputDispatcher(InputDispatcherPolicyInterface& policy)
Siarhei Vishniakou289e9242022-02-15 14:50:16 -0800757 : InputDispatcher(policy, STALE_EVENT_TIMEOUT) {}
758
Prabir Pradhana41d2442023-04-20 21:30:40 +0000759InputDispatcher::InputDispatcher(InputDispatcherPolicyInterface& policy,
Siarhei Vishniakou289e9242022-02-15 14:50:16 -0800760 std::chrono::nanoseconds staleEventTimeout)
Garfield Tan00f511d2019-06-12 16:55:40 -0700761 : mPolicy(policy),
762 mPendingEvent(nullptr),
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700763 mLastDropReason(DropReason::NOT_DROPPED),
Garfield Tanff1f1bb2020-01-28 13:24:04 -0800764 mIdGenerator(IdGenerator::Source::INPUT_DISPATCHER),
Garfield Tan00f511d2019-06-12 16:55:40 -0700765 mAppSwitchSawKeyDown(false),
Colin Cross5b799302022-10-18 21:52:41 -0700766 mAppSwitchDueTime(LLONG_MAX),
Garfield Tan00f511d2019-06-12 16:55:40 -0700767 mNextUnblockedEvent(nullptr),
Prabir Pradhan1376fcd2022-01-21 09:56:35 -0800768 mMonitorDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT),
Garfield Tan00f511d2019-06-12 16:55:40 -0700769 mDispatchEnabled(false),
770 mDispatchFrozen(false),
771 mInputFilterEnabled(false),
Bernardo Rufinoea97d182020-08-19 14:43:14 +0100772 mMaximumObscuringOpacityForTouch(1.0f),
Siarhei Vishniakou2508b872020-12-03 16:33:53 -1000773 mFocusedDisplayId(ADISPLAY_ID_DEFAULT),
Prabir Pradhan99987712020-11-10 18:43:05 -0800774 mWindowTokenWithPointerCapture(nullptr),
Siarhei Vishniakou289e9242022-02-15 14:50:16 -0800775 mStaleEventTimeout(staleEventTimeout),
Siarhei Vishniakoua04181f2021-03-26 05:56:49 +0000776 mLatencyAggregator(),
Antonio Kantek15beb512022-06-13 22:35:41 +0000777 mLatencyTracker(&mLatencyAggregator) {
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -0700778 mLooper = sp<Looper>::make(false);
Prabir Pradhanf93562f2018-11-29 12:13:37 -0800779 mReporter = createInputReporter();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800780
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -0700781 mWindowInfoListener = sp<DispatcherWindowListener>::make(*this);
Siarhei Vishniakou31977182022-09-30 08:51:23 -0700782#if defined(__ANDROID__)
Siarhei Vishniakou18050092021-09-01 13:32:49 -0700783 SurfaceComposerClient::getDefault()->addWindowInfosListener(mWindowInfoListener);
Siarhei Vishniakou31977182022-09-30 08:51:23 -0700784#endif
Yi Kong9b14ac62018-07-17 13:48:38 -0700785 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800786}
787
788InputDispatcher::~InputDispatcher() {
Prabir Pradhancef936d2021-07-21 16:17:52 +0000789 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800790
Prabir Pradhancef936d2021-07-21 16:17:52 +0000791 resetKeyRepeatLocked();
792 releasePendingEventLocked();
793 drainInboundQueueLocked();
794 mCommandQueue.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800795
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +0000796 while (!mConnectionsByToken.empty()) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -0700797 std::shared_ptr<Connection> connection = mConnectionsByToken.begin()->second;
Harry Cutts33476232023-01-30 19:57:29 +0000798 removeInputChannelLocked(connection->inputChannel->getConnectionToken(), /*notify=*/false);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800799 }
800}
801
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700802status_t InputDispatcher::start() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700803 if (mThread) {
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700804 return ALREADY_EXISTS;
805 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700806 mThread = std::make_unique<InputThread>(
807 "InputDispatcher", [this]() { dispatchOnce(); }, [this]() { mLooper->wake(); });
808 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700809}
810
811status_t InputDispatcher::stop() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700812 if (mThread && mThread->isCallingThread()) {
813 ALOGE("InputDispatcher cannot be stopped from its own thread!");
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700814 return INVALID_OPERATION;
815 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700816 mThread.reset();
817 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700818}
819
Michael Wrightd02c5b62014-02-10 15:10:22 -0800820void InputDispatcher::dispatchOnce() {
Colin Cross5b799302022-10-18 21:52:41 -0700821 nsecs_t nextWakeupTime = LLONG_MAX;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800822 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -0800823 std::scoped_lock _l(mLock);
824 mDispatcherIsAlive.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800825
826 // Run a dispatch loop if there are no pending commands.
827 // The dispatch loop might enqueue commands to run afterwards.
828 if (!haveCommandsLocked()) {
829 dispatchOnceInnerLocked(&nextWakeupTime);
830 }
831
832 // Run all pending commands if there are any.
833 // If any commands were run then force the next poll to wake up immediately.
Prabir Pradhancef936d2021-07-21 16:17:52 +0000834 if (runCommandsLockedInterruptable()) {
Colin Cross5b799302022-10-18 21:52:41 -0700835 nextWakeupTime = LLONG_MIN;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800836 }
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800837
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700838 // If we are still waiting for ack on some events,
839 // we might have to wake up earlier to check if an app is anr'ing.
840 const nsecs_t nextAnrCheck = processAnrsLocked();
841 nextWakeupTime = std::min(nextWakeupTime, nextAnrCheck);
842
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800843 // We are about to enter an infinitely long sleep, because we have no commands or
844 // pending or queued events
Colin Cross5b799302022-10-18 21:52:41 -0700845 if (nextWakeupTime == LLONG_MAX) {
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800846 mDispatcherEnteredIdle.notify_all();
847 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800848 } // release lock
849
850 // Wait for callback or timeout or wake. (make sure we round up, not down)
851 nsecs_t currentTime = now();
852 int timeoutMillis = toMillisecondTimeoutDelay(currentTime, nextWakeupTime);
853 mLooper->pollOnce(timeoutMillis);
854}
855
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700856/**
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500857 * Raise ANR if there is no focused window.
858 * Before the ANR is raised, do a final state check:
859 * 1. The currently focused application must be the same one we are waiting for.
860 * 2. Ensure we still don't have a focused window.
861 */
862void InputDispatcher::processNoFocusedWindowAnrLocked() {
863 // Check if the application that we are waiting for is still focused.
864 std::shared_ptr<InputApplicationHandle> focusedApplication =
865 getValueByKey(mFocusedApplicationHandlesByDisplay, mAwaitedApplicationDisplayId);
866 if (focusedApplication == nullptr ||
867 focusedApplication->getApplicationToken() !=
868 mAwaitedFocusedApplication->getApplicationToken()) {
869 // Unexpected because we should have reset the ANR timer when focused application changed
870 ALOGE("Waited for a focused window, but focused application has already changed to %s",
871 focusedApplication->getName().c_str());
872 return; // The focused application has changed.
873 }
874
chaviw98318de2021-05-19 16:45:23 -0500875 const sp<WindowInfoHandle>& focusedWindowHandle =
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500876 getFocusedWindowHandleLocked(mAwaitedApplicationDisplayId);
877 if (focusedWindowHandle != nullptr) {
878 return; // We now have a focused window. No need for ANR.
879 }
880 onAnrLocked(mAwaitedFocusedApplication);
881}
882
883/**
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700884 * Check if any of the connections' wait queues have events that are too old.
885 * If we waited for events to be ack'ed for more than the window timeout, raise an ANR.
886 * Return the time at which we should wake up next.
887 */
888nsecs_t InputDispatcher::processAnrsLocked() {
889 const nsecs_t currentTime = now();
Colin Cross5b799302022-10-18 21:52:41 -0700890 nsecs_t nextAnrCheck = LLONG_MAX;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700891 // Check if we are waiting for a focused window to appear. Raise ANR if waited too long
892 if (mNoFocusedWindowTimeoutTime.has_value() && mAwaitedFocusedApplication != nullptr) {
893 if (currentTime >= *mNoFocusedWindowTimeoutTime) {
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500894 processNoFocusedWindowAnrLocked();
Chris Yea209fde2020-07-22 13:54:51 -0700895 mAwaitedFocusedApplication.reset();
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500896 mNoFocusedWindowTimeoutTime = std::nullopt;
Colin Cross5b799302022-10-18 21:52:41 -0700897 return LLONG_MIN;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700898 } else {
Siarhei Vishniakou38a6d272020-10-20 20:29:33 -0500899 // Keep waiting. We will drop the event when mNoFocusedWindowTimeoutTime comes.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700900 nextAnrCheck = *mNoFocusedWindowTimeoutTime;
901 }
902 }
903
904 // Check if any connection ANRs are due
905 nextAnrCheck = std::min(nextAnrCheck, mAnrTracker.firstTimeout());
906 if (currentTime < nextAnrCheck) { // most likely scenario
907 return nextAnrCheck; // everything is normal. Let's check again at nextAnrCheck
908 }
909
910 // If we reached here, we have an unresponsive connection.
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -0700911 std::shared_ptr<Connection> connection = getConnectionLocked(mAnrTracker.firstToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700912 if (connection == nullptr) {
913 ALOGE("Could not find connection for entry %" PRId64, mAnrTracker.firstTimeout());
914 return nextAnrCheck;
915 }
916 connection->responsive = false;
917 // Stop waking up for this unresponsive connection
918 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000919 onAnrLocked(connection);
Colin Cross5b799302022-10-18 21:52:41 -0700920 return LLONG_MIN;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700921}
922
Prabir Pradhan1376fcd2022-01-21 09:56:35 -0800923std::chrono::nanoseconds InputDispatcher::getDispatchingTimeoutLocked(
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -0700924 const std::shared_ptr<Connection>& connection) {
Prabir Pradhan1376fcd2022-01-21 09:56:35 -0800925 if (connection->monitor) {
926 return mMonitorDispatchingTimeout;
927 }
928 const sp<WindowInfoHandle> window =
929 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700930 if (window != nullptr) {
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500931 return window->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700932 }
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500933 return DEFAULT_INPUT_DISPATCHING_TIMEOUT;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700934}
935
Michael Wrightd02c5b62014-02-10 15:10:22 -0800936void InputDispatcher::dispatchOnceInnerLocked(nsecs_t* nextWakeupTime) {
937 nsecs_t currentTime = now();
938
Jeff Browndc5992e2014-04-11 01:27:26 -0700939 // Reset the key repeat timer whenever normal dispatch is suspended while the
940 // device is in a non-interactive state. This is to ensure that we abort a key
941 // repeat if the device is just coming out of sleep.
942 if (!mDispatchEnabled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800943 resetKeyRepeatLocked();
944 }
945
946 // If dispatching is frozen, do not process timeouts or try to deliver any new events.
947 if (mDispatchFrozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +0100948 if (DEBUG_FOCUS) {
949 ALOGD("Dispatch frozen. Waiting some more.");
950 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800951 return;
952 }
953
954 // Optimize latency of app switches.
955 // Essentially we start a short timeout when an app switch key (HOME / ENDCALL) has
956 // been pressed. When it expires, we preempt dispatch and drop all other pending events.
957 bool isAppSwitchDue = mAppSwitchDueTime <= currentTime;
958 if (mAppSwitchDueTime < *nextWakeupTime) {
959 *nextWakeupTime = mAppSwitchDueTime;
960 }
961
962 // Ready to start a new event.
963 // If we don't already have a pending event, go grab one.
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700964 if (!mPendingEvent) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700965 if (mInboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800966 if (isAppSwitchDue) {
967 // The inbound queue is empty so the app switch key we were waiting
968 // for will never arrive. Stop waiting for it.
969 resetPendingAppSwitchLocked(false);
970 isAppSwitchDue = false;
971 }
972
973 // Synthesize a key repeat if appropriate.
974 if (mKeyRepeatState.lastKeyEntry) {
975 if (currentTime >= mKeyRepeatState.nextRepeatTime) {
976 mPendingEvent = synthesizeKeyRepeatLocked(currentTime);
977 } else {
978 if (mKeyRepeatState.nextRepeatTime < *nextWakeupTime) {
979 *nextWakeupTime = mKeyRepeatState.nextRepeatTime;
980 }
981 }
982 }
983
984 // Nothing to do if there is no pending event.
985 if (!mPendingEvent) {
986 return;
987 }
988 } else {
989 // Inbound queue has at least one entry.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700990 mPendingEvent = mInboundQueue.front();
991 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800992 traceInboundQueueLengthLocked();
993 }
994
995 // Poke user activity for this event.
996 if (mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700997 pokeUserActivityLocked(*mPendingEvent);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800998 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800999 }
1000
1001 // Now we have an event to dispatch.
1002 // All events are eventually dequeued and processed this way, even if we intend to drop them.
Yi Kong9b14ac62018-07-17 13:48:38 -07001003 ALOG_ASSERT(mPendingEvent != nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001004 bool done = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001005 DropReason dropReason = DropReason::NOT_DROPPED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001006 if (!(mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001007 dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001008 } else if (!mDispatchEnabled) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001009 dropReason = DropReason::DISABLED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001010 }
1011
1012 if (mNextUnblockedEvent == mPendingEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001013 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001014 }
1015
1016 switch (mPendingEvent->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001017 case EventEntry::Type::CONFIGURATION_CHANGED: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001018 const ConfigurationChangedEntry& typedEntry =
1019 static_cast<const ConfigurationChangedEntry&>(*mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001020 done = dispatchConfigurationChangedLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001021 dropReason = DropReason::NOT_DROPPED; // configuration changes are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001022 break;
1023 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001024
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001025 case EventEntry::Type::DEVICE_RESET: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001026 const DeviceResetEntry& typedEntry =
1027 static_cast<const DeviceResetEntry&>(*mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001028 done = dispatchDeviceResetLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001029 dropReason = DropReason::NOT_DROPPED; // device resets are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001030 break;
1031 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001032
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001033 case EventEntry::Type::FOCUS: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001034 std::shared_ptr<FocusEntry> typedEntry =
1035 std::static_pointer_cast<FocusEntry>(mPendingEvent);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001036 dispatchFocusLocked(currentTime, typedEntry);
1037 done = true;
1038 dropReason = DropReason::NOT_DROPPED; // focus events are never dropped
1039 break;
1040 }
1041
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001042 case EventEntry::Type::TOUCH_MODE_CHANGED: {
1043 const auto typedEntry = std::static_pointer_cast<TouchModeEntry>(mPendingEvent);
1044 dispatchTouchModeChangeLocked(currentTime, typedEntry);
1045 done = true;
1046 dropReason = DropReason::NOT_DROPPED; // touch mode events are never dropped
1047 break;
1048 }
1049
Prabir Pradhan99987712020-11-10 18:43:05 -08001050 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
1051 const auto typedEntry =
1052 std::static_pointer_cast<PointerCaptureChangedEntry>(mPendingEvent);
1053 dispatchPointerCaptureChangedLocked(currentTime, typedEntry, dropReason);
1054 done = true;
1055 break;
1056 }
1057
arthurhungb89ccb02020-12-30 16:19:01 +08001058 case EventEntry::Type::DRAG: {
1059 std::shared_ptr<DragEntry> typedEntry =
1060 std::static_pointer_cast<DragEntry>(mPendingEvent);
1061 dispatchDragLocked(currentTime, typedEntry);
1062 done = true;
1063 break;
1064 }
1065
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001066 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001067 std::shared_ptr<KeyEntry> keyEntry = std::static_pointer_cast<KeyEntry>(mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001068 if (isAppSwitchDue) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001069 if (isAppSwitchKeyEvent(*keyEntry)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001070 resetPendingAppSwitchLocked(true);
1071 isAppSwitchDue = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001072 } else if (dropReason == DropReason::NOT_DROPPED) {
1073 dropReason = DropReason::APP_SWITCH;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001074 }
1075 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001076 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *keyEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001077 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001078 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001079 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
1080 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001081 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001082 done = dispatchKeyLocked(currentTime, keyEntry, &dropReason, nextWakeupTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001083 break;
1084 }
1085
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001086 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001087 std::shared_ptr<MotionEntry> motionEntry =
1088 std::static_pointer_cast<MotionEntry>(mPendingEvent);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001089 if (dropReason == DropReason::NOT_DROPPED && isAppSwitchDue) {
1090 dropReason = DropReason::APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001091 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001092 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *motionEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001093 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001094 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001095 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
1096 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001097 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001098 done = dispatchMotionLocked(currentTime, motionEntry, &dropReason, nextWakeupTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001099 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001100 }
Chris Yef59a2f42020-10-16 12:55:26 -07001101
1102 case EventEntry::Type::SENSOR: {
1103 std::shared_ptr<SensorEntry> sensorEntry =
1104 std::static_pointer_cast<SensorEntry>(mPendingEvent);
1105 if (dropReason == DropReason::NOT_DROPPED && isAppSwitchDue) {
1106 dropReason = DropReason::APP_SWITCH;
1107 }
1108 // Sensor timestamps use SYSTEM_TIME_BOOTTIME time base, so we can't use
1109 // 'currentTime' here, get SYSTEM_TIME_BOOTTIME instead.
1110 nsecs_t bootTime = systemTime(SYSTEM_TIME_BOOTTIME);
1111 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(bootTime, *sensorEntry)) {
1112 dropReason = DropReason::STALE;
1113 }
1114 dispatchSensorLocked(currentTime, sensorEntry, &dropReason, nextWakeupTime);
1115 done = true;
1116 break;
1117 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001118 }
1119
1120 if (done) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001121 if (dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001122 dropInboundEventLocked(*mPendingEvent, dropReason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001123 }
Michael Wright3a981722015-06-10 15:26:13 +01001124 mLastDropReason = dropReason;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001125
1126 releasePendingEventLocked();
Colin Cross5b799302022-10-18 21:52:41 -07001127 *nextWakeupTime = LLONG_MIN; // force next poll to wake up immediately
Michael Wrightd02c5b62014-02-10 15:10:22 -08001128 }
1129}
1130
Siarhei Vishniakou289e9242022-02-15 14:50:16 -08001131bool InputDispatcher::isStaleEvent(nsecs_t currentTime, const EventEntry& entry) {
1132 return std::chrono::nanoseconds(currentTime - entry.eventTime) >= mStaleEventTimeout;
1133}
1134
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001135/**
1136 * Return true if the events preceding this incoming motion event should be dropped
1137 * Return false otherwise (the default behaviour)
1138 */
1139bool InputDispatcher::shouldPruneInboundQueueLocked(const MotionEntry& motionEntry) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001140 const bool isPointerDownEvent = motionEntry.action == AMOTION_EVENT_ACTION_DOWN &&
Prabir Pradhanaa561d12021-09-24 06:57:33 -07001141 isFromSource(motionEntry.source, AINPUT_SOURCE_CLASS_POINTER);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001142
1143 // Optimize case where the current application is unresponsive and the user
1144 // decides to touch a window in a different application.
1145 // If the application takes too long to catch up then we drop all events preceding
1146 // the touch into the other window.
1147 if (isPointerDownEvent && mAwaitedFocusedApplication != nullptr) {
Siarhei Vishniakou9306c382022-09-30 15:30:31 -07001148 const int32_t displayId = motionEntry.displayId;
1149 const auto [x, y] = resolveTouchedPosition(motionEntry);
Harry Cutts33476232023-01-30 19:57:29 +00001150 const bool isStylus = isPointerFromStylus(motionEntry, /*pointerIndex=*/0);
Siarhei Vishniakou9306c382022-09-30 15:30:31 -07001151
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07001152 sp<WindowInfoHandle> touchedWindowHandle =
1153 findTouchedWindowAtLocked(displayId, x, y, isStylus);
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001154 if (touchedWindowHandle != nullptr &&
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001155 touchedWindowHandle->getApplicationToken() !=
1156 mAwaitedFocusedApplication->getApplicationToken()) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001157 // User touched a different application than the one we are waiting on.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001158 ALOGI("Pruning input queue because user touched a different application while waiting "
1159 "for %s",
1160 mAwaitedFocusedApplication->getName().c_str());
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001161 return true;
1162 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001163
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08001164 // Alternatively, maybe there's a spy window that could handle this event.
1165 const std::vector<sp<WindowInfoHandle>> touchedSpies =
1166 findTouchedSpyWindowsAtLocked(displayId, x, y, isStylus);
1167 for (const auto& windowHandle : touchedSpies) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07001168 const std::shared_ptr<Connection> connection =
1169 getConnectionLocked(windowHandle->getToken());
Siarhei Vishniakou34ed4d42020-06-18 00:43:02 +00001170 if (connection != nullptr && connection->responsive) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08001171 // This spy window could take more input. Drop all events preceding this
1172 // event, so that the spy window can get a chance to receive the stream.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001173 ALOGW("Pruning the input queue because %s is unresponsive, but we have a "
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08001174 "responsive spy window that may handle the event.",
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001175 mAwaitedFocusedApplication->getName().c_str());
1176 return true;
1177 }
1178 }
1179 }
1180
1181 // Prevent getting stuck: if we have a pending key event, and some motion events that have not
1182 // yet been processed by some connections, the dispatcher will wait for these motion
1183 // events to be processed before dispatching the key event. This is because these motion events
1184 // may cause a new window to be launched, which the user might expect to receive focus.
1185 // To prevent waiting forever for such events, just send the key to the currently focused window
1186 if (isPointerDownEvent && mKeyIsWaitingForEventsTimeout) {
1187 ALOGD("Received a new pointer down event, stop waiting for events to process and "
1188 "just send the pending key event to the focused window.");
1189 mKeyIsWaitingForEventsTimeout = now();
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001190 }
1191 return false;
1192}
1193
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001194bool InputDispatcher::enqueueInboundEventLocked(std::unique_ptr<EventEntry> newEntry) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001195 bool needWake = mInboundQueue.empty();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001196 mInboundQueue.push_back(std::move(newEntry));
1197 EventEntry& entry = *(mInboundQueue.back());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001198 traceInboundQueueLengthLocked();
1199
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001200 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001201 case EventEntry::Type::KEY: {
Prabir Pradhan5735a322022-04-11 17:23:34 +00001202 LOG_ALWAYS_FATAL_IF((entry.policyFlags & POLICY_FLAG_TRUSTED) == 0,
1203 "Unexpected untrusted event.");
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001204 // Optimize app switch latency.
1205 // If the application takes too long to catch up then we drop all events preceding
1206 // the app switch key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001207 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001208 if (isAppSwitchKeyEvent(keyEntry)) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001209 if (keyEntry.action == AKEY_EVENT_ACTION_DOWN) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001210 mAppSwitchSawKeyDown = true;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001211 } else if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001212 if (mAppSwitchSawKeyDown) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001213 if (DEBUG_APP_SWITCH) {
1214 ALOGD("App switch is pending!");
1215 }
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001216 mAppSwitchDueTime = keyEntry.eventTime + APP_SWITCH_TIMEOUT;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001217 mAppSwitchSawKeyDown = false;
1218 needWake = true;
1219 }
1220 }
1221 }
Arthur Hung2ee6d0b2022-03-03 20:19:38 +08001222
1223 // If a new up event comes in, and the pending event with same key code has been asked
1224 // to try again later because of the policy. We have to reset the intercept key wake up
1225 // time for it may have been handled in the policy and could be dropped.
1226 if (keyEntry.action == AKEY_EVENT_ACTION_UP && mPendingEvent &&
1227 mPendingEvent->type == EventEntry::Type::KEY) {
1228 KeyEntry& pendingKey = static_cast<KeyEntry&>(*mPendingEvent);
1229 if (pendingKey.keyCode == keyEntry.keyCode &&
1230 pendingKey.interceptKeyResult ==
Michael Wright5caf55a2022-11-24 22:31:42 +00001231 KeyEntry::InterceptKeyResult::TRY_AGAIN_LATER) {
1232 pendingKey.interceptKeyResult = KeyEntry::InterceptKeyResult::UNKNOWN;
Arthur Hung2ee6d0b2022-03-03 20:19:38 +08001233 pendingKey.interceptKeyWakeupTime = 0;
1234 needWake = true;
1235 }
1236 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001237 break;
1238 }
1239
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001240 case EventEntry::Type::MOTION: {
Prabir Pradhan5735a322022-04-11 17:23:34 +00001241 LOG_ALWAYS_FATAL_IF((entry.policyFlags & POLICY_FLAG_TRUSTED) == 0,
1242 "Unexpected untrusted event.");
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001243 if (shouldPruneInboundQueueLocked(static_cast<MotionEntry&>(entry))) {
1244 mNextUnblockedEvent = mInboundQueue.back();
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001245 needWake = true;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001246 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001247 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001248 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001249 case EventEntry::Type::FOCUS: {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001250 LOG_ALWAYS_FATAL("Focus events should be inserted using enqueueFocusEventLocked");
1251 break;
1252 }
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001253 case EventEntry::Type::TOUCH_MODE_CHANGED:
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001254 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08001255 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07001256 case EventEntry::Type::SENSOR:
arthurhungb89ccb02020-12-30 16:19:01 +08001257 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
1258 case EventEntry::Type::DRAG: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001259 // nothing to do
1260 break;
1261 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001262 }
1263
1264 return needWake;
1265}
1266
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001267void InputDispatcher::addRecentEventLocked(std::shared_ptr<EventEntry> entry) {
Chris Yef59a2f42020-10-16 12:55:26 -07001268 // Do not store sensor event in recent queue to avoid flooding the queue.
1269 if (entry->type != EventEntry::Type::SENSOR) {
1270 mRecentQueue.push_back(entry);
1271 }
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001272 if (mRecentQueue.size() > RECENT_QUEUE_MAX_SIZE) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001273 mRecentQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001274 }
1275}
1276
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07001277sp<WindowInfoHandle> InputDispatcher::findTouchedWindowAtLocked(int32_t displayId, float x, float y,
1278 bool isStylus,
1279 bool ignoreDragWindow) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001280 // Traverse windows from front to back to find touched window.
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001281 const auto& windowHandles = getWindowHandlesLocked(displayId);
chaviw98318de2021-05-19 16:45:23 -05001282 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
arthurhung6d4bed92021-03-17 11:59:33 +08001283 if (ignoreDragWindow && haveSameToken(windowHandle, mDragState->dragWindow)) {
arthurhungb89ccb02020-12-30 16:19:01 +08001284 continue;
1285 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001286
Prabir Pradhan3f90d312021-11-19 03:57:24 -08001287 const WindowInfo& info = *windowHandle->getInfo();
Prabir Pradhan33e3baa2022-12-06 20:30:22 +00001288 if (!info.isSpy() &&
1289 windowAcceptsTouchAt(info, displayId, x, y, isStylus, getTransformLocked(displayId))) {
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07001290 return windowHandle;
1291 }
1292 }
1293 return nullptr;
1294}
1295
1296std::vector<InputTarget> InputDispatcher::findOutsideTargetsLocked(
Siarhei Vishniakou70f3d8c2023-09-19 15:36:52 -07001297 int32_t displayId, const sp<WindowInfoHandle>& touchedWindow, int32_t pointerId) const {
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07001298 if (touchedWindow == nullptr) {
1299 return {};
1300 }
1301 // Traverse windows from front to back until we encounter the touched window.
1302 std::vector<InputTarget> outsideTargets;
1303 const auto& windowHandles = getWindowHandlesLocked(displayId);
1304 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
1305 if (windowHandle == touchedWindow) {
1306 // Stop iterating once we found a touched window. Any WATCH_OUTSIDE_TOUCH window
1307 // below the touched window will not get ACTION_OUTSIDE event.
1308 return outsideTargets;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08001309 }
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001310
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07001311 const WindowInfo& info = *windowHandle->getInfo();
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08001312 if (info.inputConfig.test(WindowInfo::InputConfig::WATCH_OUTSIDE_TOUCH)) {
Siarhei Vishniakou70f3d8c2023-09-19 15:36:52 -07001313 std::bitset<MAX_POINTER_ID + 1> pointerIds;
1314 pointerIds.set(pointerId);
1315 addWindowTargetLocked(windowHandle, InputTarget::Flags::DISPATCH_AS_OUTSIDE, pointerIds,
1316 /*firstDownTimeInTarget=*/std::nullopt, outsideTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001317 }
1318 }
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07001319 return outsideTargets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001320}
1321
Prabir Pradhand65552b2021-10-07 11:23:50 -07001322std::vector<sp<WindowInfoHandle>> InputDispatcher::findTouchedSpyWindowsAtLocked(
Prabir Pradhan82e081e2022-12-06 09:50:09 +00001323 int32_t displayId, float x, float y, bool isStylus) const {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001324 // Traverse windows from front to back and gather the touched spy windows.
1325 std::vector<sp<WindowInfoHandle>> spyWindows;
1326 const auto& windowHandles = getWindowHandlesLocked(displayId);
1327 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
1328 const WindowInfo& info = *windowHandle->getInfo();
1329
Prabir Pradhan33e3baa2022-12-06 20:30:22 +00001330 if (!windowAcceptsTouchAt(info, displayId, x, y, isStylus, getTransformLocked(displayId))) {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001331 continue;
1332 }
1333 if (!info.isSpy()) {
1334 // The first touched non-spy window was found, so return the spy windows touched so far.
1335 return spyWindows;
1336 }
1337 spyWindows.push_back(windowHandle);
1338 }
1339 return spyWindows;
1340}
1341
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001342void InputDispatcher::dropInboundEventLocked(const EventEntry& entry, DropReason dropReason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001343 const char* reason;
1344 switch (dropReason) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001345 case DropReason::POLICY:
Prabir Pradhan65613802023-02-22 23:36:58 +00001346 if (debugInboundEventDetails()) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001347 ALOGD("Dropped event because policy consumed it.");
1348 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001349 reason = "inbound event was dropped because the policy consumed it";
1350 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001351 case DropReason::DISABLED:
1352 if (mLastDropReason != DropReason::DISABLED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001353 ALOGI("Dropped event because input dispatch is disabled.");
1354 }
1355 reason = "inbound event was dropped because input dispatch is disabled";
1356 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001357 case DropReason::APP_SWITCH:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001358 ALOGI("Dropped event because of pending overdue app switch.");
1359 reason = "inbound event was dropped because of pending overdue app switch";
1360 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001361 case DropReason::BLOCKED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001362 ALOGI("Dropped event because the current application is not responding and the user "
1363 "has started interacting with a different application.");
1364 reason = "inbound event was dropped because the current application is not responding "
1365 "and the user has started interacting with a different application";
1366 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001367 case DropReason::STALE:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001368 ALOGI("Dropped event because it is stale.");
1369 reason = "inbound event was dropped because it is stale";
1370 break;
Prabir Pradhan99987712020-11-10 18:43:05 -08001371 case DropReason::NO_POINTER_CAPTURE:
1372 ALOGI("Dropped event because there is no window with Pointer Capture.");
1373 reason = "inbound event was dropped because there is no window with Pointer Capture";
1374 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001375 case DropReason::NOT_DROPPED: {
1376 LOG_ALWAYS_FATAL("Should not be dropping a NOT_DROPPED event");
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001377 return;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001378 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001379 }
1380
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001381 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001382 case EventEntry::Type::KEY: {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001383 CancelationOptions options(CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS, reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001384 synthesizeCancelationEventsForAllConnectionsLocked(options);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001385 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001386 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001387 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001388 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
1389 if (motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001390 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS, reason);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001391 synthesizeCancelationEventsForAllConnectionsLocked(options);
1392 } else {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001393 CancelationOptions options(CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS,
1394 reason);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001395 synthesizeCancelationEventsForAllConnectionsLocked(options);
1396 }
1397 break;
1398 }
Chris Yef59a2f42020-10-16 12:55:26 -07001399 case EventEntry::Type::SENSOR: {
1400 break;
1401 }
arthurhungb89ccb02020-12-30 16:19:01 +08001402 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
1403 case EventEntry::Type::DRAG: {
Prabir Pradhan99987712020-11-10 18:43:05 -08001404 break;
1405 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001406 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001407 case EventEntry::Type::TOUCH_MODE_CHANGED:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001408 case EventEntry::Type::CONFIGURATION_CHANGED:
1409 case EventEntry::Type::DEVICE_RESET: {
Dominik Laskowski75788452021-02-09 18:51:25 -08001410 LOG_ALWAYS_FATAL("Should not drop %s events", ftl::enum_string(entry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001411 break;
1412 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001413 }
1414}
1415
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08001416static bool isAppSwitchKeyCode(int32_t keyCode) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001417 return keyCode == AKEYCODE_HOME || keyCode == AKEYCODE_ENDCALL ||
1418 keyCode == AKEYCODE_APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001419}
1420
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001421bool InputDispatcher::isAppSwitchKeyEvent(const KeyEntry& keyEntry) {
1422 return !(keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) && isAppSwitchKeyCode(keyEntry.keyCode) &&
1423 (keyEntry.policyFlags & POLICY_FLAG_TRUSTED) &&
1424 (keyEntry.policyFlags & POLICY_FLAG_PASS_TO_USER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001425}
1426
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07001427bool InputDispatcher::isAppSwitchPendingLocked() const {
Colin Cross5b799302022-10-18 21:52:41 -07001428 return mAppSwitchDueTime != LLONG_MAX;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001429}
1430
1431void InputDispatcher::resetPendingAppSwitchLocked(bool handled) {
Colin Cross5b799302022-10-18 21:52:41 -07001432 mAppSwitchDueTime = LLONG_MAX;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001433
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001434 if (DEBUG_APP_SWITCH) {
1435 if (handled) {
1436 ALOGD("App switch has arrived.");
1437 } else {
1438 ALOGD("App switch was abandoned.");
1439 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001440 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001441}
1442
Michael Wrightd02c5b62014-02-10 15:10:22 -08001443bool InputDispatcher::haveCommandsLocked() const {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001444 return !mCommandQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001445}
1446
Prabir Pradhancef936d2021-07-21 16:17:52 +00001447bool InputDispatcher::runCommandsLockedInterruptable() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001448 if (mCommandQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001449 return false;
1450 }
1451
1452 do {
Prabir Pradhancef936d2021-07-21 16:17:52 +00001453 auto command = std::move(mCommandQueue.front());
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001454 mCommandQueue.pop_front();
Prabir Pradhancef936d2021-07-21 16:17:52 +00001455 // Commands are run with the lock held, but may release and re-acquire the lock from within.
1456 command();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001457 } while (!mCommandQueue.empty());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001458 return true;
1459}
1460
Prabir Pradhancef936d2021-07-21 16:17:52 +00001461void InputDispatcher::postCommandLocked(Command&& command) {
1462 mCommandQueue.push_back(command);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001463}
1464
1465void InputDispatcher::drainInboundQueueLocked() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001466 while (!mInboundQueue.empty()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001467 std::shared_ptr<EventEntry> entry = mInboundQueue.front();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001468 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001469 releaseInboundEventLocked(entry);
1470 }
1471 traceInboundQueueLengthLocked();
1472}
1473
1474void InputDispatcher::releasePendingEventLocked() {
1475 if (mPendingEvent) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001476 releaseInboundEventLocked(mPendingEvent);
Yi Kong9b14ac62018-07-17 13:48:38 -07001477 mPendingEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001478 }
1479}
1480
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001481void InputDispatcher::releaseInboundEventLocked(std::shared_ptr<EventEntry> entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001482 InjectionState* injectionState = entry->injectionState;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001483 if (injectionState && injectionState->injectionResult == InputEventInjectionResult::PENDING) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001484 if (DEBUG_DISPATCH_CYCLE) {
1485 ALOGD("Injected inbound event was dropped.");
1486 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001487 setInjectionResult(*entry, InputEventInjectionResult::FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001488 }
1489 if (entry == mNextUnblockedEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001490 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001491 }
1492 addRecentEventLocked(entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001493}
1494
1495void InputDispatcher::resetKeyRepeatLocked() {
1496 if (mKeyRepeatState.lastKeyEntry) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001497 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001498 }
1499}
1500
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001501std::shared_ptr<KeyEntry> InputDispatcher::synthesizeKeyRepeatLocked(nsecs_t currentTime) {
1502 std::shared_ptr<KeyEntry> entry = mKeyRepeatState.lastKeyEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001503
Michael Wright2e732952014-09-24 13:26:59 -07001504 uint32_t policyFlags = entry->policyFlags &
1505 (POLICY_FLAG_RAW_MASK | POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_TRUSTED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001506
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001507 std::shared_ptr<KeyEntry> newEntry =
1508 std::make_unique<KeyEntry>(mIdGenerator.nextId(), currentTime, entry->deviceId,
1509 entry->source, entry->displayId, policyFlags, entry->action,
1510 entry->flags, entry->keyCode, entry->scanCode,
1511 entry->metaState, entry->repeatCount + 1, entry->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001512
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001513 newEntry->syntheticRepeat = true;
1514 mKeyRepeatState.lastKeyEntry = newEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001515 mKeyRepeatState.nextRepeatTime = currentTime + mConfig.keyRepeatDelay;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001516 return newEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001517}
1518
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001519bool InputDispatcher::dispatchConfigurationChangedLocked(nsecs_t currentTime,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001520 const ConfigurationChangedEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001521 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1522 ALOGD("dispatchConfigurationChanged - eventTime=%" PRId64, entry.eventTime);
1523 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001524
1525 // Reset key repeating in case a keyboard device was added or removed or something.
1526 resetKeyRepeatLocked();
1527
1528 // Enqueue a command to run outside the lock to tell the policy that the configuration changed.
Prabir Pradhancef936d2021-07-21 16:17:52 +00001529 auto command = [this, eventTime = entry.eventTime]() REQUIRES(mLock) {
1530 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00001531 mPolicy.notifyConfigurationChanged(eventTime);
Prabir Pradhancef936d2021-07-21 16:17:52 +00001532 };
1533 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001534 return true;
1535}
1536
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001537bool InputDispatcher::dispatchDeviceResetLocked(nsecs_t currentTime,
1538 const DeviceResetEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001539 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1540 ALOGD("dispatchDeviceReset - eventTime=%" PRId64 ", deviceId=%d", entry.eventTime,
1541 entry.deviceId);
1542 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001543
liushenxiang42232912021-05-21 20:24:09 +08001544 // Reset key repeating in case a keyboard device was disabled or enabled.
1545 if (mKeyRepeatState.lastKeyEntry && mKeyRepeatState.lastKeyEntry->deviceId == entry.deviceId) {
1546 resetKeyRepeatLocked();
1547 }
1548
Michael Wrightfb04fd52022-11-24 22:31:11 +00001549 CancelationOptions options(CancelationOptions::Mode::CANCEL_ALL_EVENTS, "device was reset");
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001550 options.deviceId = entry.deviceId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001551 synthesizeCancelationEventsForAllConnectionsLocked(options);
Siarhei Vishniakou0686f0c2023-05-02 11:56:15 -07001552
1553 // Remove all active pointers from this device
1554 for (auto& [_, touchState] : mTouchStatesByDisplay) {
1555 touchState.removeAllPointersForDevice(entry.deviceId);
1556 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001557 return true;
1558}
1559
Vishnu Nairad321cd2020-08-20 16:40:21 -07001560void InputDispatcher::enqueueFocusEventLocked(const sp<IBinder>& windowToken, bool hasFocus,
Vishnu Nairc519ff72021-01-21 08:23:08 -08001561 const std::string& reason) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001562 if (mPendingEvent != nullptr) {
1563 // Move the pending event to the front of the queue. This will give the chance
1564 // for the pending event to get dispatched to the newly focused window
1565 mInboundQueue.push_front(mPendingEvent);
1566 mPendingEvent = nullptr;
1567 }
1568
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001569 std::unique_ptr<FocusEntry> focusEntry =
1570 std::make_unique<FocusEntry>(mIdGenerator.nextId(), now(), windowToken, hasFocus,
1571 reason);
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001572
1573 // This event should go to the front of the queue, but behind all other focus events
1574 // Find the last focus event, and insert right after it
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001575 std::deque<std::shared_ptr<EventEntry>>::reverse_iterator it =
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001576 std::find_if(mInboundQueue.rbegin(), mInboundQueue.rend(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001577 [](const std::shared_ptr<EventEntry>& event) {
1578 return event->type == EventEntry::Type::FOCUS;
1579 });
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001580
1581 // Maintain the order of focus events. Insert the entry after all other focus events.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001582 mInboundQueue.insert(it.base(), std::move(focusEntry));
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001583}
1584
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001585void InputDispatcher::dispatchFocusLocked(nsecs_t currentTime, std::shared_ptr<FocusEntry> entry) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05001586 std::shared_ptr<InputChannel> channel = getInputChannelLocked(entry->connectionToken);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001587 if (channel == nullptr) {
1588 return; // Window has gone away
1589 }
1590 InputTarget target;
1591 target.inputChannel = channel;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08001592 target.flags = InputTarget::Flags::DISPATCH_AS_IS;
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001593 entry->dispatchInProgress = true;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00001594 std::string message = std::string("Focus ") + (entry->hasFocus ? "entering " : "leaving ") +
1595 channel->getName();
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07001596 std::string reason = std::string("reason=").append(entry->reason);
1597 android_log_event_list(LOGTAG_INPUT_FOCUS) << message << reason << LOG_ID_EVENTS;
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001598 dispatchEventLocked(currentTime, entry, {target});
1599}
1600
Prabir Pradhan99987712020-11-10 18:43:05 -08001601void InputDispatcher::dispatchPointerCaptureChangedLocked(
1602 nsecs_t currentTime, const std::shared_ptr<PointerCaptureChangedEntry>& entry,
1603 DropReason& dropReason) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001604 dropReason = DropReason::NOT_DROPPED;
1605
Prabir Pradhan99987712020-11-10 18:43:05 -08001606 const bool haveWindowWithPointerCapture = mWindowTokenWithPointerCapture != nullptr;
Prabir Pradhan99987712020-11-10 18:43:05 -08001607 sp<IBinder> token;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001608
1609 if (entry->pointerCaptureRequest.enable) {
1610 // Enable Pointer Capture.
1611 if (haveWindowWithPointerCapture &&
1612 (entry->pointerCaptureRequest == mCurrentPointerCaptureRequest)) {
Prabir Pradhan7092e262022-05-03 16:51:09 +00001613 // This can happen if pointer capture is disabled and re-enabled before we notify the
1614 // app of the state change, so there is no need to notify the app.
1615 ALOGI("Skipping dispatch of Pointer Capture being enabled: no state change.");
1616 return;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001617 }
1618 if (!mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08001619 // This can happen if a window requests capture and immediately releases capture.
1620 ALOGW("No window requested Pointer Capture.");
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001621 dropReason = DropReason::NO_POINTER_CAPTURE;
Prabir Pradhan99987712020-11-10 18:43:05 -08001622 return;
1623 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001624 if (entry->pointerCaptureRequest.seq != mCurrentPointerCaptureRequest.seq) {
1625 ALOGI("Skipping dispatch of Pointer Capture being enabled: sequence number mismatch.");
1626 return;
1627 }
1628
Vishnu Nairc519ff72021-01-21 08:23:08 -08001629 token = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Prabir Pradhan99987712020-11-10 18:43:05 -08001630 LOG_ALWAYS_FATAL_IF(!token, "Cannot find focused window for Pointer Capture.");
1631 mWindowTokenWithPointerCapture = token;
1632 } else {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001633 // Disable Pointer Capture.
1634 // We do not check if the sequence number matches for requests to disable Pointer Capture
1635 // for two reasons:
1636 // 1. Pointer Capture can be disabled by a focus change, which means we can get two entries
1637 // to disable capture with the same sequence number: one generated by
1638 // disablePointerCaptureForcedLocked() and another as an acknowledgement of Pointer
1639 // Capture being disabled in InputReader.
1640 // 2. We respect any request to disable Pointer Capture generated by InputReader, since the
1641 // actual Pointer Capture state that affects events being generated by input devices is
1642 // in InputReader.
1643 if (!haveWindowWithPointerCapture) {
1644 // Pointer capture was already forcefully disabled because of focus change.
1645 dropReason = DropReason::NOT_DROPPED;
1646 return;
1647 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001648 token = mWindowTokenWithPointerCapture;
1649 mWindowTokenWithPointerCapture = nullptr;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001650 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan7d030382020-12-21 07:58:35 -08001651 setPointerCaptureLocked(false);
1652 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001653 }
1654
1655 auto channel = getInputChannelLocked(token);
1656 if (channel == nullptr) {
1657 // Window has gone away, clean up Pointer Capture state.
1658 mWindowTokenWithPointerCapture = nullptr;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001659 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan7d030382020-12-21 07:58:35 -08001660 setPointerCaptureLocked(false);
1661 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001662 return;
1663 }
1664 InputTarget target;
1665 target.inputChannel = channel;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08001666 target.flags = InputTarget::Flags::DISPATCH_AS_IS;
Prabir Pradhan99987712020-11-10 18:43:05 -08001667 entry->dispatchInProgress = true;
1668 dispatchEventLocked(currentTime, entry, {target});
1669
1670 dropReason = DropReason::NOT_DROPPED;
1671}
1672
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001673void InputDispatcher::dispatchTouchModeChangeLocked(nsecs_t currentTime,
1674 const std::shared_ptr<TouchModeEntry>& entry) {
1675 const std::vector<sp<WindowInfoHandle>>& windowHandles =
Antonio Kantek15beb512022-06-13 22:35:41 +00001676 getWindowHandlesLocked(entry->displayId);
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001677 if (windowHandles.empty()) {
1678 return;
1679 }
1680 const std::vector<InputTarget> inputTargets =
1681 getInputTargetsFromWindowHandlesLocked(windowHandles);
1682 if (inputTargets.empty()) {
1683 return;
1684 }
1685 entry->dispatchInProgress = true;
1686 dispatchEventLocked(currentTime, entry, inputTargets);
1687}
1688
1689std::vector<InputTarget> InputDispatcher::getInputTargetsFromWindowHandlesLocked(
1690 const std::vector<sp<WindowInfoHandle>>& windowHandles) const {
1691 std::vector<InputTarget> inputTargets;
1692 for (const sp<WindowInfoHandle>& handle : windowHandles) {
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001693 const sp<IBinder>& token = handle->getToken();
1694 if (token == nullptr) {
1695 continue;
1696 }
1697 std::shared_ptr<InputChannel> channel = getInputChannelLocked(token);
1698 if (channel == nullptr) {
1699 continue; // Window has gone away
1700 }
1701 InputTarget target;
1702 target.inputChannel = channel;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08001703 target.flags = InputTarget::Flags::DISPATCH_AS_IS;
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001704 inputTargets.push_back(target);
1705 }
1706 return inputTargets;
1707}
1708
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001709bool InputDispatcher::dispatchKeyLocked(nsecs_t currentTime, std::shared_ptr<KeyEntry> entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001710 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001711 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001712 if (!entry->dispatchInProgress) {
1713 if (entry->repeatCount == 0 && entry->action == AKEY_EVENT_ACTION_DOWN &&
1714 (entry->policyFlags & POLICY_FLAG_TRUSTED) &&
1715 (!(entry->policyFlags & POLICY_FLAG_DISABLE_KEY_REPEAT))) {
1716 if (mKeyRepeatState.lastKeyEntry &&
Chris Ye2ad95392020-09-01 13:44:44 -07001717 mKeyRepeatState.lastKeyEntry->keyCode == entry->keyCode &&
Michael Wrightd02c5b62014-02-10 15:10:22 -08001718 // We have seen two identical key downs in a row which indicates that the device
1719 // driver is automatically generating key repeats itself. We take note of the
1720 // repeat here, but we disable our own next key repeat timer since it is clear that
1721 // we will not need to synthesize key repeats ourselves.
Chris Ye2ad95392020-09-01 13:44:44 -07001722 mKeyRepeatState.lastKeyEntry->deviceId == entry->deviceId) {
1723 // Make sure we don't get key down from a different device. If a different
1724 // device Id has same key pressed down, the new device Id will replace the
1725 // current one to hold the key repeat with repeat count reset.
1726 // In the future when got a KEY_UP on the device id, drop it and do not
1727 // stop the key repeat on current device.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001728 entry->repeatCount = mKeyRepeatState.lastKeyEntry->repeatCount + 1;
1729 resetKeyRepeatLocked();
Colin Cross5b799302022-10-18 21:52:41 -07001730 mKeyRepeatState.nextRepeatTime = LLONG_MAX; // don't generate repeats ourselves
Michael Wrightd02c5b62014-02-10 15:10:22 -08001731 } else {
1732 // Not a repeat. Save key down state in case we do see a repeat later.
1733 resetKeyRepeatLocked();
1734 mKeyRepeatState.nextRepeatTime = entry->eventTime + mConfig.keyRepeatTimeout;
1735 }
1736 mKeyRepeatState.lastKeyEntry = entry;
Chris Ye2ad95392020-09-01 13:44:44 -07001737 } else if (entry->action == AKEY_EVENT_ACTION_UP && mKeyRepeatState.lastKeyEntry &&
1738 mKeyRepeatState.lastKeyEntry->deviceId != entry->deviceId) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001739 // The key on device 'deviceId' is still down, do not stop key repeat
Prabir Pradhan65613802023-02-22 23:36:58 +00001740 if (debugInboundEventDetails()) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001741 ALOGD("deviceId=%d got KEY_UP as stale", entry->deviceId);
1742 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001743 } else if (!entry->syntheticRepeat) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001744 resetKeyRepeatLocked();
1745 }
1746
1747 if (entry->repeatCount == 1) {
1748 entry->flags |= AKEY_EVENT_FLAG_LONG_PRESS;
1749 } else {
1750 entry->flags &= ~AKEY_EVENT_FLAG_LONG_PRESS;
1751 }
1752
1753 entry->dispatchInProgress = true;
1754
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001755 logOutboundKeyDetails("dispatchKey - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001756 }
1757
1758 // Handle case where the policy asked us to try again later last time.
Michael Wright5caf55a2022-11-24 22:31:42 +00001759 if (entry->interceptKeyResult == KeyEntry::InterceptKeyResult::TRY_AGAIN_LATER) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001760 if (currentTime < entry->interceptKeyWakeupTime) {
1761 if (entry->interceptKeyWakeupTime < *nextWakeupTime) {
1762 *nextWakeupTime = entry->interceptKeyWakeupTime;
1763 }
1764 return false; // wait until next wakeup
1765 }
Michael Wright5caf55a2022-11-24 22:31:42 +00001766 entry->interceptKeyResult = KeyEntry::InterceptKeyResult::UNKNOWN;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001767 entry->interceptKeyWakeupTime = 0;
1768 }
1769
1770 // Give the policy a chance to intercept the key.
Michael Wright5caf55a2022-11-24 22:31:42 +00001771 if (entry->interceptKeyResult == KeyEntry::InterceptKeyResult::UNKNOWN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001772 if (entry->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07001773 sp<IBinder> focusedWindowToken =
Vishnu Nairc519ff72021-01-21 08:23:08 -08001774 mFocusResolver.getFocusedWindowToken(getTargetDisplayId(*entry));
Prabir Pradhancef936d2021-07-21 16:17:52 +00001775
1776 auto command = [this, focusedWindowToken, entry]() REQUIRES(mLock) {
1777 doInterceptKeyBeforeDispatchingCommand(focusedWindowToken, *entry);
1778 };
1779 postCommandLocked(std::move(command));
Josep del Riob3981622023-04-18 15:49:45 +00001780 // Poke user activity for keys not passed to user
1781 pokeUserActivityLocked(*entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001782 return false; // wait for the command to run
1783 } else {
Michael Wright5caf55a2022-11-24 22:31:42 +00001784 entry->interceptKeyResult = KeyEntry::InterceptKeyResult::CONTINUE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001785 }
Michael Wright5caf55a2022-11-24 22:31:42 +00001786 } else if (entry->interceptKeyResult == KeyEntry::InterceptKeyResult::SKIP) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001787 if (*dropReason == DropReason::NOT_DROPPED) {
1788 *dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001789 }
1790 }
1791
1792 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001793 if (*dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001794 setInjectionResult(*entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001795 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
1796 : InputEventInjectionResult::FAILED);
Garfield Tan6a5a14e2020-01-28 13:24:04 -08001797 mReporter->reportDroppedKey(entry->id);
Josep del Riob3981622023-04-18 15:49:45 +00001798 // Poke user activity for undispatched keys
1799 pokeUserActivityLocked(*entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001800 return true;
1801 }
1802
1803 // Identify targets.
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001804 InputEventInjectionResult injectionResult;
1805 sp<WindowInfoHandle> focusedWindow =
1806 findFocusedWindowTargetLocked(currentTime, *entry, nextWakeupTime,
1807 /*byref*/ injectionResult);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001808 if (injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001809 return false;
1810 }
1811
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001812 setInjectionResult(*entry, injectionResult);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001813 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001814 return true;
1815 }
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001816 LOG_ALWAYS_FATAL_IF(focusedWindow == nullptr);
1817
1818 std::vector<InputTarget> inputTargets;
1819 addWindowTargetLocked(focusedWindow,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08001820 InputTarget::Flags::FOREGROUND | InputTarget::Flags::DISPATCH_AS_IS,
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08001821 /*pointerIds=*/{}, getDownTime(*entry), inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001822
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001823 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001824 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001825
1826 // Dispatch the key.
1827 dispatchEventLocked(currentTime, entry, inputTargets);
1828 return true;
1829}
1830
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001831void InputDispatcher::logOutboundKeyDetails(const char* prefix, const KeyEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001832 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1833 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32 ", "
1834 "policyFlags=0x%x, action=0x%x, flags=0x%x, keyCode=0x%x, scanCode=0x%x, "
1835 "metaState=0x%x, repeatCount=%d, downTime=%" PRId64,
1836 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId,
1837 entry.policyFlags, entry.action, entry.flags, entry.keyCode, entry.scanCode,
1838 entry.metaState, entry.repeatCount, entry.downTime);
1839 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001840}
1841
Prabir Pradhancef936d2021-07-21 16:17:52 +00001842void InputDispatcher::dispatchSensorLocked(nsecs_t currentTime,
1843 const std::shared_ptr<SensorEntry>& entry,
Chris Yef59a2f42020-10-16 12:55:26 -07001844 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001845 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1846 ALOGD("notifySensorEvent eventTime=%" PRId64 ", hwTimestamp=%" PRId64 ", deviceId=%d, "
1847 "source=0x%x, sensorType=%s",
1848 entry->eventTime, entry->hwTimestamp, entry->deviceId, entry->source,
Dominik Laskowski75788452021-02-09 18:51:25 -08001849 ftl::enum_string(entry->sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001850 }
Prabir Pradhancef936d2021-07-21 16:17:52 +00001851 auto command = [this, entry]() REQUIRES(mLock) {
1852 scoped_unlock unlock(mLock);
1853
1854 if (entry->accuracyChanged) {
Prabir Pradhana41d2442023-04-20 21:30:40 +00001855 mPolicy.notifySensorAccuracy(entry->deviceId, entry->sensorType, entry->accuracy);
Prabir Pradhancef936d2021-07-21 16:17:52 +00001856 }
Prabir Pradhana41d2442023-04-20 21:30:40 +00001857 mPolicy.notifySensorEvent(entry->deviceId, entry->sensorType, entry->accuracy,
1858 entry->hwTimestamp, entry->values);
Prabir Pradhancef936d2021-07-21 16:17:52 +00001859 };
1860 postCommandLocked(std::move(command));
Chris Yef59a2f42020-10-16 12:55:26 -07001861}
1862
1863bool InputDispatcher::flushSensor(int deviceId, InputDeviceSensorType sensorType) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001864 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1865 ALOGD("flushSensor deviceId=%d, sensorType=%s", deviceId,
Dominik Laskowski75788452021-02-09 18:51:25 -08001866 ftl::enum_string(sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001867 }
Chris Yef59a2f42020-10-16 12:55:26 -07001868 { // acquire lock
1869 std::scoped_lock _l(mLock);
1870
1871 for (auto it = mInboundQueue.begin(); it != mInboundQueue.end(); it++) {
1872 std::shared_ptr<EventEntry> entry = *it;
1873 if (entry->type == EventEntry::Type::SENSOR) {
1874 it = mInboundQueue.erase(it);
1875 releaseInboundEventLocked(entry);
1876 }
1877 }
1878 }
1879 return true;
1880}
1881
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001882bool InputDispatcher::dispatchMotionLocked(nsecs_t currentTime, std::shared_ptr<MotionEntry> entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001883 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001884 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001885 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001886 if (!entry->dispatchInProgress) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001887 entry->dispatchInProgress = true;
1888
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001889 logOutboundMotionDetails("dispatchMotion - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001890 }
1891
1892 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001893 if (*dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001894 setInjectionResult(*entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001895 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
1896 : InputEventInjectionResult::FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001897 return true;
1898 }
1899
Prabir Pradhanaa561d12021-09-24 06:57:33 -07001900 const bool isPointerEvent = isFromSource(entry->source, AINPUT_SOURCE_CLASS_POINTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001901
1902 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001903 std::vector<InputTarget> inputTargets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001904
1905 bool conflictingPointerActions = false;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001906 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001907 if (isPointerEvent) {
1908 // Pointer event. (eg. touchscreen)
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00001909
1910 if (mDragState &&
1911 (entry->action & AMOTION_EVENT_ACTION_MASK) == AMOTION_EVENT_ACTION_POINTER_DOWN) {
1912 // If drag and drop ongoing and pointer down occur: pilfer drag window pointers
1913 pilferPointersLocked(mDragState->dragWindow->getToken());
1914 }
1915
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08001916 inputTargets =
Siarhei Vishniakou4fe57392022-10-25 13:44:30 -07001917 findTouchedWindowTargetsLocked(currentTime, *entry, &conflictingPointerActions,
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001918 /*byref*/ injectionResult);
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08001919 LOG_ALWAYS_FATAL_IF(injectionResult != InputEventInjectionResult::SUCCEEDED &&
1920 !inputTargets.empty());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001921 } else {
1922 // Non touch event. (eg. trackball)
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001923 sp<WindowInfoHandle> focusedWindow =
1924 findFocusedWindowTargetLocked(currentTime, *entry, nextWakeupTime, injectionResult);
1925 if (injectionResult == InputEventInjectionResult::SUCCEEDED) {
1926 LOG_ALWAYS_FATAL_IF(focusedWindow == nullptr);
1927 addWindowTargetLocked(focusedWindow,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08001928 InputTarget::Flags::FOREGROUND |
1929 InputTarget::Flags::DISPATCH_AS_IS,
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08001930 /*pointerIds=*/{}, getDownTime(*entry), inputTargets);
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001931 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001932 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001933 if (injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001934 return false;
1935 }
1936
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001937 setInjectionResult(*entry, injectionResult);
Prabir Pradhan5735a322022-04-11 17:23:34 +00001938 if (injectionResult == InputEventInjectionResult::TARGET_MISMATCH) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001939 return true;
1940 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001941 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001942 CancelationOptions::Mode mode(
1943 isPointerEvent ? CancelationOptions::Mode::CANCEL_POINTER_EVENTS
1944 : CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS);
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001945 CancelationOptions options(mode, "input event injection failed");
1946 synthesizeCancelationEventsForMonitorsLocked(options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001947 return true;
1948 }
1949
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001950 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001951 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001952
1953 // Dispatch the motion.
1954 if (conflictingPointerActions) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001955 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001956 "conflicting pointer actions");
Michael Wrightd02c5b62014-02-10 15:10:22 -08001957 synthesizeCancelationEventsForAllConnectionsLocked(options);
1958 }
1959 dispatchEventLocked(currentTime, entry, inputTargets);
1960 return true;
1961}
1962
chaviw98318de2021-05-19 16:45:23 -05001963void InputDispatcher::enqueueDragEventLocked(const sp<WindowInfoHandle>& windowHandle,
Arthur Hung54745652022-04-20 07:17:41 +00001964 bool isExiting, const int32_t rawX,
1965 const int32_t rawY) {
1966 const vec2 xy = windowHandle->getInfo()->transform.transform(vec2(rawX, rawY));
arthurhungb89ccb02020-12-30 16:19:01 +08001967 std::unique_ptr<DragEntry> dragEntry =
Arthur Hung54745652022-04-20 07:17:41 +00001968 std::make_unique<DragEntry>(mIdGenerator.nextId(), now(), windowHandle->getToken(),
1969 isExiting, xy.x, xy.y);
arthurhungb89ccb02020-12-30 16:19:01 +08001970
1971 enqueueInboundEventLocked(std::move(dragEntry));
1972}
1973
1974void InputDispatcher::dispatchDragLocked(nsecs_t currentTime, std::shared_ptr<DragEntry> entry) {
1975 std::shared_ptr<InputChannel> channel = getInputChannelLocked(entry->connectionToken);
1976 if (channel == nullptr) {
1977 return; // Window has gone away
1978 }
1979 InputTarget target;
1980 target.inputChannel = channel;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08001981 target.flags = InputTarget::Flags::DISPATCH_AS_IS;
arthurhungb89ccb02020-12-30 16:19:01 +08001982 entry->dispatchInProgress = true;
1983 dispatchEventLocked(currentTime, entry, {target});
1984}
1985
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001986void InputDispatcher::logOutboundMotionDetails(const char* prefix, const MotionEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001987 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -08001988 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=%s, displayId=%" PRId32
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001989 ", policyFlags=0x%x, "
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001990 "action=%s, actionButton=0x%x, flags=0x%x, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001991 "metaState=0x%x, buttonState=0x%x,"
1992 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%" PRId64,
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -08001993 prefix, entry.eventTime, entry.deviceId,
1994 inputEventSourceToString(entry.source).c_str(), entry.displayId, entry.policyFlags,
1995 MotionEvent::actionToString(entry.action).c_str(), entry.actionButton, entry.flags,
1996 entry.metaState, entry.buttonState, entry.edgeFlags, entry.xPrecision,
1997 entry.yPrecision, entry.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001998
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001999 for (uint32_t i = 0; i < entry.pointerCount; i++) {
Siarhei Vishniakou09a8fe42022-07-21 17:27:03 -07002000 ALOGD(" Pointer %d: id=%d, toolType=%s, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002001 "x=%f, y=%f, pressure=%f, size=%f, "
2002 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
2003 "orientation=%f",
Siarhei Vishniakou09a8fe42022-07-21 17:27:03 -07002004 i, entry.pointerProperties[i].id,
2005 ftl::enum_string(entry.pointerProperties[i].toolType).c_str(),
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002006 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
2007 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
2008 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
2009 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
2010 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
2011 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
2012 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
2013 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
2014 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
2015 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002016 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002017}
2018
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002019void InputDispatcher::dispatchEventLocked(nsecs_t currentTime,
2020 std::shared_ptr<EventEntry> eventEntry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002021 const std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002022 ATRACE_CALL();
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002023 if (DEBUG_DISPATCH_CYCLE) {
2024 ALOGD("dispatchEventToCurrentInputTargets");
2025 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002026
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00002027 processInteractionsLocked(*eventEntry, inputTargets);
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00002028
Michael Wrightd02c5b62014-02-10 15:10:22 -08002029 ALOG_ASSERT(eventEntry->dispatchInProgress); // should already have been set to true
2030
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002031 pokeUserActivityLocked(*eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002032
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002033 for (const InputTarget& inputTarget : inputTargets) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07002034 std::shared_ptr<Connection> connection =
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07002035 getConnectionLocked(inputTarget.inputChannel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07002036 if (connection != nullptr) {
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002037 prepareDispatchCycleLocked(currentTime, connection, eventEntry, inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002038 } else {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002039 if (DEBUG_FOCUS) {
2040 ALOGD("Dropping event delivery to target with channel '%s' because it "
2041 "is no longer registered with the input dispatcher.",
2042 inputTarget.inputChannel->getName().c_str());
2043 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002044 }
2045 }
2046}
2047
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07002048void InputDispatcher::cancelEventsForAnrLocked(const std::shared_ptr<Connection>& connection) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002049 // We will not be breaking any connections here, even if the policy wants us to abort dispatch.
2050 // If the policy decides to close the app, we will get a channel removal event via
2051 // unregisterInputChannel, and will clean up the connection that way. We are already not
2052 // sending new pointers to the connection when it blocked, but focused events will continue to
2053 // pile up.
2054 ALOGW("Canceling events for %s because it is unresponsive",
2055 connection->inputChannel->getName().c_str());
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08002056 if (connection->status == Connection::Status::NORMAL) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00002057 CancelationOptions options(CancelationOptions::Mode::CANCEL_ALL_EVENTS,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002058 "application not responding");
2059 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002060 }
2061}
2062
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002063void InputDispatcher::resetNoFocusedWindowTimeoutLocked() {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002064 if (DEBUG_FOCUS) {
2065 ALOGD("Resetting ANR timeouts.");
2066 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002067
2068 // Reset input target wait timeout.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002069 mNoFocusedWindowTimeoutTime = std::nullopt;
Chris Yea209fde2020-07-22 13:54:51 -07002070 mAwaitedFocusedApplication.reset();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002071}
2072
Tiger Huang721e26f2018-07-24 22:26:19 +08002073/**
2074 * Get the display id that the given event should go to. If this event specifies a valid display id,
2075 * then it should be dispatched to that display. Otherwise, the event goes to the focused display.
2076 * Focused display is the display that the user most recently interacted with.
2077 */
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002078int32_t InputDispatcher::getTargetDisplayId(const EventEntry& entry) {
Tiger Huang721e26f2018-07-24 22:26:19 +08002079 int32_t displayId;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002080 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002081 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002082 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
2083 displayId = keyEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002084 break;
2085 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002086 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002087 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
2088 displayId = motionEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002089 break;
2090 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00002091 case EventEntry::Type::TOUCH_MODE_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08002092 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002093 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002094 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07002095 case EventEntry::Type::DEVICE_RESET:
arthurhungb89ccb02020-12-30 16:19:01 +08002096 case EventEntry::Type::SENSOR:
2097 case EventEntry::Type::DRAG: {
Dominik Laskowski75788452021-02-09 18:51:25 -08002098 ALOGE("%s events do not have a target display", ftl::enum_string(entry.type).c_str());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002099 return ADISPLAY_ID_NONE;
2100 }
Tiger Huang721e26f2018-07-24 22:26:19 +08002101 }
2102 return displayId == ADISPLAY_ID_NONE ? mFocusedDisplayId : displayId;
2103}
2104
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002105bool InputDispatcher::shouldWaitToSendKeyLocked(nsecs_t currentTime,
2106 const char* focusedWindowName) {
2107 if (mAnrTracker.empty()) {
2108 // already processed all events that we waited for
2109 mKeyIsWaitingForEventsTimeout = std::nullopt;
2110 return false;
2111 }
2112
2113 if (!mKeyIsWaitingForEventsTimeout.has_value()) {
2114 // Start the timer
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00002115 // Wait to send key because there are unprocessed events that may cause focus to change
Siarhei Vishniakou70622952020-07-30 11:17:23 -05002116 mKeyIsWaitingForEventsTimeout = currentTime +
2117 std::chrono::duration_cast<std::chrono::nanoseconds>(KEY_WAITING_FOR_EVENTS_TIMEOUT)
2118 .count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002119 return true;
2120 }
2121
2122 // We still have pending events, and already started the timer
2123 if (currentTime < *mKeyIsWaitingForEventsTimeout) {
2124 return true; // Still waiting
2125 }
2126
2127 // Waited too long, and some connection still hasn't processed all motions
2128 // Just send the key to the focused window
2129 ALOGW("Dispatching key to %s even though there are other unprocessed events",
2130 focusedWindowName);
2131 mKeyIsWaitingForEventsTimeout = std::nullopt;
2132 return false;
2133}
2134
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002135sp<WindowInfoHandle> InputDispatcher::findFocusedWindowTargetLocked(
2136 nsecs_t currentTime, const EventEntry& entry, nsecs_t* nextWakeupTime,
2137 InputEventInjectionResult& outInjectionResult) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002138 std::string reason;
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002139 outInjectionResult = InputEventInjectionResult::FAILED; // Default result
Michael Wrightd02c5b62014-02-10 15:10:22 -08002140
Tiger Huang721e26f2018-07-24 22:26:19 +08002141 int32_t displayId = getTargetDisplayId(entry);
chaviw98318de2021-05-19 16:45:23 -05002142 sp<WindowInfoHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Chris Yea209fde2020-07-22 13:54:51 -07002143 std::shared_ptr<InputApplicationHandle> focusedApplicationHandle =
Tiger Huang721e26f2018-07-24 22:26:19 +08002144 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
2145
Michael Wrightd02c5b62014-02-10 15:10:22 -08002146 // If there is no currently focused window and no focused application
2147 // then drop the event.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002148 if (focusedWindowHandle == nullptr && focusedApplicationHandle == nullptr) {
2149 ALOGI("Dropping %s event because there is no focused window or focused application in "
2150 "display %" PRId32 ".",
Dominik Laskowski75788452021-02-09 18:51:25 -08002151 ftl::enum_string(entry.type).c_str(), displayId);
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002152 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002153 }
2154
Vishnu Nair062a8672021-09-03 16:07:44 -07002155 // Drop key events if requested by input feature
2156 if (focusedWindowHandle != nullptr && shouldDropInput(entry, focusedWindowHandle)) {
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002157 return nullptr;
Vishnu Nair062a8672021-09-03 16:07:44 -07002158 }
2159
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002160 // Compatibility behavior: raise ANR if there is a focused application, but no focused window.
2161 // Only start counting when we have a focused event to dispatch. The ANR is canceled if we
2162 // start interacting with another application via touch (app switch). This code can be removed
2163 // if the "no focused window ANR" is moved to the policy. Input doesn't know whether
2164 // an app is expected to have a focused window.
2165 if (focusedWindowHandle == nullptr && focusedApplicationHandle != nullptr) {
2166 if (!mNoFocusedWindowTimeoutTime.has_value()) {
2167 // We just discovered that there's no focused window. Start the ANR timer
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05002168 std::chrono::nanoseconds timeout = focusedApplicationHandle->getDispatchingTimeout(
2169 DEFAULT_INPUT_DISPATCHING_TIMEOUT);
2170 mNoFocusedWindowTimeoutTime = currentTime + timeout.count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002171 mAwaitedFocusedApplication = focusedApplicationHandle;
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05002172 mAwaitedApplicationDisplayId = displayId;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002173 ALOGW("Waiting because no window has focus but %s may eventually add a "
2174 "window when it finishes starting up. Will wait for %" PRId64 "ms",
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05002175 mAwaitedFocusedApplication->getName().c_str(), millis(timeout));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002176 *nextWakeupTime = *mNoFocusedWindowTimeoutTime;
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002177 outInjectionResult = InputEventInjectionResult::PENDING;
2178 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002179 } else if (currentTime > *mNoFocusedWindowTimeoutTime) {
2180 // Already raised ANR. Drop the event
2181 ALOGE("Dropping %s event because there is no focused window",
Dominik Laskowski75788452021-02-09 18:51:25 -08002182 ftl::enum_string(entry.type).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002183 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002184 } else {
2185 // Still waiting for the focused window
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002186 outInjectionResult = InputEventInjectionResult::PENDING;
2187 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002188 }
2189 }
2190
2191 // we have a valid, non-null focused window
2192 resetNoFocusedWindowTimeoutLocked();
2193
Prabir Pradhan5735a322022-04-11 17:23:34 +00002194 // Verify targeted injection.
2195 if (const auto err = verifyTargetedInjection(focusedWindowHandle, entry); err) {
2196 ALOGW("Dropping injected event: %s", (*err).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002197 outInjectionResult = InputEventInjectionResult::TARGET_MISMATCH;
2198 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002199 }
2200
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002201 if (focusedWindowHandle->getInfo()->inputConfig.test(
2202 WindowInfo::InputConfig::PAUSE_DISPATCHING)) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002203 ALOGI("Waiting because %s is paused", focusedWindowHandle->getName().c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002204 outInjectionResult = InputEventInjectionResult::PENDING;
2205 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002206 }
2207
2208 // If the event is a key event, then we must wait for all previous events to
2209 // complete before delivering it because previous events may have the
2210 // side-effect of transferring focus to a different window and we want to
2211 // ensure that the following keys are sent to the new window.
2212 //
2213 // Suppose the user touches a button in a window then immediately presses "A".
2214 // If the button causes a pop-up window to appear then we want to ensure that
2215 // the "A" key is delivered to the new pop-up window. This is because users
2216 // often anticipate pending UI changes when typing on a keyboard.
2217 // To obtain this behavior, we must serialize key events with respect to all
2218 // prior input events.
2219 if (entry.type == EventEntry::Type::KEY) {
2220 if (shouldWaitToSendKeyLocked(currentTime, focusedWindowHandle->getName().c_str())) {
2221 *nextWakeupTime = *mKeyIsWaitingForEventsTimeout;
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002222 outInjectionResult = InputEventInjectionResult::PENDING;
2223 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002224 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002225 }
2226
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002227 outInjectionResult = InputEventInjectionResult::SUCCEEDED;
2228 return focusedWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002229}
2230
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002231/**
2232 * Given a list of monitors, remove the ones we cannot find a connection for, and the ones
2233 * that are currently unresponsive.
2234 */
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002235std::vector<Monitor> InputDispatcher::selectResponsiveMonitorsLocked(
2236 const std::vector<Monitor>& monitors) const {
2237 std::vector<Monitor> responsiveMonitors;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002238 std::copy_if(monitors.begin(), monitors.end(), std::back_inserter(responsiveMonitors),
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002239 [this](const Monitor& monitor) REQUIRES(mLock) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07002240 std::shared_ptr<Connection> connection =
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002241 getConnectionLocked(monitor.inputChannel->getConnectionToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002242 if (connection == nullptr) {
2243 ALOGE("Could not find connection for monitor %s",
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002244 monitor.inputChannel->getName().c_str());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002245 return false;
2246 }
2247 if (!connection->responsive) {
2248 ALOGW("Unresponsive monitor %s will not get the new gesture",
2249 connection->inputChannel->getName().c_str());
2250 return false;
2251 }
2252 return true;
2253 });
2254 return responsiveMonitors;
2255}
2256
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002257std::vector<InputTarget> InputDispatcher::findTouchedWindowTargetsLocked(
Siarhei Vishniakou4fe57392022-10-25 13:44:30 -07002258 nsecs_t currentTime, const MotionEntry& entry, bool* outConflictingPointerActions,
2259 InputEventInjectionResult& outInjectionResult) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002260 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002261
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002262 std::vector<InputTarget> targets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002263 // For security reasons, we defer updating the touch state until we are sure that
2264 // event injection will be allowed.
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002265 const int32_t displayId = entry.displayId;
2266 const int32_t action = entry.action;
Siarhei Vishniakoubf880522023-05-01 11:03:22 -07002267 const int32_t maskedAction = MotionEvent::getActionMasked(action);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002268
2269 // Update the touch state as needed based on the properties of the touch event.
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002270 outInjectionResult = InputEventInjectionResult::PENDING;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002271
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002272 // Copy current touch state into tempTouchState.
2273 // This state will be used to update mTouchStatesByDisplay at the end of this function.
2274 // If no state for the specified display exists, then our initial state will be empty.
Yi Kong9b14ac62018-07-17 13:48:38 -07002275 const TouchState* oldState = nullptr;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002276 TouchState tempTouchState;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002277 if (const auto it = mTouchStatesByDisplay.find(displayId); it != mTouchStatesByDisplay.end()) {
2278 oldState = &(it->second);
Prabir Pradhane680f9b2022-02-04 04:24:00 -08002279 tempTouchState = *oldState;
Jeff Brownf086ddb2014-02-11 14:28:48 -08002280 }
2281
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07002282 bool isSplit = shouldSplitTouch(tempTouchState, entry);
Siarhei Vishniakou45504fe2023-05-05 16:05:10 -07002283 bool switchedDevice = false;
2284 if (oldState != nullptr) {
2285 std::set<int32_t> oldActiveDevices = oldState->getActiveDeviceIds();
2286 const bool anotherDeviceIsActive =
2287 oldActiveDevices.count(entry.deviceId) == 0 && !oldActiveDevices.empty();
2288 switchedDevice |= anotherDeviceIsActive;
Siarhei Vishniakou45504fe2023-05-05 16:05:10 -07002289 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002290
2291 const bool isHoverAction = (maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE ||
2292 maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2293 maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT);
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002294 // A DOWN could be generated from POINTER_DOWN if the initial pointers did not land into any
2295 // touchable windows.
2296 const bool wasDown = oldState != nullptr && oldState->isDown();
2297 const bool isDown = (maskedAction == AMOTION_EVENT_ACTION_DOWN) ||
2298 (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN && !wasDown);
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07002299 const bool newGesture = isDown || maskedAction == AMOTION_EVENT_ACTION_SCROLL ||
2300 maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2301 maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE;
Prabir Pradhanaa561d12021-09-24 06:57:33 -07002302 const bool isFromMouse = isFromSource(entry.source, AINPUT_SOURCE_MOUSE);
Siarhei Vishniakou5cee1e32022-11-29 12:35:39 -08002303
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002304 // If pointers are already down, let's finish the current gesture and ignore the new events
2305 // from another device. However, if the new event is a down event, let's cancel the current
2306 // touch and let the new one take over.
2307 if (switchedDevice && wasDown && !isDown) {
Siarhei Vishniakou45504fe2023-05-05 16:05:10 -07002308 LOG(INFO) << "Dropping event because a pointer for another device "
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002309 << " is already down in display " << displayId << ": " << entry.getDescription();
2310 // TODO(b/211379801): test multiple simultaneous input streams.
2311 outInjectionResult = InputEventInjectionResult::FAILED;
2312 return {}; // wrong device
2313 }
2314
Michael Wrightd02c5b62014-02-10 15:10:22 -08002315 if (newGesture) {
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002316 // If a new gesture is starting, clear the touch state completely.
2317 tempTouchState.reset();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002318 isSplit = false;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04002319 } else if (switchedDevice && maskedAction == AMOTION_EVENT_ACTION_MOVE) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07002320 ALOGI("Dropping move event because a pointer for a different device is already active "
2321 "in display %" PRId32,
2322 displayId);
Siarhei Vishniakou16e4fa02023-02-16 17:48:56 -08002323 // TODO(b/211379801): test multiple simultaneous input streams.
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002324 outInjectionResult = InputEventInjectionResult::FAILED;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002325 return {}; // wrong device
Michael Wrightd02c5b62014-02-10 15:10:22 -08002326 }
2327
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002328 if (isHoverAction) {
2329 // For hover actions, we will treat 'tempTouchState' as a new state, so let's erase
2330 // all of the existing hovering pointers and recompute.
2331 tempTouchState.clearHoveringPointers();
2332 }
2333
Michael Wrightd02c5b62014-02-10 15:10:22 -08002334 if (newGesture || (isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN)) {
2335 /* Case 1: New splittable pointer going down, or need target for hover or scroll. */
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07002336 const auto [x, y] = resolveTouchedPosition(entry);
Siarhei Vishniakou5b9766d2023-07-18 14:06:29 -07002337 const int32_t pointerIndex = MotionEvent::getActionIndex(action);
Siarhei Vishniakou70f3d8c2023-09-19 15:36:52 -07002338 const int32_t pointerId = entry.pointerProperties[pointerIndex].id;
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002339 // Outside targets should be added upon first dispatched DOWN event. That means, this should
2340 // be a pointer that would generate ACTION_DOWN, *and* touch should not already be down.
Prabir Pradhand65552b2021-10-07 11:23:50 -07002341 const bool isStylus = isPointerFromStylus(entry, pointerIndex);
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07002342 sp<WindowInfoHandle> newTouchedWindowHandle =
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002343 findTouchedWindowAtLocked(displayId, x, y, isStylus);
Michael Wright3dd60e22019-03-27 22:06:44 +00002344
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002345 if (isDown) {
Siarhei Vishniakou70f3d8c2023-09-19 15:36:52 -07002346 targets += findOutsideTargetsLocked(displayId, newTouchedWindowHandle, pointerId);
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002347 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002348 // Handle the case where we did not find a window.
Yi Kong9b14ac62018-07-17 13:48:38 -07002349 if (newTouchedWindowHandle == nullptr) {
Prabir Pradhan82e081e2022-12-06 09:50:09 +00002350 ALOGD("No new touched window at (%.1f, %.1f) in display %" PRId32, x, y, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002351 // Try to assign the pointer to the first foreground window we find, if there is one.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002352 newTouchedWindowHandle = tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002353 }
2354
Prabir Pradhan5735a322022-04-11 17:23:34 +00002355 // Verify targeted injection.
2356 if (const auto err = verifyTargetedInjection(newTouchedWindowHandle, entry); err) {
2357 ALOGW("Dropping injected touch event: %s", (*err).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002358 outInjectionResult = os::InputEventInjectionResult::TARGET_MISMATCH;
Prabir Pradhan5735a322022-04-11 17:23:34 +00002359 newTouchedWindowHandle = nullptr;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002360 return {};
Prabir Pradhan5735a322022-04-11 17:23:34 +00002361 }
2362
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002363 // Figure out whether splitting will be allowed for this window.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002364 if (newTouchedWindowHandle != nullptr) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002365 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
2366 // New window supports splitting, but we should never split mouse events.
2367 isSplit = !isFromMouse;
2368 } else if (isSplit) {
2369 // New window does not support splitting but we have already split events.
2370 // Ignore the new window.
Siarhei Vishniakou25537f82023-07-18 14:35:47 -07002371 LOG(INFO) << "Skipping " << newTouchedWindowHandle->getName()
2372 << " because it doesn't support split touch";
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002373 newTouchedWindowHandle = nullptr;
2374 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002375 } else {
2376 // No window is touched, so set split to true. This will allow the next pointer down to
Prabir Pradhan713bb3e2021-12-20 02:07:40 -08002377 // be delivered to a new window which supports split touch. Pointers from a mouse device
2378 // should never be split.
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07002379 isSplit = !isFromMouse;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002380 }
2381
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002382 std::vector<sp<WindowInfoHandle>> newTouchedWindows =
Prabir Pradhand65552b2021-10-07 11:23:50 -07002383 findTouchedSpyWindowsAtLocked(displayId, x, y, isStylus);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002384 if (newTouchedWindowHandle != nullptr) {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002385 // Process the foreground window first so that it is the first to receive the event.
2386 newTouchedWindows.insert(newTouchedWindows.begin(), newTouchedWindowHandle);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002387 }
2388
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002389 if (newTouchedWindows.empty()) {
Prabir Pradhan82e081e2022-12-06 09:50:09 +00002390 ALOGI("Dropping event because there is no touchable window at (%.1f, %.1f) on display "
2391 "%d.",
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002392 x, y, displayId);
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002393 outInjectionResult = InputEventInjectionResult::FAILED;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002394 return {};
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002395 }
2396
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002397 for (const sp<WindowInfoHandle>& windowHandle : newTouchedWindows) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07002398 if (!canWindowReceiveMotionLocked(windowHandle, entry)) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002399 continue;
2400 }
2401
Siarhei Vishniakoub681c202023-05-01 11:22:33 -07002402 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2403 maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE) {
Siarhei Vishniakoub681c202023-05-01 11:22:33 -07002404 // The "windowHandle" is the target of this hovering pointer.
2405 tempTouchState.addHoveringPointerToWindow(windowHandle, entry.deviceId, pointerId);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002406 }
2407
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002408 // Set target flags.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002409 ftl::Flags<InputTarget::Flags> targetFlags = InputTarget::Flags::DISPATCH_AS_IS;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002410
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002411 if (canReceiveForegroundTouches(*windowHandle->getInfo())) {
2412 // There should only be one touched window that can be "foreground" for the pointer.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002413 targetFlags |= InputTarget::Flags::FOREGROUND;
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002414 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002415
2416 if (isSplit) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002417 targetFlags |= InputTarget::Flags::SPLIT;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002418 }
2419 if (isWindowObscuredAtPointLocked(windowHandle, x, y)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002420 targetFlags |= InputTarget::Flags::WINDOW_IS_OBSCURED;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002421 } else if (isWindowObscuredLocked(windowHandle)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002422 targetFlags |= InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002423 }
Michael Wright3dd60e22019-03-27 22:06:44 +00002424
2425 // Update the temporary touch state.
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08002426 std::bitset<MAX_POINTER_ID + 1> pointerIds;
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002427 if (!isHoverAction) {
Siarhei Vishniakou70f3d8c2023-09-19 15:36:52 -07002428 pointerIds.set(pointerId);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002429 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002430
Siarhei Vishniakoue0431e42023-01-28 17:01:39 -08002431 const bool isDownOrPointerDown = maskedAction == AMOTION_EVENT_ACTION_DOWN ||
2432 maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN;
2433
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002434 // TODO(b/211379801): Currently, even if pointerIds are empty (hover case), we would
2435 // still add a window to the touch state. We should avoid doing that, but some of the
2436 // later checks ("at least one foreground window") rely on this in order to dispatch
2437 // the event properly, so that needs to be updated, possibly by looking at InputTargets.
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002438 tempTouchState.addOrUpdateWindow(windowHandle, targetFlags, entry.deviceId, pointerIds,
Siarhei Vishniakoue0431e42023-01-28 17:01:39 -08002439 isDownOrPointerDown
2440 ? std::make_optional(entry.eventTime)
2441 : std::nullopt);
Arthur Hungc539dbb2022-12-08 07:45:36 +00002442
2443 // If this is the pointer going down and the touched window has a wallpaper
2444 // then also add the touched wallpaper windows so they are locked in for the duration
2445 // of the touch gesture.
2446 // We do not collect wallpapers during HOVER_MOVE or SCROLL because the wallpaper
2447 // engine only supports touch events. We would need to add a mechanism similar
2448 // to View.onGenericMotionEvent to enable wallpapers to handle these events.
Siarhei Vishniakoue0431e42023-01-28 17:01:39 -08002449 if (isDownOrPointerDown) {
Arthur Hungc539dbb2022-12-08 07:45:36 +00002450 if (targetFlags.test(InputTarget::Flags::FOREGROUND) &&
2451 windowHandle->getInfo()->inputConfig.test(
2452 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER)) {
2453 sp<WindowInfoHandle> wallpaper = findWallpaperWindowBelow(windowHandle);
2454 if (wallpaper != nullptr) {
2455 ftl::Flags<InputTarget::Flags> wallpaperFlags =
2456 InputTarget::Flags::WINDOW_IS_OBSCURED |
2457 InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED |
2458 InputTarget::Flags::DISPATCH_AS_IS;
2459 if (isSplit) {
2460 wallpaperFlags |= InputTarget::Flags::SPLIT;
2461 }
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002462 tempTouchState.addOrUpdateWindow(wallpaper, wallpaperFlags, entry.deviceId,
2463 pointerIds, entry.eventTime);
Arthur Hungc539dbb2022-12-08 07:45:36 +00002464 }
2465 }
2466 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002467 }
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00002468
Siarhei Vishniakou060f82b2023-01-27 06:39:14 -08002469 // If a window is already pilfering some pointers, give it this new pointer as well and
2470 // make it pilfering. This will prevent other non-spy windows from getting this pointer,
2471 // which is a specific behaviour that we want.
Siarhei Vishniakou060f82b2023-01-27 06:39:14 -08002472 for (TouchedWindow& touchedWindow : tempTouchState.windows) {
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002473 if (touchedWindow.hasTouchingPointer(entry.deviceId, pointerId) &&
2474 touchedWindow.hasPilferingPointers(entry.deviceId)) {
Siarhei Vishniakou060f82b2023-01-27 06:39:14 -08002475 // This window is already pilfering some pointers, and this new pointer is also
2476 // going to it. Therefore, take over this pointer and don't give it to anyone
2477 // else.
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002478 touchedWindow.addPilferingPointer(entry.deviceId, pointerId);
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00002479 }
2480 }
Siarhei Vishniakou060f82b2023-01-27 06:39:14 -08002481
2482 // Restrict all pilfered pointers to the pilfering windows.
2483 tempTouchState.cancelPointersForNonPilferingWindows();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002484 } else {
2485 /* Case 2: Pointer move, up, cancel or non-splittable pointer down. */
2486
2487 // If the pointer is not currently down, then ignore the event.
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07002488 if (!tempTouchState.isDown() && maskedAction != AMOTION_EVENT_ACTION_HOVER_EXIT) {
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002489 LOG(INFO) << "Dropping event because the pointer is not down or we previously "
2490 "dropped the pointer down event in display "
2491 << displayId << ": " << entry.getDescription();
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002492 outInjectionResult = InputEventInjectionResult::FAILED;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002493 return {};
Michael Wrightd02c5b62014-02-10 15:10:22 -08002494 }
2495
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07002496 // If the pointer is not currently hovering, then ignore the event.
2497 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT) {
2498 const int32_t pointerId = entry.pointerProperties[0].id;
2499 if (oldState == nullptr ||
2500 oldState->getWindowsWithHoveringPointer(entry.deviceId, pointerId).empty()) {
2501 LOG(INFO) << "Dropping event because the hovering pointer is not in any windows in "
2502 "display "
2503 << displayId << ": " << entry.getDescription();
2504 outInjectionResult = InputEventInjectionResult::FAILED;
2505 return {};
2506 }
2507 tempTouchState.removeHoveringPointer(entry.deviceId, pointerId);
2508 }
2509
arthurhung6d4bed92021-03-17 11:59:33 +08002510 addDragEventLocked(entry);
arthurhungb89ccb02020-12-30 16:19:01 +08002511
Michael Wrightd02c5b62014-02-10 15:10:22 -08002512 // Check whether touches should slip outside of the current foreground window.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002513 if (maskedAction == AMOTION_EVENT_ACTION_MOVE && entry.pointerCount == 1 &&
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002514 tempTouchState.isSlippery()) {
Siarhei Vishniakou9306c382022-09-30 15:30:31 -07002515 const auto [x, y] = resolveTouchedPosition(entry);
Harry Cutts33476232023-01-30 19:57:29 +00002516 const bool isStylus = isPointerFromStylus(entry, /*pointerIndex=*/0);
chaviw98318de2021-05-19 16:45:23 -05002517 sp<WindowInfoHandle> oldTouchedWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002518 tempTouchState.getFirstForegroundWindowHandle();
Siarhei Vishniakou0f6558d2023-04-21 12:05:13 -07002519 LOG_ALWAYS_FATAL_IF(oldTouchedWindowHandle == nullptr);
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07002520 sp<WindowInfoHandle> newTouchedWindowHandle =
2521 findTouchedWindowAtLocked(displayId, x, y, isStylus);
Vishnu Nair062a8672021-09-03 16:07:44 -07002522
Prabir Pradhan5735a322022-04-11 17:23:34 +00002523 // Verify targeted injection.
2524 if (const auto err = verifyTargetedInjection(newTouchedWindowHandle, entry); err) {
2525 ALOGW("Dropping injected event: %s", (*err).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002526 outInjectionResult = os::InputEventInjectionResult::TARGET_MISMATCH;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002527 return {};
Prabir Pradhan5735a322022-04-11 17:23:34 +00002528 }
2529
Vishnu Nair062a8672021-09-03 16:07:44 -07002530 // Drop touch events if requested by input feature
2531 if (newTouchedWindowHandle != nullptr &&
2532 shouldDropInput(entry, newTouchedWindowHandle)) {
2533 newTouchedWindowHandle = nullptr;
2534 }
2535
Siarhei Vishniakouafa08cc2023-05-08 22:35:50 -07002536 if (newTouchedWindowHandle != nullptr &&
2537 !haveSameToken(oldTouchedWindowHandle, newTouchedWindowHandle)) {
Siarhei Vishniakou0f6558d2023-04-21 12:05:13 -07002538 ALOGD("Touch is slipping out of window %s into window %s in display %" PRId32,
2539 oldTouchedWindowHandle->getName().c_str(),
2540 newTouchedWindowHandle->getName().c_str(), displayId);
2541
Michael Wrightd02c5b62014-02-10 15:10:22 -08002542 // Make a slippery exit from the old window.
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08002543 std::bitset<MAX_POINTER_ID + 1> pointerIds;
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002544 const int32_t pointerId = entry.pointerProperties[0].id;
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08002545 pointerIds.set(pointerId);
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002546
2547 const TouchedWindow& touchedWindow =
2548 tempTouchState.getTouchedWindow(oldTouchedWindowHandle);
2549 addWindowTargetLocked(oldTouchedWindowHandle,
2550 InputTarget::Flags::DISPATCH_AS_SLIPPERY_EXIT, pointerIds,
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002551 touchedWindow.getDownTimeInTarget(entry.deviceId), targets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002552
2553 // Make a slippery entrance into the new window.
2554 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
Prabir Pradhan713bb3e2021-12-20 02:07:40 -08002555 isSplit = !isFromMouse;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002556 }
2557
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002558 ftl::Flags<InputTarget::Flags> targetFlags =
2559 InputTarget::Flags::DISPATCH_AS_SLIPPERY_ENTER;
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002560 if (canReceiveForegroundTouches(*newTouchedWindowHandle->getInfo())) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002561 targetFlags |= InputTarget::Flags::FOREGROUND;
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002562 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002563 if (isSplit) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002564 targetFlags |= InputTarget::Flags::SPLIT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002565 }
2566 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002567 targetFlags |= InputTarget::Flags::WINDOW_IS_OBSCURED;
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002568 } else if (isWindowObscuredLocked(newTouchedWindowHandle)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002569 targetFlags |= InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002570 }
2571
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002572 tempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags,
2573 entry.deviceId, pointerIds, entry.eventTime);
Arthur Hungc539dbb2022-12-08 07:45:36 +00002574
2575 // Check if the wallpaper window should deliver the corresponding event.
2576 slipWallpaperTouch(targetFlags, oldTouchedWindowHandle, newTouchedWindowHandle,
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002577 tempTouchState, entry.deviceId, pointerId, targets);
2578 tempTouchState.removeTouchingPointerFromWindow(entry.deviceId, pointerId,
2579 oldTouchedWindowHandle);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002580 }
2581 }
Arthur Hung96483742022-11-15 03:30:48 +00002582
2583 // Update the pointerIds for non-splittable when it received pointer down.
2584 if (!isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN) {
2585 // If no split, we suppose all touched windows should receive pointer down.
Siarhei Vishniakou5b9766d2023-07-18 14:06:29 -07002586 const int32_t pointerIndex = MotionEvent::getActionIndex(action);
Arthur Hung96483742022-11-15 03:30:48 +00002587 for (size_t i = 0; i < tempTouchState.windows.size(); i++) {
2588 TouchedWindow& touchedWindow = tempTouchState.windows[i];
2589 // Ignore drag window for it should just track one pointer.
2590 if (mDragState && mDragState->dragWindow == touchedWindow.windowHandle) {
2591 continue;
2592 }
Siarhei Vishniakou5b9766d2023-07-18 14:06:29 -07002593 std::bitset<MAX_POINTER_ID + 1> touchingPointers;
2594 touchingPointers.set(entry.pointerProperties[pointerIndex].id);
2595 touchedWindow.addTouchingPointers(entry.deviceId, touchingPointers);
Arthur Hung96483742022-11-15 03:30:48 +00002596 }
2597 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002598 }
2599
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002600 // Update dispatching for hover enter and exit.
Sam Dubeyf886dec2023-01-27 13:28:19 +00002601 {
2602 std::vector<TouchedWindow> hoveringWindows =
2603 getHoveringWindowsLocked(oldState, tempTouchState, entry);
2604 for (const TouchedWindow& touchedWindow : hoveringWindows) {
Siarhei Vishniakoud5876ba2023-05-15 17:58:34 -07002605 std::optional<InputTarget> target =
2606 createInputTargetLocked(touchedWindow.windowHandle, touchedWindow.targetFlags,
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002607 touchedWindow.getDownTimeInTarget(entry.deviceId));
Siarhei Vishniakoud5876ba2023-05-15 17:58:34 -07002608 if (!target) {
2609 continue;
2610 }
2611 // Hardcode to single hovering pointer for now.
2612 std::bitset<MAX_POINTER_ID + 1> pointerIds;
2613 pointerIds.set(entry.pointerProperties[0].id);
2614 target->addPointers(pointerIds, touchedWindow.windowHandle->getInfo()->transform);
2615 targets.push_back(*target);
Sam Dubeyf886dec2023-01-27 13:28:19 +00002616 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002617 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002618
Prabir Pradhan5735a322022-04-11 17:23:34 +00002619 // Ensure that all touched windows are valid for injection.
2620 if (entry.injectionState != nullptr) {
2621 std::string errs;
2622 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Prabir Pradhan5735a322022-04-11 17:23:34 +00002623 const auto err = verifyTargetedInjection(touchedWindow.windowHandle, entry);
2624 if (err) errs += "\n - " + *err;
2625 }
2626 if (!errs.empty()) {
2627 ALOGW("Dropping targeted injection: At least one touched window is not owned by uid "
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00002628 "%s:%s",
2629 entry.injectionState->targetUid->toString().c_str(), errs.c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002630 outInjectionResult = InputEventInjectionResult::TARGET_MISMATCH;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002631 return {};
Prabir Pradhan5735a322022-04-11 17:23:34 +00002632 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002633 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002634
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002635 // Check whether windows listening for outside touches are owned by the same UID. If the owner
2636 // has a different UID, then we will not reveal coordinate information to this window.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002637 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
chaviw98318de2021-05-19 16:45:23 -05002638 sp<WindowInfoHandle> foregroundWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002639 tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002640 if (foregroundWindowHandle) {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00002641 const auto foregroundWindowUid = foregroundWindowHandle->getInfo()->ownerUid;
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002642 for (InputTarget& target : targets) {
2643 if (target.flags.test(InputTarget::Flags::DISPATCH_AS_OUTSIDE)) {
2644 sp<WindowInfoHandle> targetWindow =
2645 getWindowHandleLocked(target.inputChannel->getConnectionToken());
2646 if (targetWindow->getInfo()->ownerUid != foregroundWindowUid) {
2647 target.flags |= InputTarget::Flags::ZERO_COORDS;
Michael Wright3dd60e22019-03-27 22:06:44 +00002648 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002649 }
2650 }
2651 }
2652 }
2653
Harry Cuttsb166c002023-05-09 13:06:05 +00002654 // If this is a touchpad navigation gesture, it needs to only be sent to trusted targets, as we
2655 // only want the system UI to handle these gestures.
2656 const bool isTouchpadNavGesture = isFromSource(entry.source, AINPUT_SOURCE_MOUSE) &&
2657 entry.classification == MotionClassification::MULTI_FINGER_SWIPE;
2658 if (isTouchpadNavGesture) {
2659 filterUntrustedTargets(/* byref */ tempTouchState, /* byref */ targets);
2660 }
2661
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07002662 // Output targets from the touch state.
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002663 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002664 if (!touchedWindow.hasTouchingPointers(entry.deviceId) &&
2665 !touchedWindow.hasHoveringPointers(entry.deviceId)) {
Siarhei Vishniakoue0431e42023-01-28 17:01:39 -08002666 // Windows with hovering pointers are getting persisted inside TouchState.
2667 // Do not send this event to those windows.
2668 continue;
2669 }
Harry Cuttsb166c002023-05-09 13:06:05 +00002670
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002671 addWindowTargetLocked(touchedWindow.windowHandle, touchedWindow.targetFlags,
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002672 touchedWindow.getTouchingPointers(entry.deviceId),
2673 touchedWindow.getDownTimeInTarget(entry.deviceId), targets);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002674 }
Sam Dubey39d37cf2022-12-07 18:05:35 +00002675
Siarhei Vishniakou580fb3a2023-05-05 15:02:20 -07002676 // During targeted injection, only allow owned targets to receive events
2677 std::erase_if(targets, [&](const InputTarget& target) {
2678 LOG_ALWAYS_FATAL_IF(target.windowHandle == nullptr);
2679 const auto err = verifyTargetedInjection(target.windowHandle, entry);
2680 if (err) {
2681 LOG(WARNING) << "Dropping injected event from " << target.windowHandle->getName()
2682 << ": " << (*err);
2683 return true;
2684 }
2685 return false;
2686 });
2687
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07002688 if (targets.empty()) {
2689 LOG(INFO) << "Dropping event because no targets were found: " << entry.getDescription();
2690 outInjectionResult = InputEventInjectionResult::FAILED;
2691 return {};
2692 }
2693
2694 // If we only have windows getting ACTION_OUTSIDE, then drop the event, because there is no
2695 // window that is actually receiving the entire gesture.
2696 if (std::all_of(targets.begin(), targets.end(), [](const InputTarget& target) {
2697 return target.flags.test(InputTarget::Flags::DISPATCH_AS_OUTSIDE);
2698 })) {
2699 LOG(INFO) << "Dropping event because all windows would just receive ACTION_OUTSIDE: "
2700 << entry.getDescription();
2701 outInjectionResult = InputEventInjectionResult::FAILED;
2702 return {};
2703 }
2704
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002705 outInjectionResult = InputEventInjectionResult::SUCCEEDED;
Sam Dubeyf886dec2023-01-27 13:28:19 +00002706 // Drop the outside or hover touch windows since we will not care about them
2707 // in the next iteration.
2708 tempTouchState.filterNonAsIsTouchWindows();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002709
Michael Wrightd02c5b62014-02-10 15:10:22 -08002710 // Update final pieces of touch state if the injector had permission.
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002711 if (switchedDevice) {
2712 if (DEBUG_FOCUS) {
2713 ALOGD("Conflicting pointer actions: Switched to a different device.");
2714 }
2715 *outConflictingPointerActions = true;
2716 }
2717
2718 if (isHoverAction) {
2719 // Started hovering, therefore no longer down.
Siarhei Vishniakou3ad385b2022-11-04 10:09:53 -07002720 if (oldState && oldState->isDown()) {
Siarhei Vishniakou6e1e9872022-11-08 17:51:35 -08002721 ALOGD_IF(DEBUG_FOCUS,
2722 "Conflicting pointer actions: Hover received while pointer was down.");
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002723 *outConflictingPointerActions = true;
2724 }
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002725 } else if (maskedAction == AMOTION_EVENT_ACTION_UP) {
2726 // Pointer went up.
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002727 tempTouchState.removeTouchingPointer(entry.deviceId, entry.pointerProperties[0].id);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002728 } else if (maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002729 // All pointers up or canceled.
2730 tempTouchState.reset();
2731 } else if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
2732 // First pointer went down.
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002733 if (oldState && (oldState->isDown() || oldState->hasHoveringPointers())) {
2734 ALOGD("Conflicting pointer actions: Down received while already down or hovering.");
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002735 *outConflictingPointerActions = true;
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002736 }
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002737 } else if (maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
2738 // One pointer went up.
Siarhei Vishniakou5b9766d2023-07-18 14:06:29 -07002739 const int32_t pointerIndex = MotionEvent::getActionIndex(action);
2740 const uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
2741 tempTouchState.removeTouchingPointer(entry.deviceId, pointerId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002742 }
2743
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002744 // Save changes unless the action was scroll in which case the temporary touch
2745 // state was only valid for this one action.
2746 if (maskedAction != AMOTION_EVENT_ACTION_SCROLL) {
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07002747 if (displayId >= 0) {
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002748 tempTouchState.clearWindowsWithoutPointers();
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002749 mTouchStatesByDisplay[displayId] = tempTouchState;
2750 } else {
2751 mTouchStatesByDisplay.erase(displayId);
2752 }
2753 }
2754
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -08002755 if (tempTouchState.windows.empty()) {
2756 mTouchStatesByDisplay.erase(displayId);
2757 }
2758
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002759 return targets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002760}
2761
arthurhung6d4bed92021-03-17 11:59:33 +08002762void InputDispatcher::finishDragAndDrop(int32_t displayId, float x, float y) {
Prabir Pradhand65552b2021-10-07 11:23:50 -07002763 // Prevent stylus interceptor windows from affecting drag and drop behavior for now, until we
2764 // have an explicit reason to support it.
2765 constexpr bool isStylus = false;
2766
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07002767 sp<WindowInfoHandle> dropWindow =
Harry Cutts33476232023-01-30 19:57:29 +00002768 findTouchedWindowAtLocked(displayId, x, y, isStylus, /*ignoreDragWindow=*/true);
arthurhung6d4bed92021-03-17 11:59:33 +08002769 if (dropWindow) {
2770 vec2 local = dropWindow->getInfo()->transform.transform(x, y);
Prabir Pradhancef936d2021-07-21 16:17:52 +00002771 sendDropWindowCommandLocked(dropWindow->getToken(), local.x, local.y);
Arthur Hung6d0571e2021-04-09 20:18:16 +08002772 } else {
Arthur Hung54745652022-04-20 07:17:41 +00002773 ALOGW("No window found when drop.");
Prabir Pradhancef936d2021-07-21 16:17:52 +00002774 sendDropWindowCommandLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08002775 }
2776 mDragState.reset();
2777}
2778
2779void InputDispatcher::addDragEventLocked(const MotionEntry& entry) {
Arthur Hung3915c1f2022-05-31 07:17:17 +00002780 if (!mDragState || mDragState->dragWindow->getInfo()->displayId != entry.displayId) {
arthurhungb89ccb02020-12-30 16:19:01 +08002781 return;
2782 }
2783
arthurhung6d4bed92021-03-17 11:59:33 +08002784 if (!mDragState->isStartDrag) {
2785 mDragState->isStartDrag = true;
2786 mDragState->isStylusButtonDownAtStart =
2787 (entry.buttonState & AMOTION_EVENT_BUTTON_STYLUS_PRIMARY) != 0;
2788 }
2789
Arthur Hung54745652022-04-20 07:17:41 +00002790 // Find the pointer index by id.
2791 int32_t pointerIndex = 0;
2792 for (; static_cast<uint32_t>(pointerIndex) < entry.pointerCount; pointerIndex++) {
2793 const PointerProperties& pointerProperties = entry.pointerProperties[pointerIndex];
2794 if (pointerProperties.id == mDragState->pointerId) {
2795 break;
arthurhung6d4bed92021-03-17 11:59:33 +08002796 }
Arthur Hung54745652022-04-20 07:17:41 +00002797 }
arthurhung6d4bed92021-03-17 11:59:33 +08002798
Arthur Hung54745652022-04-20 07:17:41 +00002799 if (uint32_t(pointerIndex) == entry.pointerCount) {
2800 LOG_ALWAYS_FATAL("Should find a valid pointer index by id %d", mDragState->pointerId);
Arthur Hung54745652022-04-20 07:17:41 +00002801 }
2802
2803 const int32_t maskedAction = entry.action & AMOTION_EVENT_ACTION_MASK;
2804 const int32_t x = entry.pointerCoords[pointerIndex].getX();
2805 const int32_t y = entry.pointerCoords[pointerIndex].getY();
2806
2807 switch (maskedAction) {
2808 case AMOTION_EVENT_ACTION_MOVE: {
2809 // Handle the special case : stylus button no longer pressed.
2810 bool isStylusButtonDown =
2811 (entry.buttonState & AMOTION_EVENT_BUTTON_STYLUS_PRIMARY) != 0;
2812 if (mDragState->isStylusButtonDownAtStart && !isStylusButtonDown) {
2813 finishDragAndDrop(entry.displayId, x, y);
2814 return;
2815 }
2816
2817 // Prevent stylus interceptor windows from affecting drag and drop behavior for now,
2818 // until we have an explicit reason to support it.
2819 constexpr bool isStylus = false;
2820
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07002821 sp<WindowInfoHandle> hoverWindowHandle =
2822 findTouchedWindowAtLocked(entry.displayId, x, y, isStylus,
2823 /*ignoreDragWindow=*/true);
Arthur Hung54745652022-04-20 07:17:41 +00002824 // enqueue drag exit if needed.
2825 if (hoverWindowHandle != mDragState->dragHoverWindowHandle &&
2826 !haveSameToken(hoverWindowHandle, mDragState->dragHoverWindowHandle)) {
2827 if (mDragState->dragHoverWindowHandle != nullptr) {
Harry Cutts33476232023-01-30 19:57:29 +00002828 enqueueDragEventLocked(mDragState->dragHoverWindowHandle, /*isExiting=*/true, x,
Arthur Hung54745652022-04-20 07:17:41 +00002829 y);
2830 }
2831 mDragState->dragHoverWindowHandle = hoverWindowHandle;
2832 }
2833 // enqueue drag location if needed.
2834 if (hoverWindowHandle != nullptr) {
Harry Cutts33476232023-01-30 19:57:29 +00002835 enqueueDragEventLocked(hoverWindowHandle, /*isExiting=*/false, x, y);
Arthur Hung54745652022-04-20 07:17:41 +00002836 }
2837 break;
2838 }
2839
2840 case AMOTION_EVENT_ACTION_POINTER_UP:
Siarhei Vishniakou5b9766d2023-07-18 14:06:29 -07002841 if (MotionEvent::getActionIndex(entry.action) != pointerIndex) {
Arthur Hung54745652022-04-20 07:17:41 +00002842 break;
2843 }
2844 // The drag pointer is up.
2845 [[fallthrough]];
2846 case AMOTION_EVENT_ACTION_UP:
2847 finishDragAndDrop(entry.displayId, x, y);
2848 break;
2849 case AMOTION_EVENT_ACTION_CANCEL: {
2850 ALOGD("Receiving cancel when drag and drop.");
2851 sendDropWindowCommandLocked(nullptr, 0, 0);
2852 mDragState.reset();
2853 break;
2854 }
arthurhungb89ccb02020-12-30 16:19:01 +08002855 }
2856}
2857
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002858std::optional<InputTarget> InputDispatcher::createInputTargetLocked(
2859 const sp<android::gui::WindowInfoHandle>& windowHandle,
2860 ftl::Flags<InputTarget::Flags> targetFlags,
2861 std::optional<nsecs_t> firstDownTimeInTarget) const {
2862 std::shared_ptr<InputChannel> inputChannel = getInputChannelLocked(windowHandle->getToken());
2863 if (inputChannel == nullptr) {
2864 ALOGW("Not creating InputTarget for %s, no input channel", windowHandle->getName().c_str());
2865 return {};
2866 }
2867 InputTarget inputTarget;
2868 inputTarget.inputChannel = inputChannel;
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00002869 inputTarget.windowHandle = windowHandle;
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002870 inputTarget.flags = targetFlags;
2871 inputTarget.globalScaleFactor = windowHandle->getInfo()->globalScaleFactor;
2872 inputTarget.firstDownTimeInTarget = firstDownTimeInTarget;
2873 const auto& displayInfoIt = mDisplayInfos.find(windowHandle->getInfo()->displayId);
2874 if (displayInfoIt != mDisplayInfos.end()) {
2875 inputTarget.displayTransform = displayInfoIt->second.transform;
2876 } else {
Siarhei Vishniakou580fb3a2023-05-05 15:02:20 -07002877 // DisplayInfo not found for this window on display windowHandle->getInfo()->displayId.
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002878 // TODO(b/198444055): Make this an error message after 'setInputWindows' API is removed.
2879 }
2880 return inputTarget;
2881}
2882
chaviw98318de2021-05-19 16:45:23 -05002883void InputDispatcher::addWindowTargetLocked(const sp<WindowInfoHandle>& windowHandle,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002884 ftl::Flags<InputTarget::Flags> targetFlags,
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08002885 std::bitset<MAX_POINTER_ID + 1> pointerIds,
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002886 std::optional<nsecs_t> firstDownTimeInTarget,
Siarhei Vishniakouf75cddb2022-10-25 10:42:16 -07002887 std::vector<InputTarget>& inputTargets) const {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002888 std::vector<InputTarget>::iterator it =
2889 std::find_if(inputTargets.begin(), inputTargets.end(),
2890 [&windowHandle](const InputTarget& inputTarget) {
2891 return inputTarget.inputChannel->getConnectionToken() ==
2892 windowHandle->getToken();
2893 });
Chavi Weingarten97b8eec2020-01-09 18:09:08 +00002894
chaviw98318de2021-05-19 16:45:23 -05002895 const WindowInfo* windowInfo = windowHandle->getInfo();
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002896
2897 if (it == inputTargets.end()) {
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002898 std::optional<InputTarget> target =
2899 createInputTargetLocked(windowHandle, targetFlags, firstDownTimeInTarget);
2900 if (!target) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002901 return;
2902 }
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002903 inputTargets.push_back(*target);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002904 it = inputTargets.end() - 1;
2905 }
2906
2907 ALOG_ASSERT(it->flags == targetFlags);
2908 ALOG_ASSERT(it->globalScaleFactor == windowInfo->globalScaleFactor);
2909
chaviw1ff3d1e2020-07-01 15:53:47 -07002910 it->addPointers(pointerIds, windowInfo->transform);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002911}
2912
Michael Wright3dd60e22019-03-27 22:06:44 +00002913void InputDispatcher::addGlobalMonitoringTargetsLocked(std::vector<InputTarget>& inputTargets,
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002914 int32_t displayId) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002915 auto monitorsIt = mGlobalMonitorsByDisplay.find(displayId);
2916 if (monitorsIt == mGlobalMonitorsByDisplay.end()) return;
Michael Wright3dd60e22019-03-27 22:06:44 +00002917
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002918 for (const Monitor& monitor : selectResponsiveMonitorsLocked(monitorsIt->second)) {
2919 InputTarget target;
2920 target.inputChannel = monitor.inputChannel;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002921 target.flags = InputTarget::Flags::DISPATCH_AS_IS;
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002922 // target.firstDownTimeInTarget is not set for global monitors. It is only required in split
2923 // touch and global monitoring works as intended even without setting firstDownTimeInTarget
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002924 if (const auto& it = mDisplayInfos.find(displayId); it != mDisplayInfos.end()) {
2925 target.displayTransform = it->second.transform;
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002926 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002927 target.setDefaultPointerTransform(target.displayTransform);
2928 inputTargets.push_back(target);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002929 }
2930}
2931
Robert Carrc9bf1d32020-04-13 17:21:08 -07002932/**
2933 * Indicate whether one window handle should be considered as obscuring
2934 * another window handle. We only check a few preconditions. Actually
2935 * checking the bounds is left to the caller.
2936 */
chaviw98318de2021-05-19 16:45:23 -05002937static bool canBeObscuredBy(const sp<WindowInfoHandle>& windowHandle,
2938 const sp<WindowInfoHandle>& otherHandle) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002939 // Compare by token so cloned layers aren't counted
2940 if (haveSameToken(windowHandle, otherHandle)) {
2941 return false;
2942 }
2943 auto info = windowHandle->getInfo();
2944 auto otherInfo = otherHandle->getInfo();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002945 if (otherInfo->inputConfig.test(WindowInfo::InputConfig::NOT_VISIBLE)) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002946 return false;
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002947 } else if (otherInfo->alpha == 0 &&
2948 otherInfo->inputConfig.test(WindowInfo::InputConfig::NOT_TOUCHABLE)) {
Bernardo Rufino653d2e02020-10-20 17:32:40 +00002949 // Those act as if they were invisible, so we don't need to flag them.
2950 // We do want to potentially flag touchable windows even if they have 0
2951 // opacity, since they can consume touches and alter the effects of the
2952 // user interaction (eg. apps that rely on
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002953 // Flags::WINDOW_IS_PARTIALLY_OBSCURED should still be told about those
Bernardo Rufino653d2e02020-10-20 17:32:40 +00002954 // windows), hence we also check for FLAG_NOT_TOUCHABLE.
2955 return false;
Bernardo Rufino8007daf2020-09-22 09:40:01 +00002956 } else if (info->ownerUid == otherInfo->ownerUid) {
2957 // If ownerUid is the same we don't generate occlusion events as there
2958 // is no security boundary within an uid.
Robert Carrc9bf1d32020-04-13 17:21:08 -07002959 return false;
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002960 } else if (otherInfo->inputConfig.test(gui::WindowInfo::InputConfig::TRUSTED_OVERLAY)) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002961 return false;
2962 } else if (otherInfo->displayId != info->displayId) {
2963 return false;
2964 }
2965 return true;
2966}
2967
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002968/**
2969 * Returns touch occlusion information in the form of TouchOcclusionInfo. To check if the touch is
2970 * untrusted, one should check:
2971 *
2972 * 1. If result.hasBlockingOcclusion is true.
2973 * If it's, it means the touch should be blocked due to a window with occlusion mode of
2974 * BLOCK_UNTRUSTED.
2975 *
2976 * 2. If result.obscuringOpacity > mMaximumObscuringOpacityForTouch.
2977 * If it is (and 1 is false), then the touch should be blocked because a stack of windows
2978 * (possibly only one) with occlusion mode of USE_OPACITY from one UID resulted in a composed
2979 * obscuring opacity above the threshold. Note that if there was no window of occlusion mode
2980 * USE_OPACITY, result.obscuringOpacity would've been 0 and since
2981 * mMaximumObscuringOpacityForTouch >= 0, the condition above would never be true.
2982 *
2983 * If neither of those is true, then it means the touch can be allowed.
2984 */
2985InputDispatcher::TouchOcclusionInfo InputDispatcher::computeTouchOcclusionInfoLocked(
chaviw98318de2021-05-19 16:45:23 -05002986 const sp<WindowInfoHandle>& windowHandle, int32_t x, int32_t y) const {
2987 const WindowInfo* windowInfo = windowHandle->getInfo();
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002988 int32_t displayId = windowInfo->displayId;
chaviw98318de2021-05-19 16:45:23 -05002989 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002990 TouchOcclusionInfo info;
2991 info.hasBlockingOcclusion = false;
2992 info.obscuringOpacity = 0;
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00002993 info.obscuringUid = gui::Uid::INVALID;
2994 std::map<gui::Uid, float> opacityByUid;
chaviw98318de2021-05-19 16:45:23 -05002995 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002996 if (windowHandle == otherHandle) {
2997 break; // All future windows are below us. Exit early.
2998 }
chaviw98318de2021-05-19 16:45:23 -05002999 const WindowInfo* otherInfo = otherHandle->getInfo();
Bernardo Rufino1ff9d592021-01-18 16:58:57 +00003000 if (canBeObscuredBy(windowHandle, otherHandle) && otherInfo->frameContainsPoint(x, y) &&
3001 !haveSameApplicationToken(windowInfo, otherInfo)) {
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00003002 if (DEBUG_TOUCH_OCCLUSION) {
3003 info.debugInfo.push_back(
Harry Cutts101ee9b2023-07-06 18:04:14 +00003004 dumpWindowForTouchOcclusion(otherInfo, /*isTouchedWindow=*/false));
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00003005 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003006 // canBeObscuredBy() has returned true above, which means this window is untrusted, so
3007 // we perform the checks below to see if the touch can be propagated or not based on the
3008 // window's touch occlusion mode
3009 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::BLOCK_UNTRUSTED) {
3010 info.hasBlockingOcclusion = true;
3011 info.obscuringUid = otherInfo->ownerUid;
3012 info.obscuringPackage = otherInfo->packageName;
3013 break;
3014 }
3015 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::USE_OPACITY) {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003016 const auto uid = otherInfo->ownerUid;
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003017 float opacity =
3018 (opacityByUid.find(uid) == opacityByUid.end()) ? 0 : opacityByUid[uid];
3019 // Given windows A and B:
3020 // opacity(A, B) = 1 - [1 - opacity(A)] * [1 - opacity(B)]
3021 opacity = 1 - (1 - opacity) * (1 - otherInfo->alpha);
3022 opacityByUid[uid] = opacity;
3023 if (opacity > info.obscuringOpacity) {
3024 info.obscuringOpacity = opacity;
3025 info.obscuringUid = uid;
3026 info.obscuringPackage = otherInfo->packageName;
3027 }
3028 }
3029 }
3030 }
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00003031 if (DEBUG_TOUCH_OCCLUSION) {
Harry Cutts101ee9b2023-07-06 18:04:14 +00003032 info.debugInfo.push_back(dumpWindowForTouchOcclusion(windowInfo, /*isTouchedWindow=*/true));
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00003033 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003034 return info;
3035}
3036
chaviw98318de2021-05-19 16:45:23 -05003037std::string InputDispatcher::dumpWindowForTouchOcclusion(const WindowInfo* info,
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00003038 bool isTouchedWindow) const {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003039 return StringPrintf(INDENT2 "* %spackage=%s/%s, id=%" PRId32 ", mode=%s, alpha=%.2f, "
Prabir Pradhan51e7db02022-02-07 06:02:57 -08003040 "frame=[%" PRId32 ",%" PRId32 "][%" PRId32 ",%" PRId32
3041 "], touchableRegion=%s, window={%s}, inputConfig={%s}, "
3042 "hasToken=%s, applicationInfo.name=%s, applicationInfo.token=%s\n",
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08003043 isTouchedWindow ? "[TOUCHED] " : "", info->packageName.c_str(),
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003044 info->ownerUid.toString().c_str(), info->id,
Chavi Weingarten7f019192023-08-08 20:39:01 +00003045 toString(info->touchOcclusionMode).c_str(), info->alpha, info->frame.left,
3046 info->frame.top, info->frame.right, info->frame.bottom,
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003047 dumpRegion(info->touchableRegion).c_str(), info->name.c_str(),
3048 info->inputConfig.string().c_str(), toString(info->token != nullptr),
3049 info->applicationInfo.name.c_str(),
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07003050 binderToString(info->applicationInfo.token).c_str());
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00003051}
3052
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003053bool InputDispatcher::isTouchTrustedLocked(const TouchOcclusionInfo& occlusionInfo) const {
3054 if (occlusionInfo.hasBlockingOcclusion) {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003055 ALOGW("Untrusted touch due to occlusion by %s/%s", occlusionInfo.obscuringPackage.c_str(),
3056 occlusionInfo.obscuringUid.toString().c_str());
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003057 return false;
3058 }
3059 if (occlusionInfo.obscuringOpacity > mMaximumObscuringOpacityForTouch) {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003060 ALOGW("Untrusted touch due to occlusion by %s/%s (obscuring opacity = "
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003061 "%.2f, maximum allowed = %.2f)",
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003062 occlusionInfo.obscuringPackage.c_str(), occlusionInfo.obscuringUid.toString().c_str(),
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003063 occlusionInfo.obscuringOpacity, mMaximumObscuringOpacityForTouch);
3064 return false;
3065 }
3066 return true;
3067}
3068
chaviw98318de2021-05-19 16:45:23 -05003069bool InputDispatcher::isWindowObscuredAtPointLocked(const sp<WindowInfoHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003070 int32_t x, int32_t y) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003071 int32_t displayId = windowHandle->getInfo()->displayId;
chaviw98318de2021-05-19 16:45:23 -05003072 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
3073 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07003074 if (windowHandle == otherHandle) {
3075 break; // All future windows are below us. Exit early.
Michael Wrightd02c5b62014-02-10 15:10:22 -08003076 }
chaviw98318de2021-05-19 16:45:23 -05003077 const WindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07003078 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08003079 otherInfo->frameContainsPoint(x, y)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003080 return true;
3081 }
3082 }
3083 return false;
3084}
3085
chaviw98318de2021-05-19 16:45:23 -05003086bool InputDispatcher::isWindowObscuredLocked(const sp<WindowInfoHandle>& windowHandle) const {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07003087 int32_t displayId = windowHandle->getInfo()->displayId;
chaviw98318de2021-05-19 16:45:23 -05003088 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
3089 const WindowInfo* windowInfo = windowHandle->getInfo();
3090 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07003091 if (windowHandle == otherHandle) {
3092 break; // All future windows are below us. Exit early.
Michael Wrightcdcd8f22016-03-22 16:52:13 -07003093 }
chaviw98318de2021-05-19 16:45:23 -05003094 const WindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07003095 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08003096 otherInfo->overlaps(windowInfo)) {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07003097 return true;
3098 }
3099 }
3100 return false;
3101}
3102
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08003103std::string InputDispatcher::getApplicationWindowLabel(
chaviw98318de2021-05-19 16:45:23 -05003104 const InputApplicationHandle* applicationHandle, const sp<WindowInfoHandle>& windowHandle) {
Yi Kong9b14ac62018-07-17 13:48:38 -07003105 if (applicationHandle != nullptr) {
3106 if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07003107 return applicationHandle->getName() + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003108 } else {
3109 return applicationHandle->getName();
3110 }
Yi Kong9b14ac62018-07-17 13:48:38 -07003111 } else if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07003112 return windowHandle->getInfo()->applicationInfo.name + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003113 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003114 return "<unknown application or window>";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003115 }
3116}
3117
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003118void InputDispatcher::pokeUserActivityLocked(const EventEntry& eventEntry) {
Antonio Kantekf16f2832021-09-28 04:39:20 +00003119 if (!isUserActivityEvent(eventEntry)) {
3120 // Not poking user activity if the event type does not represent a user activity
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003121 return;
3122 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003123 int32_t displayId = getTargetDisplayId(eventEntry);
chaviw98318de2021-05-19 16:45:23 -05003124 sp<WindowInfoHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Josep del Riob3981622023-04-18 15:49:45 +00003125 const WindowInfo* windowDisablingUserActivityInfo = nullptr;
Tiger Huang721e26f2018-07-24 22:26:19 +08003126 if (focusedWindowHandle != nullptr) {
chaviw98318de2021-05-19 16:45:23 -05003127 const WindowInfo* info = focusedWindowHandle->getInfo();
Prabir Pradhan51e7db02022-02-07 06:02:57 -08003128 if (info->inputConfig.test(WindowInfo::InputConfig::DISABLE_USER_ACTIVITY)) {
Josep del Riob3981622023-04-18 15:49:45 +00003129 windowDisablingUserActivityInfo = info;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003130 }
3131 }
3132
3133 int32_t eventType = USER_ACTIVITY_EVENT_OTHER;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003134 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003135 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003136 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
3137 if (motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003138 return;
3139 }
Josep del Riob3981622023-04-18 15:49:45 +00003140 if (windowDisablingUserActivityInfo != nullptr) {
3141 if (DEBUG_DISPATCH_CYCLE) {
3142 ALOGD("Not poking user activity: disabled by window '%s'.",
3143 windowDisablingUserActivityInfo->name.c_str());
3144 }
3145 return;
3146 }
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003147 if (MotionEvent::isTouchEvent(motionEntry.source, motionEntry.action)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003148 eventType = USER_ACTIVITY_EVENT_TOUCH;
3149 }
3150 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003151 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003152 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003153 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
3154 if (keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003155 return;
3156 }
Josep del Riob3981622023-04-18 15:49:45 +00003157 // If the key code is unknown, we don't consider it user activity
3158 if (keyEntry.keyCode == AKEYCODE_UNKNOWN) {
3159 return;
3160 }
3161 // Don't inhibit events that were intercepted or are not passed to
3162 // the apps, like system shortcuts
3163 if (windowDisablingUserActivityInfo != nullptr &&
3164 keyEntry.interceptKeyResult != KeyEntry::InterceptKeyResult::SKIP &&
3165 keyEntry.policyFlags & POLICY_FLAG_PASS_TO_USER) {
3166 if (DEBUG_DISPATCH_CYCLE) {
3167 ALOGD("Not poking user activity: disabled by window '%s'.",
3168 windowDisablingUserActivityInfo->name.c_str());
3169 }
3170 return;
3171 }
3172
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003173 eventType = USER_ACTIVITY_EVENT_BUTTON;
3174 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003175 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00003176 default: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003177 LOG_ALWAYS_FATAL("%s events are not user activity",
Dominik Laskowski75788452021-02-09 18:51:25 -08003178 ftl::enum_string(eventEntry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003179 break;
3180 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003181 }
3182
Prabir Pradhancef936d2021-07-21 16:17:52 +00003183 auto command = [this, eventTime = eventEntry.eventTime, eventType, displayId]()
3184 REQUIRES(mLock) {
3185 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00003186 mPolicy.pokeUserActivity(eventTime, eventType, displayId);
Prabir Pradhancef936d2021-07-21 16:17:52 +00003187 };
3188 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003189}
3190
3191void InputDispatcher::prepareDispatchCycleLocked(nsecs_t currentTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003192 const std::shared_ptr<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003193 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003194 const InputTarget& inputTarget) {
Prabir Pradhan2dac8b82023-09-06 01:11:51 +00003195 ATRACE_NAME_IF(ATRACE_ENABLED(),
3196 StringPrintf("prepareDispatchCycleLocked(inputChannel=%s, id=0x%" PRIx32 ")",
3197 connection->getInputChannelName().c_str(), eventEntry->id));
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003198 if (DEBUG_DISPATCH_CYCLE) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003199 ALOGD("channel '%s' ~ prepareDispatchCycle - flags=%s, "
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08003200 "globalScaleFactor=%f, pointerIds=%s %s",
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003201 connection->getInputChannelName().c_str(), inputTarget.flags.string().c_str(),
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08003202 inputTarget.globalScaleFactor, bitsetToString(inputTarget.pointerIds).c_str(),
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003203 inputTarget.getPointerInfoString().c_str());
3204 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003205
3206 // Skip this event if the connection status is not normal.
3207 // We don't want to enqueue additional outbound events if the connection is broken.
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003208 if (connection->status != Connection::Status::NORMAL) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003209 if (DEBUG_DISPATCH_CYCLE) {
3210 ALOGD("channel '%s' ~ Dropping event because the channel status is %s",
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003211 connection->getInputChannelName().c_str(),
3212 ftl::enum_string(connection->status).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003213 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003214 return;
3215 }
3216
3217 // Split a motion event if needed.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003218 if (inputTarget.flags.test(InputTarget::Flags::SPLIT)) {
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003219 LOG_ALWAYS_FATAL_IF(eventEntry->type != EventEntry::Type::MOTION,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003220 "Entry type %s should not have Flags::SPLIT",
Dominik Laskowski75788452021-02-09 18:51:25 -08003221 ftl::enum_string(eventEntry->type).c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003222
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003223 const MotionEntry& originalMotionEntry = static_cast<const MotionEntry&>(*eventEntry);
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003224 if (inputTarget.pointerIds.count() != originalMotionEntry.pointerCount) {
Siarhei Vishniakou16e4fa02023-02-16 17:48:56 -08003225 if (!inputTarget.firstDownTimeInTarget.has_value()) {
3226 logDispatchStateLocked();
3227 LOG(FATAL) << "Splitting motion events requires a down time to be set for the "
3228 "target on connection "
3229 << connection->getInputChannelName() << " for "
3230 << originalMotionEntry.getDescription();
3231 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003232 std::unique_ptr<MotionEntry> splitMotionEntry =
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00003233 splitMotionEvent(originalMotionEntry, inputTarget.pointerIds,
3234 inputTarget.firstDownTimeInTarget.value());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003235 if (!splitMotionEntry) {
3236 return; // split event was dropped
3237 }
Arthur Hungb3307ee2021-10-14 10:57:37 +00003238 if (splitMotionEntry->action == AMOTION_EVENT_ACTION_CANCEL) {
3239 std::string reason = std::string("reason=pointer cancel on split window");
3240 android_log_event_list(LOGTAG_INPUT_CANCEL)
3241 << connection->getInputChannelName().c_str() << reason << LOG_ID_EVENTS;
3242 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003243 if (DEBUG_FOCUS) {
3244 ALOGD("channel '%s' ~ Split motion event.",
3245 connection->getInputChannelName().c_str());
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003246 logOutboundMotionDetails(" ", *splitMotionEntry);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003247 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003248 enqueueDispatchEntriesLocked(currentTime, connection, std::move(splitMotionEntry),
3249 inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003250 return;
3251 }
3252 }
3253
3254 // Not splitting. Enqueue dispatch entries for the event as is.
3255 enqueueDispatchEntriesLocked(currentTime, connection, eventEntry, inputTarget);
3256}
3257
3258void InputDispatcher::enqueueDispatchEntriesLocked(nsecs_t currentTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003259 const std::shared_ptr<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003260 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003261 const InputTarget& inputTarget) {
Prabir Pradhan2dac8b82023-09-06 01:11:51 +00003262 ATRACE_NAME_IF(ATRACE_ENABLED(),
3263 StringPrintf("enqueueDispatchEntriesLocked(inputChannel=%s, id=0x%" PRIx32 ")",
3264 connection->getInputChannelName().c_str(), eventEntry->id));
Siarhei Vishniakou5cee1e32022-11-29 12:35:39 -08003265 LOG_ALWAYS_FATAL_IF(!inputTarget.flags.any(InputTarget::DISPATCH_MASK),
3266 "No dispatch flags are set for %s", eventEntry->getDescription().c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00003267
hongzuo liu95785e22022-09-06 02:51:35 +00003268 const bool wasEmpty = connection->outboundQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003269
3270 // Enqueue dispatch entries for the requested modes.
chaviw8c9cf542019-03-25 13:02:48 -07003271 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003272 InputTarget::Flags::DISPATCH_AS_HOVER_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07003273 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003274 InputTarget::Flags::DISPATCH_AS_OUTSIDE);
chaviw8c9cf542019-03-25 13:02:48 -07003275 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003276 InputTarget::Flags::DISPATCH_AS_HOVER_ENTER);
chaviw8c9cf542019-03-25 13:02:48 -07003277 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003278 InputTarget::Flags::DISPATCH_AS_IS);
chaviw8c9cf542019-03-25 13:02:48 -07003279 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003280 InputTarget::Flags::DISPATCH_AS_SLIPPERY_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07003281 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003282 InputTarget::Flags::DISPATCH_AS_SLIPPERY_ENTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003283
3284 // If the outbound queue was previously empty, start the dispatch cycle going.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003285 if (wasEmpty && !connection->outboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003286 startDispatchCycleLocked(currentTime, connection);
3287 }
3288}
3289
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003290void InputDispatcher::enqueueDispatchEntryLocked(const std::shared_ptr<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003291 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003292 const InputTarget& inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003293 ftl::Flags<InputTarget::Flags> dispatchMode) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003294 ftl::Flags<InputTarget::Flags> inputTargetFlags = inputTarget.flags;
3295 if (!inputTargetFlags.any(dispatchMode)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003296 return;
3297 }
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003298
3299 inputTargetFlags.clear(InputTarget::DISPATCH_MASK);
3300 inputTargetFlags |= dispatchMode;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003301
3302 // This is a new event.
3303 // Enqueue a new dispatch entry onto the outbound queue for this connection.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003304 std::unique_ptr<DispatchEntry> dispatchEntry =
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003305 createDispatchEntry(inputTarget, eventEntry, inputTargetFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003306
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003307 // Use the eventEntry from dispatchEntry since the entry may have changed and can now be a
3308 // different EventEntry than what was passed in.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003309 EventEntry& newEntry = *(dispatchEntry->eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003310 // Apply target flags and update the connection's input state.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003311 switch (newEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003312 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003313 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(newEntry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003314 if (!connection->inputState.trackKey(keyEntry, dispatchEntry->resolvedAction,
3315 dispatchEntry->resolvedFlags)) {
Siarhei Vishniakouc94dafe2023-05-26 10:24:19 -07003316 LOG(WARNING) << "channel " << connection->getInputChannelName()
3317 << "~ dropping inconsistent event: " << *dispatchEntry;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003318 return; // skip the inconsistent event
3319 }
3320 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003321 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003322
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003323 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003324 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003325 // Assign a default value to dispatchEntry that will never be generated by InputReader,
3326 // and assign a InputDispatcher value if it doesn't change in the if-else chain below.
3327 constexpr int32_t DEFAULT_RESOLVED_EVENT_ID =
3328 static_cast<int32_t>(IdGenerator::Source::OTHER);
3329 dispatchEntry->resolvedEventId = DEFAULT_RESOLVED_EVENT_ID;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003330 if (dispatchMode.test(InputTarget::Flags::DISPATCH_AS_OUTSIDE)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003331 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_OUTSIDE;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003332 } else if (dispatchMode.test(InputTarget::Flags::DISPATCH_AS_HOVER_EXIT)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003333 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_EXIT;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003334 } else if (dispatchMode.test(InputTarget::Flags::DISPATCH_AS_HOVER_ENTER)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003335 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003336 } else if (dispatchMode.test(InputTarget::Flags::DISPATCH_AS_SLIPPERY_EXIT)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003337 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_CANCEL;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003338 } else if (dispatchMode.test(InputTarget::Flags::DISPATCH_AS_SLIPPERY_ENTER)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003339 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_DOWN;
3340 } else {
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003341 dispatchEntry->resolvedEventId = motionEntry.id;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003342 }
3343 if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_HOVER_MOVE &&
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003344 !connection->inputState.isHovering(motionEntry.deviceId, motionEntry.source,
3345 motionEntry.displayId)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003346 if (DEBUG_DISPATCH_CYCLE) {
3347 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: filling in missing hover "
3348 "enter event",
3349 connection->getInputChannelName().c_str());
3350 }
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00003351 // We keep the 'resolvedEventId' here equal to the original 'motionEntry.id' because
3352 // this is a one-to-one event conversion.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003353 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
3354 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003355
Siarhei Vishniakou1ae72f12023-01-29 12:55:30 -08003356 if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_CANCEL) {
3357 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_CANCELED;
3358 }
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003359 if (dispatchEntry->targetFlags.test(InputTarget::Flags::WINDOW_IS_OBSCURED)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003360 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED;
3361 }
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003362 if (dispatchEntry->targetFlags.test(InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003363 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
3364 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003365
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003366 if (!connection->inputState.trackMotion(motionEntry, dispatchEntry->resolvedAction,
3367 dispatchEntry->resolvedFlags)) {
Siarhei Vishniakouc94dafe2023-05-26 10:24:19 -07003368 LOG(WARNING) << "channel " << connection->getInputChannelName()
3369 << "~ dropping inconsistent event: " << *dispatchEntry;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003370 return; // skip the inconsistent event
3371 }
3372
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003373 dispatchEntry->resolvedEventId =
3374 dispatchEntry->resolvedEventId == DEFAULT_RESOLVED_EVENT_ID
3375 ? mIdGenerator.nextId()
3376 : motionEntry.id;
3377 if (ATRACE_ENABLED() && dispatchEntry->resolvedEventId != motionEntry.id) {
3378 std::string message = StringPrintf("Transmute MotionEvent(id=0x%" PRIx32
3379 ") to MotionEvent(id=0x%" PRIx32 ").",
3380 motionEntry.id, dispatchEntry->resolvedEventId);
3381 ATRACE_NAME(message.c_str());
3382 }
3383
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08003384 if ((motionEntry.flags & AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE) &&
3385 (motionEntry.policyFlags & POLICY_FLAG_TRUSTED)) {
3386 // Skip reporting pointer down outside focus to the policy.
3387 break;
3388 }
3389
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003390 dispatchPointerDownOutsideFocus(motionEntry.source, dispatchEntry->resolvedAction,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003391 inputTarget.inputChannel->getConnectionToken());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003392
3393 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003394 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003395 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003396 case EventEntry::Type::TOUCH_MODE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08003397 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
3398 case EventEntry::Type::DRAG: {
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003399 break;
3400 }
Chris Yef59a2f42020-10-16 12:55:26 -07003401 case EventEntry::Type::SENSOR: {
3402 LOG_ALWAYS_FATAL("SENSOR events should not go to apps via input channel");
3403 break;
3404 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003405 case EventEntry::Type::CONFIGURATION_CHANGED:
3406 case EventEntry::Type::DEVICE_RESET: {
3407 LOG_ALWAYS_FATAL("%s events should not go to apps",
Dominik Laskowski75788452021-02-09 18:51:25 -08003408 ftl::enum_string(newEntry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003409 break;
3410 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003411 }
3412
3413 // Remember that we are waiting for this dispatch to complete.
3414 if (dispatchEntry->hasForegroundTarget()) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003415 incrementPendingForegroundDispatches(newEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003416 }
3417
3418 // Enqueue the dispatch entry.
Prabir Pradhan8c90d782023-09-15 21:16:44 +00003419 connection->outboundQueue.emplace_back(std::move(dispatchEntry));
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003420 traceOutboundQueueLength(*connection);
chaviw8c9cf542019-03-25 13:02:48 -07003421}
3422
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003423/**
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003424 * This function is for debugging and metrics collection. It has two roles.
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003425 *
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003426 * The first role is to log input interaction with windows, which helps determine what the user was
3427 * interacting with. For example, if user is touching launcher, we will see an input_interaction log
3428 * that user started interacting with launcher window, as well as any other window that received
3429 * that gesture, such as the wallpaper or other spy windows. A new input_interaction is only logged
3430 * when the set of tokens that received the event changes. It is not logged again as long as the
3431 * user is interacting with the same windows.
3432 *
3433 * The second role is to track input device activity for metrics collection. For each input event,
3434 * we report the set of UIDs that the input device interacted with to the policy. Unlike for the
3435 * input_interaction logs, the device interaction is reported even when the set of interaction
3436 * tokens do not change.
3437 *
3438 * For these purposes, we do not count ACTION_OUTSIDE, ACTION_UP and ACTION_CANCEL actions as
3439 * interaction. This includes up and cancel events for both keys and motions.
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003440 */
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003441void InputDispatcher::processInteractionsLocked(const EventEntry& entry,
3442 const std::vector<InputTarget>& targets) {
3443 int32_t deviceId;
3444 nsecs_t eventTime;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003445 // Skip ACTION_UP events, and all events other than keys and motions
3446 if (entry.type == EventEntry::Type::KEY) {
3447 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
3448 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
3449 return;
3450 }
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003451 deviceId = keyEntry.deviceId;
3452 eventTime = keyEntry.eventTime;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003453 } else if (entry.type == EventEntry::Type::MOTION) {
3454 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
3455 if (motionEntry.action == AMOTION_EVENT_ACTION_UP ||
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003456 motionEntry.action == AMOTION_EVENT_ACTION_CANCEL ||
3457 MotionEvent::getActionMasked(motionEntry.action) == AMOTION_EVENT_ACTION_POINTER_UP) {
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003458 return;
3459 }
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003460 deviceId = motionEntry.deviceId;
3461 eventTime = motionEntry.eventTime;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003462 } else {
3463 return; // Not a key or a motion
3464 }
3465
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003466 std::set<gui::Uid> interactionUids;
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07003467 std::unordered_set<sp<IBinder>, StrongPointerHash<IBinder>> newConnectionTokens;
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003468 std::vector<std::shared_ptr<Connection>> newConnections;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003469 for (const InputTarget& target : targets) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003470 if (target.flags.test(InputTarget::Flags::DISPATCH_AS_OUTSIDE)) {
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003471 continue; // Skip windows that receive ACTION_OUTSIDE
3472 }
3473
3474 sp<IBinder> token = target.inputChannel->getConnectionToken();
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003475 std::shared_ptr<Connection> connection = getConnectionLocked(token);
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003476 if (connection == nullptr) {
3477 continue;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003478 }
3479 newConnectionTokens.insert(std::move(token));
3480 newConnections.emplace_back(connection);
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003481 if (target.windowHandle) {
3482 interactionUids.emplace(target.windowHandle->getInfo()->ownerUid);
3483 }
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003484 }
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003485
3486 auto command = [this, deviceId, eventTime, uids = std::move(interactionUids)]()
3487 REQUIRES(mLock) {
3488 scoped_unlock unlock(mLock);
3489 mPolicy.notifyDeviceInteraction(deviceId, eventTime, uids);
3490 };
3491 postCommandLocked(std::move(command));
3492
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003493 if (newConnectionTokens == mInteractionConnectionTokens) {
3494 return; // no change
3495 }
3496 mInteractionConnectionTokens = newConnectionTokens;
3497
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003498 std::string targetList;
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003499 for (const std::shared_ptr<Connection>& connection : newConnections) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003500 targetList += connection->getWindowName() + ", ";
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003501 }
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003502 std::string message = "Interaction with: " + targetList;
3503 if (targetList.empty()) {
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003504 message += "<none>";
3505 }
3506 android_log_event_list(LOGTAG_INPUT_INTERACTION) << message << LOG_ID_EVENTS;
3507}
3508
chaviwfd6d3512019-03-25 13:23:49 -07003509void InputDispatcher::dispatchPointerDownOutsideFocus(uint32_t source, int32_t action,
Vishnu Nairad321cd2020-08-20 16:40:21 -07003510 const sp<IBinder>& token) {
chaviw8c9cf542019-03-25 13:02:48 -07003511 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
chaviwfd6d3512019-03-25 13:23:49 -07003512 uint32_t maskedSource = source & AINPUT_SOURCE_CLASS_MASK;
3513 if (maskedSource != AINPUT_SOURCE_CLASS_POINTER || maskedAction != AMOTION_EVENT_ACTION_DOWN) {
chaviw8c9cf542019-03-25 13:02:48 -07003514 return;
3515 }
3516
Vishnu Nairc519ff72021-01-21 08:23:08 -08003517 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07003518 if (focusedToken == token) {
3519 // ignore since token is focused
chaviw8c9cf542019-03-25 13:02:48 -07003520 return;
3521 }
3522
Prabir Pradhancef936d2021-07-21 16:17:52 +00003523 auto command = [this, token]() REQUIRES(mLock) {
3524 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00003525 mPolicy.onPointerDownOutsideFocus(token);
Prabir Pradhancef936d2021-07-21 16:17:52 +00003526 };
3527 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003528}
3529
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003530status_t InputDispatcher::publishMotionEvent(Connection& connection,
3531 DispatchEntry& dispatchEntry) const {
3532 const EventEntry& eventEntry = *(dispatchEntry.eventEntry);
3533 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
3534
3535 PointerCoords scaledCoords[MAX_POINTERS];
3536 const PointerCoords* usingCoords = motionEntry.pointerCoords;
3537
3538 // Set the X and Y offset and X and Y scale depending on the input source.
3539 if ((motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) &&
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003540 !(dispatchEntry.targetFlags.test(InputTarget::Flags::ZERO_COORDS))) {
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003541 float globalScaleFactor = dispatchEntry.globalScaleFactor;
3542 if (globalScaleFactor != 1.0f) {
3543 for (uint32_t i = 0; i < motionEntry.pointerCount; i++) {
3544 scaledCoords[i] = motionEntry.pointerCoords[i];
3545 // Don't apply window scale here since we don't want scale to affect raw
3546 // coordinates. The scale will be sent back to the client and applied
3547 // later when requesting relative coordinates.
Harry Cutts33476232023-01-30 19:57:29 +00003548 scaledCoords[i].scale(globalScaleFactor, /*windowXScale=*/1, /*windowYScale=*/1);
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003549 }
3550 usingCoords = scaledCoords;
3551 }
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003552 } else if (dispatchEntry.targetFlags.test(InputTarget::Flags::ZERO_COORDS)) {
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003553 // We don't want the dispatch target to know the coordinates
3554 for (uint32_t i = 0; i < motionEntry.pointerCount; i++) {
3555 scaledCoords[i].clear();
3556 }
3557 usingCoords = scaledCoords;
3558 }
3559
3560 std::array<uint8_t, 32> hmac = getSignature(motionEntry, dispatchEntry);
3561
3562 // Publish the motion event.
3563 return connection.inputPublisher
3564 .publishMotionEvent(dispatchEntry.seq, dispatchEntry.resolvedEventId,
3565 motionEntry.deviceId, motionEntry.source, motionEntry.displayId,
3566 std::move(hmac), dispatchEntry.resolvedAction,
3567 motionEntry.actionButton, dispatchEntry.resolvedFlags,
3568 motionEntry.edgeFlags, motionEntry.metaState,
3569 motionEntry.buttonState, motionEntry.classification,
3570 dispatchEntry.transform, motionEntry.xPrecision,
3571 motionEntry.yPrecision, motionEntry.xCursorPosition,
3572 motionEntry.yCursorPosition, dispatchEntry.rawTransform,
3573 motionEntry.downTime, motionEntry.eventTime,
3574 motionEntry.pointerCount, motionEntry.pointerProperties,
3575 usingCoords);
3576}
3577
Michael Wrightd02c5b62014-02-10 15:10:22 -08003578void InputDispatcher::startDispatchCycleLocked(nsecs_t currentTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003579 const std::shared_ptr<Connection>& connection) {
Prabir Pradhan2dac8b82023-09-06 01:11:51 +00003580 ATRACE_NAME_IF(ATRACE_ENABLED(),
3581 StringPrintf("startDispatchCycleLocked(inputChannel=%s)",
3582 connection->getInputChannelName().c_str()));
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003583 if (DEBUG_DISPATCH_CYCLE) {
3584 ALOGD("channel '%s' ~ startDispatchCycle", connection->getInputChannelName().c_str());
3585 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003586
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003587 while (connection->status == Connection::Status::NORMAL && !connection->outboundQueue.empty()) {
Prabir Pradhan8c90d782023-09-15 21:16:44 +00003588 std::unique_ptr<DispatchEntry>& dispatchEntry = connection->outboundQueue.front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003589 dispatchEntry->deliveryTime = currentTime;
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003590 const std::chrono::nanoseconds timeout = getDispatchingTimeoutLocked(connection);
Siarhei Vishniakou70622952020-07-30 11:17:23 -05003591 dispatchEntry->timeoutTime = currentTime + timeout.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003592
3593 // Publish the event.
3594 status_t status;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003595 const EventEntry& eventEntry = *(dispatchEntry->eventEntry);
3596 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003597 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003598 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
3599 std::array<uint8_t, 32> hmac = getSignature(keyEntry, *dispatchEntry);
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08003600 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07003601 LOG(INFO) << "Publishing " << *dispatchEntry << " to "
3602 << connection->getInputChannelName();
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08003603 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003604
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003605 // Publish the key event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003606 status = connection->inputPublisher
3607 .publishKeyEvent(dispatchEntry->seq,
3608 dispatchEntry->resolvedEventId, keyEntry.deviceId,
3609 keyEntry.source, keyEntry.displayId,
3610 std::move(hmac), dispatchEntry->resolvedAction,
3611 dispatchEntry->resolvedFlags, keyEntry.keyCode,
3612 keyEntry.scanCode, keyEntry.metaState,
3613 keyEntry.repeatCount, keyEntry.downTime,
3614 keyEntry.eventTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003615 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003616 }
3617
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003618 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08003619 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07003620 LOG(INFO) << "Publishing " << *dispatchEntry << " to "
3621 << connection->getInputChannelName();
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08003622 }
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003623 status = publishMotionEvent(*connection, *dispatchEntry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003624 break;
3625 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003626
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003627 case EventEntry::Type::FOCUS: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003628 const FocusEntry& focusEntry = static_cast<const FocusEntry&>(eventEntry);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003629 status = connection->inputPublisher.publishFocusEvent(dispatchEntry->seq,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003630 focusEntry.id,
Antonio Kantek3cfec7b2021-11-05 18:26:17 -07003631 focusEntry.hasFocus);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003632 break;
3633 }
3634
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003635 case EventEntry::Type::TOUCH_MODE_CHANGED: {
3636 const TouchModeEntry& touchModeEntry =
3637 static_cast<const TouchModeEntry&>(eventEntry);
3638 status = connection->inputPublisher
3639 .publishTouchModeEvent(dispatchEntry->seq, touchModeEntry.id,
3640 touchModeEntry.inTouchMode);
3641
3642 break;
3643 }
3644
Prabir Pradhan99987712020-11-10 18:43:05 -08003645 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
3646 const auto& captureEntry =
3647 static_cast<const PointerCaptureChangedEntry&>(eventEntry);
3648 status = connection->inputPublisher
3649 .publishCaptureEvent(dispatchEntry->seq, captureEntry.id,
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00003650 captureEntry.pointerCaptureRequest.enable);
Prabir Pradhan99987712020-11-10 18:43:05 -08003651 break;
3652 }
3653
arthurhungb89ccb02020-12-30 16:19:01 +08003654 case EventEntry::Type::DRAG: {
3655 const DragEntry& dragEntry = static_cast<const DragEntry&>(eventEntry);
3656 status = connection->inputPublisher.publishDragEvent(dispatchEntry->seq,
3657 dragEntry.id, dragEntry.x,
3658 dragEntry.y,
3659 dragEntry.isExiting);
3660 break;
3661 }
3662
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003663 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07003664 case EventEntry::Type::DEVICE_RESET:
3665 case EventEntry::Type::SENSOR: {
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003666 LOG_ALWAYS_FATAL("Should never start dispatch cycles for %s events",
Dominik Laskowski75788452021-02-09 18:51:25 -08003667 ftl::enum_string(eventEntry.type).c_str());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003668 return;
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003669 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003670 }
3671
3672 // Check the result.
3673 if (status) {
3674 if (status == WOULD_BLOCK) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003675 if (connection->waitQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003676 ALOGE("channel '%s' ~ Could not publish event because the pipe is full. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003677 "This is unexpected because the wait queue is empty, so the pipe "
3678 "should be empty and we shouldn't have any problems writing an "
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +00003679 "event to it, status=%s(%d)",
3680 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3681 status);
Harry Cutts33476232023-01-30 19:57:29 +00003682 abortBrokenDispatchCycleLocked(currentTime, connection, /*notify=*/true);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003683 } else {
3684 // Pipe is full and we are waiting for the app to finish process some events
3685 // before sending more events to it.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003686 if (DEBUG_DISPATCH_CYCLE) {
3687 ALOGD("channel '%s' ~ Could not publish event because the pipe is full, "
3688 "waiting for the application to catch up",
3689 connection->getInputChannelName().c_str());
3690 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003691 }
3692 } else {
3693 ALOGE("channel '%s' ~ Could not publish event due to an unexpected error, "
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +00003694 "status=%s(%d)",
3695 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3696 status);
Harry Cutts33476232023-01-30 19:57:29 +00003697 abortBrokenDispatchCycleLocked(currentTime, connection, /*notify=*/true);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003698 }
3699 return;
3700 }
3701
3702 // Re-enqueue the event on the wait queue.
Prabir Pradhan8c90d782023-09-15 21:16:44 +00003703 const nsecs_t timeoutTime = dispatchEntry->timeoutTime;
3704 connection->waitQueue.emplace_back(std::move(dispatchEntry));
3705 connection->outboundQueue.erase(connection->outboundQueue.begin());
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003706 traceOutboundQueueLength(*connection);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003707 if (connection->responsive) {
Prabir Pradhan8c90d782023-09-15 21:16:44 +00003708 mAnrTracker.insert(timeoutTime, connection->inputChannel->getConnectionToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003709 }
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003710 traceWaitQueueLength(*connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003711 }
3712}
3713
chaviw09c8d2d2020-08-24 15:48:26 -07003714std::array<uint8_t, 32> InputDispatcher::sign(const VerifiedInputEvent& event) const {
3715 size_t size;
3716 switch (event.type) {
3717 case VerifiedInputEvent::Type::KEY: {
3718 size = sizeof(VerifiedKeyEvent);
3719 break;
3720 }
3721 case VerifiedInputEvent::Type::MOTION: {
3722 size = sizeof(VerifiedMotionEvent);
3723 break;
3724 }
3725 }
3726 const uint8_t* start = reinterpret_cast<const uint8_t*>(&event);
3727 return mHmacKeyManager.sign(start, size);
3728}
3729
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003730const std::array<uint8_t, 32> InputDispatcher::getSignature(
3731 const MotionEntry& motionEntry, const DispatchEntry& dispatchEntry) const {
Siarhei Vishniakoubf880522023-05-01 11:03:22 -07003732 const int32_t actionMasked = MotionEvent::getActionMasked(dispatchEntry.resolvedAction);
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003733 if (actionMasked != AMOTION_EVENT_ACTION_UP && actionMasked != AMOTION_EVENT_ACTION_DOWN) {
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003734 // Only sign events up and down events as the purely move events
3735 // are tied to their up/down counterparts so signing would be redundant.
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003736 return INVALID_HMAC;
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003737 }
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003738
3739 VerifiedMotionEvent verifiedEvent =
3740 verifiedMotionEventFromMotionEntry(motionEntry, dispatchEntry.rawTransform);
3741 verifiedEvent.actionMasked = actionMasked;
3742 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_MOTION_EVENT_FLAGS;
3743 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003744}
3745
3746const std::array<uint8_t, 32> InputDispatcher::getSignature(
3747 const KeyEntry& keyEntry, const DispatchEntry& dispatchEntry) const {
3748 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEntry(keyEntry);
3749 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_KEY_EVENT_FLAGS;
3750 verifiedEvent.action = dispatchEntry.resolvedAction;
chaviw09c8d2d2020-08-24 15:48:26 -07003751 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003752}
3753
Michael Wrightd02c5b62014-02-10 15:10:22 -08003754void InputDispatcher::finishDispatchCycleLocked(nsecs_t currentTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003755 const std::shared_ptr<Connection>& connection,
3756 uint32_t seq, bool handled, nsecs_t consumeTime) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003757 if (DEBUG_DISPATCH_CYCLE) {
3758 ALOGD("channel '%s' ~ finishDispatchCycle - seq=%u, handled=%s",
3759 connection->getInputChannelName().c_str(), seq, toString(handled));
3760 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003761
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003762 if (connection->status == Connection::Status::BROKEN ||
3763 connection->status == Connection::Status::ZOMBIE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003764 return;
3765 }
3766
3767 // Notify other system components and prepare to start the next dispatch cycle.
Prabir Pradhancef936d2021-07-21 16:17:52 +00003768 auto command = [this, currentTime, connection, seq, handled, consumeTime]() REQUIRES(mLock) {
3769 doDispatchCycleFinishedCommand(currentTime, connection, seq, handled, consumeTime);
3770 };
3771 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003772}
3773
3774void InputDispatcher::abortBrokenDispatchCycleLocked(nsecs_t currentTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003775 const std::shared_ptr<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003776 bool notify) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003777 if (DEBUG_DISPATCH_CYCLE) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07003778 LOG(INFO) << "channel '" << connection->getInputChannelName() << "'~ " << __func__
3779 << " - notify=" << toString(notify);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003780 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003781
3782 // Clear the dispatch queues.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003783 drainDispatchQueue(connection->outboundQueue);
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003784 traceOutboundQueueLength(*connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003785 drainDispatchQueue(connection->waitQueue);
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003786 traceWaitQueueLength(*connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003787
3788 // The connection appears to be unrecoverably broken.
3789 // Ignore already broken or zombie connections.
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003790 if (connection->status == Connection::Status::NORMAL) {
3791 connection->status = Connection::Status::BROKEN;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003792
3793 if (notify) {
3794 // Notify other system components.
Prabir Pradhancef936d2021-07-21 16:17:52 +00003795 ALOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
3796 connection->getInputChannelName().c_str());
3797
3798 auto command = [this, connection]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00003799 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00003800 mPolicy.notifyInputChannelBroken(connection->inputChannel->getConnectionToken());
Prabir Pradhancef936d2021-07-21 16:17:52 +00003801 };
3802 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003803 }
3804 }
3805}
3806
Prabir Pradhan8c90d782023-09-15 21:16:44 +00003807void InputDispatcher::drainDispatchQueue(std::deque<std::unique_ptr<DispatchEntry>>& queue) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003808 while (!queue.empty()) {
Prabir Pradhan8c90d782023-09-15 21:16:44 +00003809 releaseDispatchEntry(std::move(queue.front()));
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003810 queue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003811 }
3812}
3813
Prabir Pradhan8c90d782023-09-15 21:16:44 +00003814void InputDispatcher::releaseDispatchEntry(std::unique_ptr<DispatchEntry> dispatchEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003815 if (dispatchEntry->hasForegroundTarget()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003816 decrementPendingForegroundDispatches(*(dispatchEntry->eventEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003817 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003818}
3819
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003820int InputDispatcher::handleReceiveCallback(int events, sp<IBinder> connectionToken) {
3821 std::scoped_lock _l(mLock);
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003822 std::shared_ptr<Connection> connection = getConnectionLocked(connectionToken);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003823 if (connection == nullptr) {
3824 ALOGW("Received looper callback for unknown input channel token %p. events=0x%x",
3825 connectionToken.get(), events);
3826 return 0; // remove the callback
3827 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003828
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003829 bool notify;
3830 if (!(events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP))) {
3831 if (!(events & ALOOPER_EVENT_INPUT)) {
3832 ALOGW("channel '%s' ~ Received spurious callback for unhandled poll event. "
3833 "events=0x%x",
3834 connection->getInputChannelName().c_str(), events);
3835 return 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003836 }
3837
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003838 nsecs_t currentTime = now();
3839 bool gotOne = false;
3840 status_t status = OK;
3841 for (;;) {
3842 Result<InputPublisher::ConsumerResponse> result =
3843 connection->inputPublisher.receiveConsumerResponse();
3844 if (!result.ok()) {
3845 status = result.error().code();
3846 break;
3847 }
3848
3849 if (std::holds_alternative<InputPublisher::Finished>(*result)) {
3850 const InputPublisher::Finished& finish =
3851 std::get<InputPublisher::Finished>(*result);
3852 finishDispatchCycleLocked(currentTime, connection, finish.seq, finish.handled,
3853 finish.consumeTime);
3854 } else if (std::holds_alternative<InputPublisher::Timeline>(*result)) {
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00003855 if (shouldReportMetricsForConnection(*connection)) {
3856 const InputPublisher::Timeline& timeline =
3857 std::get<InputPublisher::Timeline>(*result);
3858 mLatencyTracker
3859 .trackGraphicsLatency(timeline.inputEventId,
3860 connection->inputChannel->getConnectionToken(),
3861 std::move(timeline.graphicsTimeline));
3862 }
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003863 }
3864 gotOne = true;
3865 }
3866 if (gotOne) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00003867 runCommandsLockedInterruptable();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003868 if (status == WOULD_BLOCK) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003869 return 1;
3870 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003871 }
3872
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003873 notify = status != DEAD_OBJECT || !connection->monitor;
3874 if (notify) {
3875 ALOGE("channel '%s' ~ Failed to receive finished signal. status=%s(%d)",
3876 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3877 status);
3878 }
3879 } else {
3880 // Monitor channels are never explicitly unregistered.
3881 // We do it automatically when the remote endpoint is closed so don't warn about them.
3882 const bool stillHaveWindowHandle =
3883 getWindowHandleLocked(connection->inputChannel->getConnectionToken()) != nullptr;
3884 notify = !connection->monitor && stillHaveWindowHandle;
3885 if (notify) {
3886 ALOGW("channel '%s' ~ Consumer closed input channel or an error occurred. events=0x%x",
3887 connection->getInputChannelName().c_str(), events);
3888 }
3889 }
3890
3891 // Remove the channel.
3892 removeInputChannelLocked(connection->inputChannel->getConnectionToken(), notify);
3893 return 0; // remove the callback
Michael Wrightd02c5b62014-02-10 15:10:22 -08003894}
3895
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003896void InputDispatcher::synthesizeCancelationEventsForAllConnectionsLocked(
Michael Wrightd02c5b62014-02-10 15:10:22 -08003897 const CancelationOptions& options) {
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003898 for (const auto& [token, connection] : mConnectionsByToken) {
Siarhei Vishniakou2e2ea992020-12-15 02:57:19 +00003899 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003900 }
3901}
3902
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003903void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
Michael Wrightfa13dcf2015-06-12 13:25:11 +01003904 const CancelationOptions& options) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08003905 for (const auto& [_, monitors] : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003906 for (const Monitor& monitor : monitors) {
3907 synthesizeCancelationEventsForInputChannelLocked(monitor.inputChannel, options);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003908 }
Michael Wrightfa13dcf2015-06-12 13:25:11 +01003909 }
3910}
3911
Michael Wrightd02c5b62014-02-10 15:10:22 -08003912void InputDispatcher::synthesizeCancelationEventsForInputChannelLocked(
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05003913 const std::shared_ptr<InputChannel>& channel, const CancelationOptions& options) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003914 std::shared_ptr<Connection> connection = getConnectionLocked(channel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003915 if (connection == nullptr) {
3916 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003917 }
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003918
3919 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003920}
3921
3922void InputDispatcher::synthesizeCancelationEventsForConnectionLocked(
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003923 const std::shared_ptr<Connection>& connection, const CancelationOptions& options) {
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003924 if (connection->status == Connection::Status::BROKEN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003925 return;
3926 }
3927
3928 nsecs_t currentTime = now();
3929
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003930 std::vector<std::unique_ptr<EventEntry>> cancelationEvents =
Siarhei Vishniakou00fca7c2019-10-29 13:05:57 -07003931 connection->inputState.synthesizeCancelationEvents(currentTime, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003932
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003933 if (cancelationEvents.empty()) {
3934 return;
3935 }
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003936 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
3937 ALOGD("channel '%s' ~ Synthesized %zu cancelation events to bring channel back in sync "
Siarhei Vishniakou2e3e4432023-02-09 18:34:11 -08003938 "with reality: %s, mode=%s.",
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003939 connection->getInputChannelName().c_str(), cancelationEvents.size(), options.reason,
Siarhei Vishniakou2e3e4432023-02-09 18:34:11 -08003940 ftl::enum_string(options.mode).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003941 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08003942
Arthur Hungb3307ee2021-10-14 10:57:37 +00003943 std::string reason = std::string("reason=").append(options.reason);
3944 android_log_event_list(LOGTAG_INPUT_CANCEL)
3945 << connection->getInputChannelName().c_str() << reason << LOG_ID_EVENTS;
3946
Hu Guo771a7692023-09-17 20:51:08 +08003947 sp<WindowInfoHandle> windowHandle;
3948 if (options.displayId) {
3949 windowHandle = getWindowHandleLocked(connection->inputChannel->getConnectionToken(),
3950 options.displayId.value());
3951 } else {
3952 windowHandle = getWindowHandleLocked(connection->inputChannel->getConnectionToken());
3953 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08003954
hongzuo liu95785e22022-09-06 02:51:35 +00003955 const bool wasEmpty = connection->outboundQueue.empty();
3956
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003957 for (size_t i = 0; i < cancelationEvents.size(); i++) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003958 std::unique_ptr<EventEntry> cancelationEventEntry = std::move(cancelationEvents[i]);
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00003959 std::vector<InputTarget> targets{};
3960 // The target to use if we don't find a window associated with the channel.
3961 const InputTarget fallbackTarget{.inputChannel = connection->inputChannel,
3962 .flags = InputTarget::Flags::DISPATCH_AS_IS};
3963
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003964 switch (cancelationEventEntry->type) {
3965 case EventEntry::Type::KEY: {
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00003966 const auto& keyEntry = static_cast<const KeyEntry&>(*cancelationEventEntry);
3967 if (windowHandle != nullptr) {
3968 addWindowTargetLocked(windowHandle, InputTarget::Flags::DISPATCH_AS_IS,
3969 /*pointerIds=*/{}, keyEntry.downTime, targets);
3970 } else {
3971 targets.emplace_back(fallbackTarget);
3972 }
3973 logOutboundKeyDetails("cancel - ", keyEntry);
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003974 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003975 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003976 case EventEntry::Type::MOTION: {
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00003977 const auto& motionEntry = static_cast<const MotionEntry&>(*cancelationEventEntry);
3978 if (windowHandle != nullptr) {
3979 std::bitset<MAX_POINTER_ID + 1> pointerIds;
3980 for (uint32_t pointerIndex = 0; pointerIndex < motionEntry.pointerCount;
3981 pointerIndex++) {
3982 pointerIds.set(motionEntry.pointerProperties[pointerIndex].id);
3983 }
3984 addWindowTargetLocked(windowHandle, InputTarget::Flags::DISPATCH_AS_IS,
3985 pointerIds, motionEntry.downTime, targets);
3986 } else {
3987 targets.emplace_back(fallbackTarget);
3988 const auto it = mDisplayInfos.find(motionEntry.displayId);
3989 if (it != mDisplayInfos.end()) {
3990 targets.back().displayTransform = it->second.transform;
3991 targets.back().setDefaultPointerTransform(it->second.transform);
3992 }
3993 }
3994 logOutboundMotionDetails("cancel - ", motionEntry);
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003995 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003996 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003997 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003998 case EventEntry::Type::TOUCH_MODE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08003999 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
4000 case EventEntry::Type::DRAG: {
Prabir Pradhan99987712020-11-10 18:43:05 -08004001 LOG_ALWAYS_FATAL("Canceling %s events is not supported",
Dominik Laskowski75788452021-02-09 18:51:25 -08004002 ftl::enum_string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004003 break;
4004 }
4005 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07004006 case EventEntry::Type::DEVICE_RESET:
4007 case EventEntry::Type::SENSOR: {
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004008 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Dominik Laskowski75788452021-02-09 18:51:25 -08004009 ftl::enum_string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004010 break;
4011 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004012 }
4013
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00004014 if (targets.size() != 1) LOG(FATAL) << __func__ << ": InputTarget not created";
4015 enqueueDispatchEntryLocked(connection, std::move(cancelationEventEntry), targets[0],
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08004016 InputTarget::Flags::DISPATCH_AS_IS);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004017 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004018
hongzuo liu95785e22022-09-06 02:51:35 +00004019 // If the outbound queue was previously empty, start the dispatch cycle going.
4020 if (wasEmpty && !connection->outboundQueue.empty()) {
4021 startDispatchCycleLocked(currentTime, connection);
4022 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004023}
4024
Svet Ganov5d3bc372020-01-26 23:11:07 -08004025void InputDispatcher::synthesizePointerDownEventsForConnectionLocked(
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07004026 const nsecs_t downTime, const std::shared_ptr<Connection>& connection,
Arthur Hungc539dbb2022-12-08 07:45:36 +00004027 ftl::Flags<InputTarget::Flags> targetFlags) {
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08004028 if (connection->status == Connection::Status::BROKEN) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08004029 return;
4030 }
4031
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004032 std::vector<std::unique_ptr<EventEntry>> downEvents =
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00004033 connection->inputState.synthesizePointerDownEvents(downTime);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004034
4035 if (downEvents.empty()) {
4036 return;
4037 }
4038
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004039 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08004040 ALOGD("channel '%s' ~ Synthesized %zu down events to ensure consistent event stream.",
4041 connection->getInputChannelName().c_str(), downEvents.size());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004042 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08004043
4044 InputTarget target;
chaviw98318de2021-05-19 16:45:23 -05004045 sp<WindowInfoHandle> windowHandle =
Svet Ganov5d3bc372020-01-26 23:11:07 -08004046 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
4047 if (windowHandle != nullptr) {
chaviw98318de2021-05-19 16:45:23 -05004048 const WindowInfo* windowInfo = windowHandle->getInfo();
chaviw1ff3d1e2020-07-01 15:53:47 -07004049 target.setDefaultPointerTransform(windowInfo->transform);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004050 target.globalScaleFactor = windowInfo->globalScaleFactor;
4051 }
4052 target.inputChannel = connection->inputChannel;
Arthur Hungc539dbb2022-12-08 07:45:36 +00004053 target.flags = targetFlags;
Svet Ganov5d3bc372020-01-26 23:11:07 -08004054
hongzuo liu95785e22022-09-06 02:51:35 +00004055 const bool wasEmpty = connection->outboundQueue.empty();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004056 for (std::unique_ptr<EventEntry>& downEventEntry : downEvents) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08004057 switch (downEventEntry->type) {
4058 case EventEntry::Type::MOTION: {
4059 logOutboundMotionDetails("down - ",
4060 static_cast<const MotionEntry&>(*downEventEntry));
4061 break;
4062 }
4063
4064 case EventEntry::Type::KEY:
4065 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07004066 case EventEntry::Type::TOUCH_MODE_CHANGED:
Svet Ganov5d3bc372020-01-26 23:11:07 -08004067 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08004068 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07004069 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08004070 case EventEntry::Type::SENSOR:
4071 case EventEntry::Type::DRAG: {
Svet Ganov5d3bc372020-01-26 23:11:07 -08004072 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Dominik Laskowski75788452021-02-09 18:51:25 -08004073 ftl::enum_string(downEventEntry->type).c_str());
Svet Ganov5d3bc372020-01-26 23:11:07 -08004074 break;
4075 }
4076 }
4077
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004078 enqueueDispatchEntryLocked(connection, std::move(downEventEntry), target,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08004079 InputTarget::Flags::DISPATCH_AS_IS);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004080 }
4081
hongzuo liu95785e22022-09-06 02:51:35 +00004082 // If the outbound queue was previously empty, start the dispatch cycle going.
4083 if (wasEmpty && !connection->outboundQueue.empty()) {
4084 startDispatchCycleLocked(downTime, connection);
4085 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08004086}
4087
Arthur Hungc539dbb2022-12-08 07:45:36 +00004088void InputDispatcher::synthesizeCancelationEventsForWindowLocked(
4089 const sp<WindowInfoHandle>& windowHandle, const CancelationOptions& options) {
4090 if (windowHandle != nullptr) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07004091 std::shared_ptr<Connection> wallpaperConnection =
4092 getConnectionLocked(windowHandle->getToken());
Arthur Hungc539dbb2022-12-08 07:45:36 +00004093 if (wallpaperConnection != nullptr) {
4094 synthesizeCancelationEventsForConnectionLocked(wallpaperConnection, options);
4095 }
4096 }
4097}
4098
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004099std::unique_ptr<MotionEntry> InputDispatcher::splitMotionEvent(
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08004100 const MotionEntry& originalMotionEntry, std::bitset<MAX_POINTER_ID + 1> pointerIds,
4101 nsecs_t splitDownTime) {
4102 ALOG_ASSERT(pointerIds.any());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004103
4104 uint32_t splitPointerIndexMap[MAX_POINTERS];
4105 PointerProperties splitPointerProperties[MAX_POINTERS];
4106 PointerCoords splitPointerCoords[MAX_POINTERS];
4107
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07004108 uint32_t originalPointerCount = originalMotionEntry.pointerCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004109 uint32_t splitPointerCount = 0;
4110
4111 for (uint32_t originalPointerIndex = 0; originalPointerIndex < originalPointerCount;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004112 originalPointerIndex++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004113 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07004114 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08004115 uint32_t pointerId = uint32_t(pointerProperties.id);
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08004116 if (pointerIds.test(pointerId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004117 splitPointerIndexMap[splitPointerCount] = originalPointerIndex;
Siarhei Vishniakou73e6d372023-07-06 18:07:21 -07004118 splitPointerProperties[splitPointerCount] = pointerProperties;
4119 splitPointerCoords[splitPointerCount] =
4120 originalMotionEntry.pointerCoords[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08004121 splitPointerCount += 1;
4122 }
4123 }
4124
4125 if (splitPointerCount != pointerIds.count()) {
4126 // This is bad. We are missing some of the pointers that we expected to deliver.
4127 // Most likely this indicates that we received an ACTION_MOVE events that has
4128 // different pointer ids than we expected based on the previous ACTION_DOWN
4129 // or ACTION_POINTER_DOWN events that caused us to decide to split the pointers
4130 // in this way.
4131 ALOGW("Dropping split motion event because the pointer count is %d but "
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08004132 "we expected there to be %zu pointers. This probably means we received "
Siarhei Vishniakou16e4fa02023-02-16 17:48:56 -08004133 "a broken sequence of pointer ids from the input device: %s",
4134 splitPointerCount, pointerIds.count(), originalMotionEntry.getDescription().c_str());
Yi Kong9b14ac62018-07-17 13:48:38 -07004135 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004136 }
4137
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07004138 int32_t action = originalMotionEntry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004139 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004140 if (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN ||
4141 maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
Siarhei Vishniakou5b9766d2023-07-18 14:06:29 -07004142 int32_t originalPointerIndex = MotionEvent::getActionIndex(action);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004143 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07004144 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08004145 uint32_t pointerId = uint32_t(pointerProperties.id);
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08004146 if (pointerIds.test(pointerId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004147 if (pointerIds.count() == 1) {
4148 // The first/last pointer went down/up.
4149 action = maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004150 ? AMOTION_EVENT_ACTION_DOWN
arthurhungea3f4fc2020-12-21 23:18:53 +08004151 : (originalMotionEntry.flags & AMOTION_EVENT_FLAG_CANCELED) != 0
4152 ? AMOTION_EVENT_ACTION_CANCEL
4153 : AMOTION_EVENT_ACTION_UP;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004154 } else {
4155 // A secondary pointer went down/up.
4156 uint32_t splitPointerIndex = 0;
4157 while (pointerId != uint32_t(splitPointerProperties[splitPointerIndex].id)) {
4158 splitPointerIndex += 1;
4159 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004160 action = maskedAction |
4161 (splitPointerIndex << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004162 }
4163 } else {
4164 // An unrelated pointer changed.
4165 action = AMOTION_EVENT_ACTION_MOVE;
4166 }
4167 }
4168
Siarhei Vishniakou59e302b2023-06-05 08:04:53 -07004169 if (action == AMOTION_EVENT_ACTION_DOWN && splitDownTime != originalMotionEntry.eventTime) {
4170 logDispatchStateLocked();
4171 LOG_ALWAYS_FATAL("Split motion event has mismatching downTime and eventTime for "
4172 "ACTION_DOWN, motionEntry=%s, splitDownTime=%" PRId64,
4173 originalMotionEntry.getDescription().c_str(), splitDownTime);
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00004174 }
4175
Garfield Tanff1f1bb2020-01-28 13:24:04 -08004176 int32_t newId = mIdGenerator.nextId();
Prabir Pradhan2dac8b82023-09-06 01:11:51 +00004177 ATRACE_NAME_IF(ATRACE_ENABLED(),
4178 StringPrintf("Split MotionEvent(id=0x%" PRIx32 ") to MotionEvent(id=0x%" PRIx32
4179 ").",
4180 originalMotionEntry.id, newId));
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004181 std::unique_ptr<MotionEntry> splitMotionEntry =
4182 std::make_unique<MotionEntry>(newId, originalMotionEntry.eventTime,
4183 originalMotionEntry.deviceId, originalMotionEntry.source,
4184 originalMotionEntry.displayId,
4185 originalMotionEntry.policyFlags, action,
4186 originalMotionEntry.actionButton,
4187 originalMotionEntry.flags, originalMotionEntry.metaState,
4188 originalMotionEntry.buttonState,
4189 originalMotionEntry.classification,
4190 originalMotionEntry.edgeFlags,
4191 originalMotionEntry.xPrecision,
4192 originalMotionEntry.yPrecision,
4193 originalMotionEntry.xCursorPosition,
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00004194 originalMotionEntry.yCursorPosition, splitDownTime,
4195 splitPointerCount, splitPointerProperties,
4196 splitPointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004197
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07004198 if (originalMotionEntry.injectionState) {
4199 splitMotionEntry->injectionState = originalMotionEntry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004200 splitMotionEntry->injectionState->refCount += 1;
4201 }
4202
4203 return splitMotionEntry;
4204}
4205
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004206void InputDispatcher::notifyConfigurationChanged(const NotifyConfigurationChangedArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004207 if (debugInboundEventDetails()) {
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004208 ALOGD("notifyConfigurationChanged - eventTime=%" PRId64, args.eventTime);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004209 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004210
Antonio Kantekf16f2832021-09-28 04:39:20 +00004211 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004212 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004213 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004214
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004215 std::unique_ptr<ConfigurationChangedEntry> newEntry =
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004216 std::make_unique<ConfigurationChangedEntry>(args.id, args.eventTime);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004217 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004218 } // release lock
4219
4220 if (needWake) {
4221 mLooper->wake();
4222 }
4223}
4224
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004225void InputDispatcher::notifyKey(const NotifyKeyArgs& args) {
Prabir Pradhan96282b02023-02-24 22:36:17 +00004226 ALOGD_IF(debugInboundEventDetails(),
4227 "notifyKey - id=%" PRIx32 ", eventTime=%" PRId64
4228 ", deviceId=%d, source=%s, displayId=%" PRId32
4229 "policyFlags=0x%x, action=%s, flags=0x%x, keyCode=%s, scanCode=0x%x, metaState=0x%x, "
4230 "downTime=%" PRId64,
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004231 args.id, args.eventTime, args.deviceId, inputEventSourceToString(args.source).c_str(),
4232 args.displayId, args.policyFlags, KeyEvent::actionToString(args.action), args.flags,
4233 KeyEvent::getLabel(args.keyCode), args.scanCode, args.metaState, args.downTime);
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004234 Result<void> keyCheck = validateKeyEvent(args.action);
4235 if (!keyCheck.ok()) {
4236 LOG(ERROR) << "invalid key event: " << keyCheck.error();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004237 return;
4238 }
4239
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004240 uint32_t policyFlags = args.policyFlags;
4241 int32_t flags = args.flags;
4242 int32_t metaState = args.metaState;
Siarhei Vishniakou622bd322018-10-29 18:02:27 -07004243 // InputDispatcher tracks and generates key repeats on behalf of
4244 // whatever notifies it, so repeatCount should always be set to 0
4245 constexpr int32_t repeatCount = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004246 if ((policyFlags & POLICY_FLAG_VIRTUAL) || (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY)) {
4247 policyFlags |= POLICY_FLAG_VIRTUAL;
4248 flags |= AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
4249 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004250 if (policyFlags & POLICY_FLAG_FUNCTION) {
4251 metaState |= AMETA_FUNCTION_ON;
4252 }
4253
4254 policyFlags |= POLICY_FLAG_TRUSTED;
4255
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004256 int32_t keyCode = args.keyCode;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004257 KeyEvent event;
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004258 event.initialize(args.id, args.deviceId, args.source, args.displayId, INVALID_HMAC, args.action,
4259 flags, keyCode, args.scanCode, metaState, repeatCount, args.downTime,
4260 args.eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004261
Michael Wright2b3c3302018-03-02 17:19:13 +00004262 android::base::Timer t;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004263 mPolicy.interceptKeyBeforeQueueing(event, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00004264 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4265 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004266 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00004267 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004268
Antonio Kantekf16f2832021-09-28 04:39:20 +00004269 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004270 { // acquire lock
4271 mLock.lock();
4272
4273 if (shouldSendKeyToInputFilterLocked(args)) {
4274 mLock.unlock();
4275
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004276 policyFlags |= POLICY_FLAG_FILTERED;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004277 if (!mPolicy.filterInputEvent(event, policyFlags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004278 return; // event was consumed by the filter
4279 }
4280
4281 mLock.lock();
4282 }
4283
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004284 std::unique_ptr<KeyEntry> newEntry =
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004285 std::make_unique<KeyEntry>(args.id, args.eventTime, args.deviceId, args.source,
4286 args.displayId, policyFlags, args.action, flags, keyCode,
4287 args.scanCode, metaState, repeatCount, args.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004288
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004289 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004290 mLock.unlock();
4291 } // release lock
4292
4293 if (needWake) {
4294 mLooper->wake();
4295 }
4296}
4297
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004298bool InputDispatcher::shouldSendKeyToInputFilterLocked(const NotifyKeyArgs& args) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004299 return mInputFilterEnabled;
4300}
4301
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004302void InputDispatcher::notifyMotion(const NotifyMotionArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004303 if (debugInboundEventDetails()) {
Prabir Pradhan96282b02023-02-24 22:36:17 +00004304 ALOGD("notifyMotion - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=%s, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004305 "displayId=%" PRId32 ", policyFlags=0x%x, "
Siarhei Vishniakou6ebd0692022-10-20 15:05:45 -07004306 "action=%s, actionButton=0x%x, flags=0x%x, metaState=0x%x, buttonState=0x%x, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004307 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, xCursorPosition=%f, "
4308 "yCursorPosition=%f, downTime=%" PRId64,
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004309 args.id, args.eventTime, args.deviceId, inputEventSourceToString(args.source).c_str(),
4310 args.displayId, args.policyFlags, MotionEvent::actionToString(args.action).c_str(),
4311 args.actionButton, args.flags, args.metaState, args.buttonState, args.edgeFlags,
4312 args.xPrecision, args.yPrecision, args.xCursorPosition, args.yCursorPosition,
4313 args.downTime);
Siarhei Vishniakou3218fc02023-06-15 20:41:02 -07004314 for (uint32_t i = 0; i < args.getPointerCount(); i++) {
Prabir Pradhan96282b02023-02-24 22:36:17 +00004315 ALOGD(" Pointer %d: id=%d, toolType=%s, x=%f, y=%f, pressure=%f, size=%f, "
4316 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, orientation=%f",
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004317 i, args.pointerProperties[i].id,
4318 ftl::enum_string(args.pointerProperties[i].toolType).c_str(),
4319 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
4320 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
4321 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
4322 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
4323 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
4324 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
4325 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
4326 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
4327 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004328 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004329 }
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004330
Siarhei Vishniakou3218fc02023-06-15 20:41:02 -07004331 Result<void> motionCheck =
4332 validateMotionEvent(args.action, args.actionButton, args.getPointerCount(),
4333 args.pointerProperties.data());
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004334 if (!motionCheck.ok()) {
4335 LOG(FATAL) << "Invalid event: " << args.dump() << "; reason: " << motionCheck.error();
4336 return;
4337 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004338
Siarhei Vishniakou5c02a712023-05-15 15:45:02 -07004339 if (DEBUG_VERIFY_EVENTS) {
4340 auto [it, _] =
4341 mVerifiersByDisplay.try_emplace(args.displayId,
4342 StringPrintf("display %" PRId32, args.displayId));
4343 Result<void> result =
Siarhei Vishniakou2d151ac2023-09-19 13:30:24 -07004344 it->second.processMovement(args.deviceId, args.source, args.action,
4345 args.getPointerCount(), args.pointerProperties.data(),
4346 args.pointerCoords.data(), args.flags);
Siarhei Vishniakou5c02a712023-05-15 15:45:02 -07004347 if (!result.ok()) {
4348 LOG(FATAL) << "Bad stream: " << result.error() << " caused by " << args.dump();
4349 }
4350 }
4351
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004352 uint32_t policyFlags = args.policyFlags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004353 policyFlags |= POLICY_FLAG_TRUSTED;
Michael Wright2b3c3302018-03-02 17:19:13 +00004354
4355 android::base::Timer t;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004356 mPolicy.interceptMotionBeforeQueueing(args.displayId, args.eventTime, policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00004357 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4358 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004359 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00004360 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004361
Antonio Kantekf16f2832021-09-28 04:39:20 +00004362 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004363 { // acquire lock
4364 mLock.lock();
Siarhei Vishniakou5bf25d92023-02-08 15:43:38 -08004365 if (!(policyFlags & POLICY_FLAG_PASS_TO_USER)) {
4366 // Set the flag anyway if we already have an ongoing gesture. That would allow us to
4367 // complete the processing of the current stroke.
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004368 const auto touchStateIt = mTouchStatesByDisplay.find(args.displayId);
Siarhei Vishniakou5bf25d92023-02-08 15:43:38 -08004369 if (touchStateIt != mTouchStatesByDisplay.end()) {
4370 const TouchState& touchState = touchStateIt->second;
Siarhei Vishniakou45504fe2023-05-05 16:05:10 -07004371 if (touchState.hasTouchingPointers(args.deviceId)) {
Siarhei Vishniakou5bf25d92023-02-08 15:43:38 -08004372 policyFlags |= POLICY_FLAG_PASS_TO_USER;
4373 }
4374 }
4375 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004376
4377 if (shouldSendMotionToInputFilterLocked(args)) {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004378 ui::Transform displayTransform;
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004379 if (const auto it = mDisplayInfos.find(args.displayId); it != mDisplayInfos.end()) {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004380 displayTransform = it->second.transform;
4381 }
4382
Michael Wrightd02c5b62014-02-10 15:10:22 -08004383 mLock.unlock();
4384
4385 MotionEvent event;
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004386 event.initialize(args.id, args.deviceId, args.source, args.displayId, INVALID_HMAC,
4387 args.action, args.actionButton, args.flags, args.edgeFlags,
4388 args.metaState, args.buttonState, args.classification,
4389 displayTransform, args.xPrecision, args.yPrecision,
4390 args.xCursorPosition, args.yCursorPosition, displayTransform,
Siarhei Vishniakou3218fc02023-06-15 20:41:02 -07004391 args.downTime, args.eventTime, args.getPointerCount(),
4392 args.pointerProperties.data(), args.pointerCoords.data());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004393
4394 policyFlags |= POLICY_FLAG_FILTERED;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004395 if (!mPolicy.filterInputEvent(event, policyFlags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004396 return; // event was consumed by the filter
4397 }
4398
4399 mLock.lock();
4400 }
4401
4402 // Just enqueue a new motion event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004403 std::unique_ptr<MotionEntry> newEntry =
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004404 std::make_unique<MotionEntry>(args.id, args.eventTime, args.deviceId, args.source,
4405 args.displayId, policyFlags, args.action,
4406 args.actionButton, args.flags, args.metaState,
4407 args.buttonState, args.classification, args.edgeFlags,
4408 args.xPrecision, args.yPrecision,
4409 args.xCursorPosition, args.yCursorPosition,
Siarhei Vishniakou3218fc02023-06-15 20:41:02 -07004410 args.downTime, args.getPointerCount(),
4411 args.pointerProperties.data(),
4412 args.pointerCoords.data());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004413
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004414 if (args.id != android::os::IInputConstants::INVALID_INPUT_EVENT_ID &&
4415 IdGenerator::getSource(args.id) == IdGenerator::Source::INPUT_READER &&
Siarhei Vishniakou363e7292021-07-09 03:22:42 +00004416 !mInputFilterEnabled) {
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004417 const bool isDown = args.action == AMOTION_EVENT_ACTION_DOWN;
4418 mLatencyTracker.trackListener(args.id, isDown, args.eventTime, args.readTime);
Siarhei Vishniakou363e7292021-07-09 03:22:42 +00004419 }
4420
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004421 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004422 mLock.unlock();
4423 } // release lock
4424
4425 if (needWake) {
4426 mLooper->wake();
4427 }
4428}
4429
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004430void InputDispatcher::notifySensor(const NotifySensorArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004431 if (debugInboundEventDetails()) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004432 ALOGD("notifySensor - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=0x%x, "
4433 " sensorType=%s",
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004434 args.id, args.eventTime, args.deviceId, args.source,
4435 ftl::enum_string(args.sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004436 }
Chris Yef59a2f42020-10-16 12:55:26 -07004437
Antonio Kantekf16f2832021-09-28 04:39:20 +00004438 bool needWake = false;
Chris Yef59a2f42020-10-16 12:55:26 -07004439 { // acquire lock
4440 mLock.lock();
4441
4442 // Just enqueue a new sensor event.
4443 std::unique_ptr<SensorEntry> newEntry =
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004444 std::make_unique<SensorEntry>(args.id, args.eventTime, args.deviceId, args.source,
4445 /* policyFlags=*/0, args.hwTimestamp, args.sensorType,
4446 args.accuracy, args.accuracyChanged, args.values);
Chris Yef59a2f42020-10-16 12:55:26 -07004447
4448 needWake = enqueueInboundEventLocked(std::move(newEntry));
4449 mLock.unlock();
4450 } // release lock
4451
4452 if (needWake) {
4453 mLooper->wake();
4454 }
4455}
4456
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004457void InputDispatcher::notifyVibratorState(const NotifyVibratorStateArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004458 if (debugInboundEventDetails()) {
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004459 ALOGD("notifyVibratorState - eventTime=%" PRId64 ", device=%d, isOn=%d", args.eventTime,
4460 args.deviceId, args.isOn);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004461 }
Prabir Pradhana41d2442023-04-20 21:30:40 +00004462 mPolicy.notifyVibratorState(args.deviceId, args.isOn);
Chris Yefb552902021-02-03 17:18:37 -08004463}
4464
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004465bool InputDispatcher::shouldSendMotionToInputFilterLocked(const NotifyMotionArgs& args) {
Jackal Guof9696682018-10-05 12:23:23 +08004466 return mInputFilterEnabled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004467}
4468
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004469void InputDispatcher::notifySwitch(const NotifySwitchArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004470 if (debugInboundEventDetails()) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004471 ALOGD("notifySwitch - eventTime=%" PRId64 ", policyFlags=0x%x, switchValues=0x%08x, "
4472 "switchMask=0x%08x",
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004473 args.eventTime, args.policyFlags, args.switchValues, args.switchMask);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004474 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004475
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004476 uint32_t policyFlags = args.policyFlags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004477 policyFlags |= POLICY_FLAG_TRUSTED;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004478 mPolicy.notifySwitch(args.eventTime, args.switchValues, args.switchMask, policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004479}
4480
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004481void InputDispatcher::notifyDeviceReset(const NotifyDeviceResetArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004482 if (debugInboundEventDetails()) {
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004483 ALOGD("notifyDeviceReset - eventTime=%" PRId64 ", deviceId=%d", args.eventTime,
4484 args.deviceId);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004485 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004486
Antonio Kantekf16f2832021-09-28 04:39:20 +00004487 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004488 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004489 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004490
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004491 std::unique_ptr<DeviceResetEntry> newEntry =
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004492 std::make_unique<DeviceResetEntry>(args.id, args.eventTime, args.deviceId);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004493 needWake = enqueueInboundEventLocked(std::move(newEntry));
Siarhei Vishniakou1160ecd2023-06-28 15:57:47 -07004494
4495 for (auto& [_, verifier] : mVerifiersByDisplay) {
4496 verifier.resetDevice(args.deviceId);
4497 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004498 } // release lock
4499
4500 if (needWake) {
4501 mLooper->wake();
4502 }
4503}
4504
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004505void InputDispatcher::notifyPointerCaptureChanged(const NotifyPointerCaptureChangedArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004506 if (debugInboundEventDetails()) {
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004507 ALOGD("notifyPointerCaptureChanged - eventTime=%" PRId64 ", enabled=%s", args.eventTime,
4508 args.request.enable ? "true" : "false");
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004509 }
Prabir Pradhan7e186182020-11-10 13:56:45 -08004510
Antonio Kantekf16f2832021-09-28 04:39:20 +00004511 bool needWake = false;
Prabir Pradhan99987712020-11-10 18:43:05 -08004512 { // acquire lock
4513 std::scoped_lock _l(mLock);
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004514 auto entry =
4515 std::make_unique<PointerCaptureChangedEntry>(args.id, args.eventTime, args.request);
Prabir Pradhan99987712020-11-10 18:43:05 -08004516 needWake = enqueueInboundEventLocked(std::move(entry));
4517 } // release lock
4518
4519 if (needWake) {
4520 mLooper->wake();
4521 }
Prabir Pradhan7e186182020-11-10 13:56:45 -08004522}
4523
Prabir Pradhan5735a322022-04-11 17:23:34 +00004524InputEventInjectionResult InputDispatcher::injectInputEvent(const InputEvent* event,
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00004525 std::optional<gui::Uid> targetUid,
Prabir Pradhan5735a322022-04-11 17:23:34 +00004526 InputEventInjectionSync syncMode,
4527 std::chrono::milliseconds timeout,
4528 uint32_t policyFlags) {
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004529 Result<void> eventValidation = validateInputEvent(*event);
4530 if (!eventValidation.ok()) {
4531 LOG(INFO) << "Injection failed: invalid event: " << eventValidation.error();
4532 return InputEventInjectionResult::FAILED;
4533 }
4534
Prabir Pradhan65613802023-02-22 23:36:58 +00004535 if (debugInboundEventDetails()) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07004536 LOG(INFO) << __func__ << ": targetUid=" << toString(targetUid, &uidString)
4537 << ", syncMode=" << ftl::enum_string(syncMode) << ", timeout=" << timeout.count()
4538 << "ms, policyFlags=0x" << std::hex << policyFlags << std::dec
4539 << ", event=" << *event;
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004540 }
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07004541 nsecs_t endTime = now() + std::chrono::duration_cast<std::chrono::nanoseconds>(timeout).count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004542
Prabir Pradhan5735a322022-04-11 17:23:34 +00004543 policyFlags |= POLICY_FLAG_INJECTED | POLICY_FLAG_TRUSTED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004544
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004545 // For all injected events, set device id = VIRTUAL_KEYBOARD_ID. The only exception is events
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004546 // that have gone through the InputFilter. If the event passed through the InputFilter, assign
4547 // the provided device id. If the InputFilter is accessibility, and it modifies or synthesizes
4548 // the injected event, it is responsible for setting POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY.
4549 // For those events, we will set FLAG_IS_ACCESSIBILITY_EVENT to allow apps to distinguish them
4550 // from events that originate from actual hardware.
Siarhei Vishniakouf4043212023-09-18 19:33:03 -07004551 DeviceId resolvedDeviceId = VIRTUAL_KEYBOARD_ID;
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004552 if (policyFlags & POLICY_FLAG_FILTERED) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004553 resolvedDeviceId = event->getDeviceId();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004554 }
4555
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004556 std::queue<std::unique_ptr<EventEntry>> injectedEntries;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004557 switch (event->getType()) {
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004558 case InputEventType::KEY: {
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004559 const KeyEvent& incomingKey = static_cast<const KeyEvent&>(*event);
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004560 const int32_t action = incomingKey.getAction();
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004561 int32_t flags = incomingKey.getFlags();
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004562 if (policyFlags & POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY) {
4563 flags |= AKEY_EVENT_FLAG_IS_ACCESSIBILITY_EVENT;
4564 }
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004565 int32_t keyCode = incomingKey.getKeyCode();
4566 int32_t metaState = incomingKey.getMetaState();
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004567 KeyEvent keyEvent;
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004568 keyEvent.initialize(incomingKey.getId(), resolvedDeviceId, incomingKey.getSource(),
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004569 incomingKey.getDisplayId(), INVALID_HMAC, action, flags, keyCode,
4570 incomingKey.getScanCode(), metaState, incomingKey.getRepeatCount(),
4571 incomingKey.getDownTime(), incomingKey.getEventTime());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004572
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004573 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
4574 policyFlags |= POLICY_FLAG_VIRTUAL;
Michael Wright2b3c3302018-03-02 17:19:13 +00004575 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004576
4577 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
4578 android::base::Timer t;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004579 mPolicy.interceptKeyBeforeQueueing(keyEvent, /*byref*/ policyFlags);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004580 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4581 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
4582 std::to_string(t.duration().count()).c_str());
4583 }
4584 }
4585
4586 mLock.lock();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004587 std::unique_ptr<KeyEntry> injectedEntry =
4588 std::make_unique<KeyEntry>(incomingKey.getId(), incomingKey.getEventTime(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004589 resolvedDeviceId, incomingKey.getSource(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004590 incomingKey.getDisplayId(), policyFlags, action,
4591 flags, keyCode, incomingKey.getScanCode(), metaState,
4592 incomingKey.getRepeatCount(),
4593 incomingKey.getDownTime());
4594 injectedEntries.push(std::move(injectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004595 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004596 }
4597
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004598 case InputEventType::MOTION: {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004599 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(*event);
Prabir Pradhanaa561d12021-09-24 06:57:33 -07004600 const bool isPointerEvent =
4601 isFromSource(event->getSource(), AINPUT_SOURCE_CLASS_POINTER);
4602 // If a pointer event has no displayId specified, inject it to the default display.
4603 const uint32_t displayId = isPointerEvent && (event->getDisplayId() == ADISPLAY_ID_NONE)
4604 ? ADISPLAY_ID_DEFAULT
4605 : event->getDisplayId();
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004606 int32_t flags = motionEvent.getFlags();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004607
4608 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004609 nsecs_t eventTime = motionEvent.getEventTime();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004610 android::base::Timer t;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004611 mPolicy.interceptMotionBeforeQueueing(displayId, eventTime, /*byref*/ policyFlags);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004612 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4613 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
4614 std::to_string(t.duration().count()).c_str());
4615 }
4616 }
4617
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004618 if (policyFlags & POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY) {
4619 flags |= AMOTION_EVENT_FLAG_IS_ACCESSIBILITY_EVENT;
4620 }
4621
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004622 mLock.lock();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004623 const nsecs_t* sampleEventTimes = motionEvent.getSampleEventTimes();
4624 const PointerCoords* samplePointerCoords = motionEvent.getSamplePointerCoords();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004625 std::unique_ptr<MotionEntry> injectedEntry =
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004626 std::make_unique<MotionEntry>(motionEvent.getId(), *sampleEventTimes,
4627 resolvedDeviceId, motionEvent.getSource(),
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004628 displayId, policyFlags, motionEvent.getAction(),
4629 motionEvent.getActionButton(), flags,
4630 motionEvent.getMetaState(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004631 motionEvent.getButtonState(),
4632 motionEvent.getClassification(),
4633 motionEvent.getEdgeFlags(),
4634 motionEvent.getXPrecision(),
4635 motionEvent.getYPrecision(),
4636 motionEvent.getRawXCursorPosition(),
4637 motionEvent.getRawYCursorPosition(),
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004638 motionEvent.getDownTime(),
4639 motionEvent.getPointerCount(),
4640 motionEvent.getPointerProperties(),
4641 samplePointerCoords);
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004642 transformMotionEntryForInjectionLocked(*injectedEntry, motionEvent.getTransform());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004643 injectedEntries.push(std::move(injectedEntry));
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004644 for (size_t i = motionEvent.getHistorySize(); i > 0; i--) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004645 sampleEventTimes += 1;
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004646 samplePointerCoords += motionEvent.getPointerCount();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004647 std::unique_ptr<MotionEntry> nextInjectedEntry =
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004648 std::make_unique<MotionEntry>(motionEvent.getId(), *sampleEventTimes,
4649 resolvedDeviceId, motionEvent.getSource(),
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004650 displayId, policyFlags,
4651 motionEvent.getAction(),
4652 motionEvent.getActionButton(), flags,
4653 motionEvent.getMetaState(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004654 motionEvent.getButtonState(),
4655 motionEvent.getClassification(),
4656 motionEvent.getEdgeFlags(),
4657 motionEvent.getXPrecision(),
4658 motionEvent.getYPrecision(),
4659 motionEvent.getRawXCursorPosition(),
4660 motionEvent.getRawYCursorPosition(),
4661 motionEvent.getDownTime(),
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004662 motionEvent.getPointerCount(),
4663 motionEvent.getPointerProperties(),
Prabir Pradhan5beda762021-12-10 09:30:08 +00004664 samplePointerCoords);
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004665 transformMotionEntryForInjectionLocked(*nextInjectedEntry,
4666 motionEvent.getTransform());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004667 injectedEntries.push(std::move(nextInjectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004668 }
4669 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004670 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004671
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004672 default:
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004673 LOG(WARNING) << "Cannot inject " << ftl::enum_string(event->getType()) << " events";
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004674 return InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004675 }
4676
Prabir Pradhan5735a322022-04-11 17:23:34 +00004677 InjectionState* injectionState = new InjectionState(targetUid);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004678 if (syncMode == InputEventInjectionSync::NONE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004679 injectionState->injectionIsAsync = true;
4680 }
4681
4682 injectionState->refCount += 1;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004683 injectedEntries.back()->injectionState = injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004684
4685 bool needWake = false;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004686 while (!injectedEntries.empty()) {
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08004687 if (DEBUG_INJECTION) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07004688 LOG(INFO) << "Injecting " << injectedEntries.front()->getDescription();
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08004689 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004690 needWake |= enqueueInboundEventLocked(std::move(injectedEntries.front()));
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004691 injectedEntries.pop();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004692 }
4693
4694 mLock.unlock();
4695
4696 if (needWake) {
4697 mLooper->wake();
4698 }
4699
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004700 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004701 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004702 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004703
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004704 if (syncMode == InputEventInjectionSync::NONE) {
4705 injectionResult = InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004706 } else {
4707 for (;;) {
4708 injectionResult = injectionState->injectionResult;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004709 if (injectionResult != InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004710 break;
4711 }
4712
4713 nsecs_t remainingTimeout = endTime - now();
4714 if (remainingTimeout <= 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004715 if (DEBUG_INJECTION) {
4716 ALOGD("injectInputEvent - Timed out waiting for injection result "
4717 "to become available.");
4718 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004719 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004720 break;
4721 }
4722
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004723 mInjectionResultAvailable.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004724 }
4725
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004726 if (injectionResult == InputEventInjectionResult::SUCCEEDED &&
4727 syncMode == InputEventInjectionSync::WAIT_FOR_FINISHED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004728 while (injectionState->pendingForegroundDispatches != 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004729 if (DEBUG_INJECTION) {
4730 ALOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
4731 injectionState->pendingForegroundDispatches);
4732 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004733 nsecs_t remainingTimeout = endTime - now();
4734 if (remainingTimeout <= 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004735 if (DEBUG_INJECTION) {
4736 ALOGD("injectInputEvent - Timed out waiting for pending foreground "
4737 "dispatches to finish.");
4738 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004739 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004740 break;
4741 }
4742
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004743 mInjectionSyncFinished.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004744 }
4745 }
4746 }
4747
4748 injectionState->release();
4749 } // release lock
4750
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004751 if (DEBUG_INJECTION) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07004752 LOG(INFO) << "injectInputEvent - Finished with result "
4753 << ftl::enum_string(injectionResult);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004754 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004755
4756 return injectionResult;
4757}
4758
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004759std::unique_ptr<VerifiedInputEvent> InputDispatcher::verifyInputEvent(const InputEvent& event) {
Gang Wange9087892020-01-07 12:17:14 -05004760 std::array<uint8_t, 32> calculatedHmac;
4761 std::unique_ptr<VerifiedInputEvent> result;
4762 switch (event.getType()) {
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004763 case InputEventType::KEY: {
Gang Wange9087892020-01-07 12:17:14 -05004764 const KeyEvent& keyEvent = static_cast<const KeyEvent&>(event);
4765 VerifiedKeyEvent verifiedKeyEvent = verifiedKeyEventFromKeyEvent(keyEvent);
4766 result = std::make_unique<VerifiedKeyEvent>(verifiedKeyEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004767 calculatedHmac = sign(verifiedKeyEvent);
Gang Wange9087892020-01-07 12:17:14 -05004768 break;
4769 }
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004770 case InputEventType::MOTION: {
Gang Wange9087892020-01-07 12:17:14 -05004771 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(event);
4772 VerifiedMotionEvent verifiedMotionEvent =
4773 verifiedMotionEventFromMotionEvent(motionEvent);
4774 result = std::make_unique<VerifiedMotionEvent>(verifiedMotionEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004775 calculatedHmac = sign(verifiedMotionEvent);
Gang Wange9087892020-01-07 12:17:14 -05004776 break;
4777 }
4778 default: {
4779 ALOGE("Cannot verify events of type %" PRId32, event.getType());
4780 return nullptr;
4781 }
4782 }
4783 if (calculatedHmac == INVALID_HMAC) {
4784 return nullptr;
4785 }
tyiu1573a672023-02-21 22:38:32 +00004786 if (0 != CRYPTO_memcmp(calculatedHmac.data(), event.getHmac().data(), calculatedHmac.size())) {
Gang Wange9087892020-01-07 12:17:14 -05004787 return nullptr;
4788 }
4789 return result;
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004790}
4791
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004792void InputDispatcher::setInjectionResult(EventEntry& entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004793 InputEventInjectionResult injectionResult) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004794 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004795 if (injectionState) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004796 if (DEBUG_INJECTION) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07004797 LOG(INFO) << "Setting input event injection result to "
4798 << ftl::enum_string(injectionResult);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004799 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004800
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004801 if (injectionState->injectionIsAsync && !(entry.policyFlags & POLICY_FLAG_FILTERED)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004802 // Log the outcome since the injector did not wait for the injection result.
4803 switch (injectionResult) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004804 case InputEventInjectionResult::SUCCEEDED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004805 ALOGV("Asynchronous input event injection succeeded.");
4806 break;
Prabir Pradhan5735a322022-04-11 17:23:34 +00004807 case InputEventInjectionResult::TARGET_MISMATCH:
4808 ALOGV("Asynchronous input event injection target mismatch.");
4809 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004810 case InputEventInjectionResult::FAILED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004811 ALOGW("Asynchronous input event injection failed.");
4812 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004813 case InputEventInjectionResult::TIMED_OUT:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004814 ALOGW("Asynchronous input event injection timed out.");
4815 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004816 case InputEventInjectionResult::PENDING:
4817 ALOGE("Setting result to 'PENDING' for asynchronous injection");
4818 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004819 }
4820 }
4821
4822 injectionState->injectionResult = injectionResult;
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004823 mInjectionResultAvailable.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004824 }
4825}
4826
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004827void InputDispatcher::transformMotionEntryForInjectionLocked(
4828 MotionEntry& entry, const ui::Transform& injectedTransform) const {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004829 // Input injection works in the logical display coordinate space, but the input pipeline works
4830 // display space, so we need to transform the injected events accordingly.
4831 const auto it = mDisplayInfos.find(entry.displayId);
4832 if (it == mDisplayInfos.end()) return;
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004833 const auto& transformToDisplay = it->second.transform.inverse() * injectedTransform;
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004834
Prabir Pradhand9a2ebe2022-07-20 19:25:13 +00004835 if (entry.xCursorPosition != AMOTION_EVENT_INVALID_CURSOR_POSITION &&
4836 entry.yCursorPosition != AMOTION_EVENT_INVALID_CURSOR_POSITION) {
4837 const vec2 cursor =
4838 MotionEvent::calculateTransformedXY(entry.source, transformToDisplay,
4839 {entry.xCursorPosition, entry.yCursorPosition});
4840 entry.xCursorPosition = cursor.x;
4841 entry.yCursorPosition = cursor.y;
4842 }
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004843 for (uint32_t i = 0; i < entry.pointerCount; i++) {
Prabir Pradhan8e6ce222022-02-24 09:08:54 -08004844 entry.pointerCoords[i] =
4845 MotionEvent::calculateTransformedCoords(entry.source, transformToDisplay,
4846 entry.pointerCoords[i]);
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004847 }
4848}
4849
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004850void InputDispatcher::incrementPendingForegroundDispatches(EventEntry& entry) {
4851 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004852 if (injectionState) {
4853 injectionState->pendingForegroundDispatches += 1;
4854 }
4855}
4856
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004857void InputDispatcher::decrementPendingForegroundDispatches(EventEntry& entry) {
4858 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004859 if (injectionState) {
4860 injectionState->pendingForegroundDispatches -= 1;
4861
4862 if (injectionState->pendingForegroundDispatches == 0) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004863 mInjectionSyncFinished.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004864 }
4865 }
4866}
4867
chaviw98318de2021-05-19 16:45:23 -05004868const std::vector<sp<WindowInfoHandle>>& InputDispatcher::getWindowHandlesLocked(
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004869 int32_t displayId) const {
chaviw98318de2021-05-19 16:45:23 -05004870 static const std::vector<sp<WindowInfoHandle>> EMPTY_WINDOW_HANDLES;
Vishnu Nairad321cd2020-08-20 16:40:21 -07004871 auto it = mWindowHandlesByDisplay.find(displayId);
4872 return it != mWindowHandlesByDisplay.end() ? it->second : EMPTY_WINDOW_HANDLES;
Arthur Hungb92218b2018-08-14 12:00:21 +08004873}
4874
chaviw98318de2021-05-19 16:45:23 -05004875sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(
chaviwfbe5d9c2018-12-26 12:23:37 -08004876 const sp<IBinder>& windowHandleToken) const {
arthurhungbe737672020-06-24 12:29:21 +08004877 if (windowHandleToken == nullptr) {
4878 return nullptr;
4879 }
4880
Arthur Hungb92218b2018-08-14 12:00:21 +08004881 for (auto& it : mWindowHandlesByDisplay) {
chaviw98318de2021-05-19 16:45:23 -05004882 const std::vector<sp<WindowInfoHandle>>& windowHandles = it.second;
4883 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
chaviwfbe5d9c2018-12-26 12:23:37 -08004884 if (windowHandle->getToken() == windowHandleToken) {
Arthur Hungb92218b2018-08-14 12:00:21 +08004885 return windowHandle;
4886 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004887 }
4888 }
Yi Kong9b14ac62018-07-17 13:48:38 -07004889 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004890}
4891
chaviw98318de2021-05-19 16:45:23 -05004892sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(const sp<IBinder>& windowHandleToken,
4893 int displayId) const {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004894 if (windowHandleToken == nullptr) {
4895 return nullptr;
4896 }
4897
chaviw98318de2021-05-19 16:45:23 -05004898 for (const sp<WindowInfoHandle>& windowHandle : getWindowHandlesLocked(displayId)) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004899 if (windowHandle->getToken() == windowHandleToken) {
4900 return windowHandle;
4901 }
4902 }
4903 return nullptr;
4904}
4905
chaviw98318de2021-05-19 16:45:23 -05004906sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(
4907 const sp<WindowInfoHandle>& windowHandle) const {
Mady Mellor017bcd12020-06-23 19:12:00 +00004908 for (auto& it : mWindowHandlesByDisplay) {
chaviw98318de2021-05-19 16:45:23 -05004909 const std::vector<sp<WindowInfoHandle>>& windowHandles = it.second;
4910 for (const sp<WindowInfoHandle>& handle : windowHandles) {
arthurhungbe737672020-06-24 12:29:21 +08004911 if (handle->getId() == windowHandle->getId() &&
4912 handle->getToken() == windowHandle->getToken()) {
Mady Mellor017bcd12020-06-23 19:12:00 +00004913 if (windowHandle->getInfo()->displayId != it.first) {
4914 ALOGE("Found window %s in display %" PRId32
4915 ", but it should belong to display %" PRId32,
4916 windowHandle->getName().c_str(), it.first,
4917 windowHandle->getInfo()->displayId);
4918 }
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004919 return handle;
Arthur Hungb92218b2018-08-14 12:00:21 +08004920 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004921 }
4922 }
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004923 return nullptr;
4924}
4925
chaviw98318de2021-05-19 16:45:23 -05004926sp<WindowInfoHandle> InputDispatcher::getFocusedWindowHandleLocked(int displayId) const {
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004927 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(displayId);
4928 return getWindowHandleLocked(focusedToken, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004929}
4930
Prabir Pradhan33e3baa2022-12-06 20:30:22 +00004931ui::Transform InputDispatcher::getTransformLocked(int32_t displayId) const {
4932 auto displayInfoIt = mDisplayInfos.find(displayId);
4933 return displayInfoIt != mDisplayInfos.end() ? displayInfoIt->second.transform
4934 : kIdentityTransform;
4935}
4936
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004937bool InputDispatcher::canWindowReceiveMotionLocked(const sp<WindowInfoHandle>& window,
4938 const MotionEntry& motionEntry) const {
4939 const WindowInfo& info = *window->getInfo();
4940
4941 // Skip spy window targets that are not valid for targeted injection.
4942 if (const auto err = verifyTargetedInjection(window, motionEntry); err) {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004943 return false;
4944 }
4945
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004946 if (info.inputConfig.test(WindowInfo::InputConfig::PAUSE_DISPATCHING)) {
4947 ALOGI("Not sending touch event to %s because it is paused", window->getName().c_str());
4948 return false;
4949 }
4950
4951 if (info.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL)) {
4952 ALOGW("Not sending touch gesture to %s because it has config NO_INPUT_CHANNEL",
4953 window->getName().c_str());
4954 return false;
4955 }
4956
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07004957 std::shared_ptr<Connection> connection = getConnectionLocked(window->getToken());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004958 if (connection == nullptr) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004959 ALOGW("Not sending touch to %s because there's no corresponding connection",
4960 window->getName().c_str());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004961 return false;
4962 }
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004963
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004964 if (!connection->responsive) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004965 ALOGW("Not sending touch to %s because it is not responsive", window->getName().c_str());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004966 return false;
4967 }
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004968
4969 // Drop events that can't be trusted due to occlusion
4970 const auto [x, y] = resolveTouchedPosition(motionEntry);
4971 TouchOcclusionInfo occlusionInfo = computeTouchOcclusionInfoLocked(window, x, y);
4972 if (!isTouchTrustedLocked(occlusionInfo)) {
4973 if (DEBUG_TOUCH_OCCLUSION) {
Prabir Pradhan82e081e2022-12-06 09:50:09 +00004974 ALOGD("Stack of obscuring windows during untrusted touch (%.1f, %.1f):", x, y);
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004975 for (const auto& log : occlusionInfo.debugInfo) {
4976 ALOGD("%s", log.c_str());
4977 }
4978 }
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00004979 ALOGW("Dropping untrusted touch event due to %s/%s", occlusionInfo.obscuringPackage.c_str(),
4980 occlusionInfo.obscuringUid.toString().c_str());
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004981 return false;
4982 }
4983
4984 // Drop touch events if requested by input feature
4985 if (shouldDropInput(motionEntry, window)) {
4986 return false;
4987 }
4988
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004989 return true;
4990}
4991
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004992std::shared_ptr<InputChannel> InputDispatcher::getInputChannelLocked(
4993 const sp<IBinder>& token) const {
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00004994 auto connectionIt = mConnectionsByToken.find(token);
4995 if (connectionIt == mConnectionsByToken.end()) {
Robert Carr5c8a0262018-10-03 16:30:44 -07004996 return nullptr;
4997 }
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00004998 return connectionIt->second->inputChannel;
Robert Carr5c8a0262018-10-03 16:30:44 -07004999}
5000
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005001void InputDispatcher::updateWindowHandlesForDisplayLocked(
chaviw98318de2021-05-19 16:45:23 -05005002 const std::vector<sp<WindowInfoHandle>>& windowInfoHandles, int32_t displayId) {
5003 if (windowInfoHandles.empty()) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005004 // Remove all handles on a display if there are no windows left.
5005 mWindowHandlesByDisplay.erase(displayId);
5006 return;
5007 }
5008
5009 // Since we compare the pointer of input window handles across window updates, we need
5010 // to make sure the handle object for the same window stays unchanged across updates.
chaviw98318de2021-05-19 16:45:23 -05005011 const std::vector<sp<WindowInfoHandle>>& oldHandles = getWindowHandlesLocked(displayId);
5012 std::unordered_map<int32_t /*id*/, sp<WindowInfoHandle>> oldHandlesById;
5013 for (const sp<WindowInfoHandle>& handle : oldHandles) {
chaviwaf87b3e2019-10-01 16:59:28 -07005014 oldHandlesById[handle->getId()] = handle;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005015 }
5016
chaviw98318de2021-05-19 16:45:23 -05005017 std::vector<sp<WindowInfoHandle>> newHandles;
5018 for (const sp<WindowInfoHandle>& handle : windowInfoHandles) {
chaviw98318de2021-05-19 16:45:23 -05005019 const WindowInfo* info = handle->getInfo();
Siarhei Vishniakou64452932020-11-06 17:51:32 -06005020 if (getInputChannelLocked(handle->getToken()) == nullptr) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005021 const bool noInputChannel =
Prabir Pradhan51e7db02022-02-07 06:02:57 -08005022 info->inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005023 const bool canReceiveInput =
5024 !info->inputConfig.test(WindowInfo::InputConfig::NOT_TOUCHABLE) ||
5025 !info->inputConfig.test(WindowInfo::InputConfig::NOT_FOCUSABLE);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005026 if (canReceiveInput && !noInputChannel) {
John Recke0710582019-09-26 13:46:12 -07005027 ALOGV("Window handle %s has no registered input channel",
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005028 handle->getName().c_str());
Robert Carr2984b7a2020-04-13 17:06:45 -07005029 continue;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005030 }
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005031 }
5032
5033 if (info->displayId != displayId) {
5034 ALOGE("Window %s updated by wrong display %d, should belong to display %d",
5035 handle->getName().c_str(), displayId, info->displayId);
5036 continue;
5037 }
5038
Robert Carredd13602020-04-13 17:24:34 -07005039 if ((oldHandlesById.find(handle->getId()) != oldHandlesById.end()) &&
5040 (oldHandlesById.at(handle->getId())->getToken() == handle->getToken())) {
chaviw98318de2021-05-19 16:45:23 -05005041 const sp<WindowInfoHandle>& oldHandle = oldHandlesById.at(handle->getId());
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005042 oldHandle->updateFrom(handle);
5043 newHandles.push_back(oldHandle);
5044 } else {
5045 newHandles.push_back(handle);
5046 }
5047 }
5048
5049 // Insert or replace
5050 mWindowHandlesByDisplay[displayId] = newHandles;
5051}
5052
Arthur Hungb92218b2018-08-14 12:00:21 +08005053/**
5054 * Called from InputManagerService, update window handle list by displayId that can receive input.
5055 * A window handle contains information about InputChannel, Touch Region, Types, Focused,...
5056 * If set an empty list, remove all handles from the specific display.
5057 * For focused handle, check if need to change and send a cancel event to previous one.
5058 * For removed handle, check if need to send a cancel event if already in touch.
5059 */
Arthur Hung72d8dc32020-03-28 00:48:39 +00005060void InputDispatcher::setInputWindowsLocked(
chaviw98318de2021-05-19 16:45:23 -05005061 const std::vector<sp<WindowInfoHandle>>& windowInfoHandles, int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005062 if (DEBUG_FOCUS) {
5063 std::string windowList;
chaviw98318de2021-05-19 16:45:23 -05005064 for (const sp<WindowInfoHandle>& iwh : windowInfoHandles) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005065 windowList += iwh->getName() + " ";
5066 }
5067 ALOGD("setInputWindows displayId=%" PRId32 " %s", displayId, windowList.c_str());
5068 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005069
Prabir Pradhand65552b2021-10-07 11:23:50 -07005070 // Check preconditions for new input windows
chaviw98318de2021-05-19 16:45:23 -05005071 for (const sp<WindowInfoHandle>& window : windowInfoHandles) {
Prabir Pradhand65552b2021-10-07 11:23:50 -07005072 const WindowInfo& info = *window->getInfo();
5073
5074 // Ensure all tokens are null if the window has feature NO_INPUT_CHANNEL
Prabir Pradhan51e7db02022-02-07 06:02:57 -08005075 const bool noInputWindow = info.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005076 if (noInputWindow && window->getToken() != nullptr) {
5077 ALOGE("%s has feature NO_INPUT_WINDOW, but a non-null token. Clearing",
5078 window->getName().c_str());
5079 window->releaseChannel();
5080 }
Prabir Pradhand65552b2021-10-07 11:23:50 -07005081
Prabir Pradhan5c85e052021-12-22 02:27:12 -08005082 // Ensure all spy windows are trusted overlays
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005083 LOG_ALWAYS_FATAL_IF(info.isSpy() &&
5084 !info.inputConfig.test(
5085 WindowInfo::InputConfig::TRUSTED_OVERLAY),
Prabir Pradhan5c85e052021-12-22 02:27:12 -08005086 "%s has feature SPY, but is not a trusted overlay.",
5087 window->getName().c_str());
5088
Prabir Pradhand65552b2021-10-07 11:23:50 -07005089 // Ensure all stylus interceptors are trusted overlays
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005090 LOG_ALWAYS_FATAL_IF(info.interceptsStylus() &&
5091 !info.inputConfig.test(
5092 WindowInfo::InputConfig::TRUSTED_OVERLAY),
Prabir Pradhand65552b2021-10-07 11:23:50 -07005093 "%s has feature INTERCEPTS_STYLUS, but is not a trusted overlay.",
5094 window->getName().c_str());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005095 }
5096
Arthur Hung72d8dc32020-03-28 00:48:39 +00005097 // Copy old handles for release if they are no longer present.
chaviw98318de2021-05-19 16:45:23 -05005098 const std::vector<sp<WindowInfoHandle>> oldWindowHandles = getWindowHandlesLocked(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005099
chaviw98318de2021-05-19 16:45:23 -05005100 updateWindowHandlesForDisplayLocked(windowInfoHandles, displayId);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005101
chaviw98318de2021-05-19 16:45:23 -05005102 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Arthur Hung72d8dc32020-03-28 00:48:39 +00005103
Vishnu Nairc519ff72021-01-21 08:23:08 -08005104 std::optional<FocusResolver::FocusChanges> changes =
5105 mFocusResolver.setInputWindows(displayId, windowHandles);
5106 if (changes) {
5107 onFocusChangedLocked(*changes);
Arthur Hung72d8dc32020-03-28 00:48:39 +00005108 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005109
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005110 std::unordered_map<int32_t, TouchState>::iterator stateIt =
5111 mTouchStatesByDisplay.find(displayId);
5112 if (stateIt != mTouchStatesByDisplay.end()) {
5113 TouchState& state = stateIt->second;
Arthur Hung72d8dc32020-03-28 00:48:39 +00005114 for (size_t i = 0; i < state.windows.size();) {
5115 TouchedWindow& touchedWindow = state.windows[i];
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07005116 if (getWindowHandleLocked(touchedWindow.windowHandle) == nullptr) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005117 if (DEBUG_FOCUS) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00005118 ALOGD("Touched window was removed: %s in display %" PRId32,
5119 touchedWindow.windowHandle->getName().c_str(), displayId);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005120 }
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005121 std::shared_ptr<InputChannel> touchedInputChannel =
Arthur Hung72d8dc32020-03-28 00:48:39 +00005122 getInputChannelLocked(touchedWindow.windowHandle->getToken());
5123 if (touchedInputChannel != nullptr) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00005124 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
Arthur Hung72d8dc32020-03-28 00:48:39 +00005125 "touched window was removed");
5126 synthesizeCancelationEventsForInputChannelLocked(touchedInputChannel, options);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00005127 // Since we are about to drop the touch, cancel the events for the wallpaper as
5128 // well.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005129 if (touchedWindow.targetFlags.test(InputTarget::Flags::FOREGROUND) &&
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005130 touchedWindow.windowHandle->getInfo()->inputConfig.test(
5131 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER)) {
Siarhei Vishniakouca205502021-07-16 21:31:58 +00005132 sp<WindowInfoHandle> wallpaper = state.getWallpaperWindow();
Arthur Hungc539dbb2022-12-08 07:45:36 +00005133 synthesizeCancelationEventsForWindowLocked(wallpaper, options);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00005134 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005135 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00005136 state.windows.erase(state.windows.begin() + i);
5137 } else {
5138 ++i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005139 }
5140 }
arthurhungb89ccb02020-12-30 16:19:01 +08005141
arthurhung6d4bed92021-03-17 11:59:33 +08005142 // If drag window is gone, it would receive a cancel event and broadcast the DRAG_END. We
arthurhungb89ccb02020-12-30 16:19:01 +08005143 // could just clear the state here.
Arthur Hung3915c1f2022-05-31 07:17:17 +00005144 if (mDragState && mDragState->dragWindow->getInfo()->displayId == displayId &&
arthurhung6d4bed92021-03-17 11:59:33 +08005145 std::find(windowHandles.begin(), windowHandles.end(), mDragState->dragWindow) ==
arthurhungb89ccb02020-12-30 16:19:01 +08005146 windowHandles.end()) {
Arthur Hung3915c1f2022-05-31 07:17:17 +00005147 ALOGI("Drag window went away: %s", mDragState->dragWindow->getName().c_str());
5148 sendDropWindowCommandLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08005149 mDragState.reset();
arthurhungb89ccb02020-12-30 16:19:01 +08005150 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00005151 }
Arthur Hung25e2af12020-03-26 12:58:37 +00005152
Arthur Hung72d8dc32020-03-28 00:48:39 +00005153 // Release information for windows that are no longer present.
5154 // This ensures that unused input channels are released promptly.
5155 // Otherwise, they might stick around until the window handle is destroyed
5156 // which might not happen until the next GC.
chaviw98318de2021-05-19 16:45:23 -05005157 for (const sp<WindowInfoHandle>& oldWindowHandle : oldWindowHandles) {
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07005158 if (getWindowHandleLocked(oldWindowHandle) == nullptr) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00005159 if (DEBUG_FOCUS) {
5160 ALOGD("Window went away: %s", oldWindowHandle->getName().c_str());
Arthur Hung25e2af12020-03-26 12:58:37 +00005161 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00005162 oldWindowHandle->releaseChannel();
Arthur Hung25e2af12020-03-26 12:58:37 +00005163 }
chaviw291d88a2019-02-14 10:33:58 -08005164 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005165}
5166
5167void InputDispatcher::setFocusedApplication(
Chris Yea209fde2020-07-22 13:54:51 -07005168 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005169 if (DEBUG_FOCUS) {
5170 ALOGD("setFocusedApplication displayId=%" PRId32 " %s", displayId,
5171 inputApplicationHandle ? inputApplicationHandle->getName().c_str() : "<nullptr>");
5172 }
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05005173 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005174 std::scoped_lock _l(mLock);
Vishnu Nair599f1412021-06-21 10:39:58 -07005175 setFocusedApplicationLocked(displayId, inputApplicationHandle);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005176 } // release lock
5177
5178 // Wake up poll loop since it may need to make new input dispatching choices.
5179 mLooper->wake();
5180}
5181
Vishnu Nair599f1412021-06-21 10:39:58 -07005182void InputDispatcher::setFocusedApplicationLocked(
5183 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
5184 std::shared_ptr<InputApplicationHandle> oldFocusedApplicationHandle =
5185 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
5186
5187 if (sharedPointersEqual(oldFocusedApplicationHandle, inputApplicationHandle)) {
5188 return; // This application is already focused. No need to wake up or change anything.
5189 }
5190
5191 // Set the new application handle.
5192 if (inputApplicationHandle != nullptr) {
5193 mFocusedApplicationHandlesByDisplay[displayId] = inputApplicationHandle;
5194 } else {
5195 mFocusedApplicationHandlesByDisplay.erase(displayId);
5196 }
5197
5198 // No matter what the old focused application was, stop waiting on it because it is
5199 // no longer focused.
5200 resetNoFocusedWindowTimeoutLocked();
5201}
5202
Tiger Huang721e26f2018-07-24 22:26:19 +08005203/**
5204 * Sets the focused display, which is responsible for receiving focus-dispatched input events where
5205 * the display not specified.
5206 *
5207 * We track any unreleased events for each window. If a window loses the ability to receive the
5208 * released event, we will send a cancel event to it. So when the focused display is changed, we
5209 * cancel all the unreleased display-unspecified events for the focused window on the old focused
5210 * display. The display-specified events won't be affected.
5211 */
5212void InputDispatcher::setFocusedDisplay(int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005213 if (DEBUG_FOCUS) {
5214 ALOGD("setFocusedDisplay displayId=%" PRId32, displayId);
5215 }
Tiger Huang721e26f2018-07-24 22:26:19 +08005216 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005217 std::scoped_lock _l(mLock);
Tiger Huang721e26f2018-07-24 22:26:19 +08005218
5219 if (mFocusedDisplayId != displayId) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07005220 sp<IBinder> oldFocusedWindowToken =
Vishnu Nairc519ff72021-01-21 08:23:08 -08005221 mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07005222 if (oldFocusedWindowToken != nullptr) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005223 std::shared_ptr<InputChannel> inputChannel =
Vishnu Nairad321cd2020-08-20 16:40:21 -07005224 getInputChannelLocked(oldFocusedWindowToken);
Tiger Huang721e26f2018-07-24 22:26:19 +08005225 if (inputChannel != nullptr) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005226 CancelationOptions
Michael Wrightfb04fd52022-11-24 22:31:11 +00005227 options(CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005228 "The display which contains this window no longer has focus.");
Michael Wright3dd60e22019-03-27 22:06:44 +00005229 options.displayId = ADISPLAY_ID_NONE;
Tiger Huang721e26f2018-07-24 22:26:19 +08005230 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
5231 }
5232 }
5233 mFocusedDisplayId = displayId;
5234
Chris Ye3c2d6f52020-08-09 10:39:48 -07005235 // Find new focused window and validate
Vishnu Nairc519ff72021-01-21 08:23:08 -08005236 sp<IBinder> newFocusedWindowToken = mFocusResolver.getFocusedWindowToken(displayId);
Prabir Pradhancef936d2021-07-21 16:17:52 +00005237 sendFocusChangedCommandLocked(oldFocusedWindowToken, newFocusedWindowToken);
Robert Carrf759f162018-11-13 12:57:11 -08005238
Vishnu Nairad321cd2020-08-20 16:40:21 -07005239 if (newFocusedWindowToken == nullptr) {
Tiger Huang721e26f2018-07-24 22:26:19 +08005240 ALOGW("Focused display #%" PRId32 " does not have a focused window.", displayId);
Vishnu Nairc519ff72021-01-21 08:23:08 -08005241 if (mFocusResolver.hasFocusedWindowTokens()) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07005242 ALOGE("But another display has a focused window\n%s",
Vishnu Nairc519ff72021-01-21 08:23:08 -08005243 mFocusResolver.dumpFocusedWindows().c_str());
Tiger Huang721e26f2018-07-24 22:26:19 +08005244 }
5245 }
5246 }
Tiger Huang721e26f2018-07-24 22:26:19 +08005247 } // release lock
5248
5249 // Wake up poll loop since it may need to make new input dispatching choices.
5250 mLooper->wake();
5251}
5252
Michael Wrightd02c5b62014-02-10 15:10:22 -08005253void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005254 if (DEBUG_FOCUS) {
5255 ALOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
5256 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005257
5258 bool changed;
5259 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005260 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005261
5262 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
5263 if (mDispatchFrozen && !frozen) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005264 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005265 }
5266
5267 if (mDispatchEnabled && !enabled) {
5268 resetAndDropEverythingLocked("dispatcher is being disabled");
5269 }
5270
5271 mDispatchEnabled = enabled;
5272 mDispatchFrozen = frozen;
5273 changed = true;
5274 } else {
5275 changed = false;
5276 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005277 } // release lock
5278
5279 if (changed) {
5280 // Wake up poll loop since it may need to make new input dispatching choices.
5281 mLooper->wake();
5282 }
5283}
5284
5285void InputDispatcher::setInputFilterEnabled(bool enabled) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005286 if (DEBUG_FOCUS) {
5287 ALOGD("setInputFilterEnabled: enabled=%d", enabled);
5288 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005289
5290 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005291 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005292
5293 if (mInputFilterEnabled == enabled) {
5294 return;
5295 }
5296
5297 mInputFilterEnabled = enabled;
5298 resetAndDropEverythingLocked("input filter is being enabled or disabled");
5299 } // release lock
5300
5301 // Wake up poll loop since there might be work to do to drop everything.
5302 mLooper->wake();
5303}
5304
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005305bool InputDispatcher::setInTouchMode(bool inTouchMode, gui::Pid pid, gui::Uid uid,
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00005306 bool hasPermission, int32_t displayId) {
Antonio Kantekf16f2832021-09-28 04:39:20 +00005307 bool needWake = false;
5308 {
5309 std::scoped_lock lock(mLock);
Antonio Kantek15beb512022-06-13 22:35:41 +00005310 ALOGD_IF(DEBUG_TOUCH_MODE,
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005311 "Request to change touch mode to %s (calling pid=%s, uid=%s, "
Antonio Kantek15beb512022-06-13 22:35:41 +00005312 "hasPermission=%s, target displayId=%d, mTouchModePerDisplay[displayId]=%s)",
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005313 toString(inTouchMode), pid.toString().c_str(), uid.toString().c_str(),
5314 toString(hasPermission), displayId,
Antonio Kantek15beb512022-06-13 22:35:41 +00005315 mTouchModePerDisplay.count(displayId) == 0
5316 ? "not set"
5317 : std::to_string(mTouchModePerDisplay[displayId]).c_str());
5318
Antonio Kantek15beb512022-06-13 22:35:41 +00005319 auto touchModeIt = mTouchModePerDisplay.find(displayId);
5320 if (touchModeIt != mTouchModePerDisplay.end() && touchModeIt->second == inTouchMode) {
Antonio Kantekea47acb2021-12-23 12:41:25 -08005321 return false;
Antonio Kantekf16f2832021-09-28 04:39:20 +00005322 }
Antonio Kantekea47acb2021-12-23 12:41:25 -08005323 if (!hasPermission) {
Antonio Kantek48710e42022-03-24 14:19:30 -07005324 if (!focusedWindowIsOwnedByLocked(pid, uid) &&
5325 !recentWindowsAreOwnedByLocked(pid, uid)) {
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005326 ALOGD("Touch mode switch rejected, caller (pid=%s, uid=%s) doesn't own the focused "
Antonio Kantek48710e42022-03-24 14:19:30 -07005327 "window nor none of the previously interacted window",
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005328 pid.toString().c_str(), uid.toString().c_str());
Antonio Kantekea47acb2021-12-23 12:41:25 -08005329 return false;
5330 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00005331 }
Antonio Kantek15beb512022-06-13 22:35:41 +00005332 mTouchModePerDisplay[displayId] = inTouchMode;
5333 auto entry = std::make_unique<TouchModeEntry>(mIdGenerator.nextId(), now(), inTouchMode,
5334 displayId);
Antonio Kantekf16f2832021-09-28 04:39:20 +00005335 needWake = enqueueInboundEventLocked(std::move(entry));
5336 } // release lock
5337
5338 if (needWake) {
5339 mLooper->wake();
5340 }
Antonio Kantekea47acb2021-12-23 12:41:25 -08005341 return true;
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -08005342}
5343
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005344bool InputDispatcher::focusedWindowIsOwnedByLocked(gui::Pid pid, gui::Uid uid) {
Antonio Kantek48710e42022-03-24 14:19:30 -07005345 const sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
5346 if (focusedToken == nullptr) {
5347 return false;
5348 }
5349 sp<WindowInfoHandle> windowHandle = getWindowHandleLocked(focusedToken);
5350 return isWindowOwnedBy(windowHandle, pid, uid);
5351}
5352
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005353bool InputDispatcher::recentWindowsAreOwnedByLocked(gui::Pid pid, gui::Uid uid) {
Antonio Kantek48710e42022-03-24 14:19:30 -07005354 return std::find_if(mInteractionConnectionTokens.begin(), mInteractionConnectionTokens.end(),
5355 [&](const sp<IBinder>& connectionToken) REQUIRES(mLock) {
5356 const sp<WindowInfoHandle> windowHandle =
5357 getWindowHandleLocked(connectionToken);
5358 return isWindowOwnedBy(windowHandle, pid, uid);
5359 }) != mInteractionConnectionTokens.end();
5360}
5361
Bernardo Rufinoea97d182020-08-19 14:43:14 +01005362void InputDispatcher::setMaximumObscuringOpacityForTouch(float opacity) {
5363 if (opacity < 0 || opacity > 1) {
5364 LOG_ALWAYS_FATAL("Maximum obscuring opacity for touch should be >= 0 and <= 1");
5365 return;
5366 }
5367
5368 std::scoped_lock lock(mLock);
5369 mMaximumObscuringOpacityForTouch = opacity;
5370}
5371
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005372std::tuple<TouchState*, TouchedWindow*, int32_t /*displayId*/>
5373InputDispatcher::findTouchStateWindowAndDisplayLocked(const sp<IBinder>& token) {
Arthur Hungabbb9d82021-09-01 14:52:30 +00005374 for (auto& [displayId, state] : mTouchStatesByDisplay) {
5375 for (TouchedWindow& w : state.windows) {
5376 if (w.windowHandle->getToken() == token) {
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005377 return std::make_tuple(&state, &w, displayId);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005378 }
5379 }
5380 }
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005381 return std::make_tuple(nullptr, nullptr, ADISPLAY_ID_DEFAULT);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005382}
5383
arthurhungb89ccb02020-12-30 16:19:01 +08005384bool InputDispatcher::transferTouchFocus(const sp<IBinder>& fromToken, const sp<IBinder>& toToken,
5385 bool isDragDrop) {
chaviwfbe5d9c2018-12-26 12:23:37 -08005386 if (fromToken == toToken) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005387 if (DEBUG_FOCUS) {
5388 ALOGD("Trivial transfer to same window.");
5389 }
chaviwfbe5d9c2018-12-26 12:23:37 -08005390 return true;
5391 }
5392
Michael Wrightd02c5b62014-02-10 15:10:22 -08005393 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005394 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005395
Arthur Hungabbb9d82021-09-01 14:52:30 +00005396 // Find the target touch state and touched window by fromToken.
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005397 auto [state, touchedWindow, displayId] = findTouchStateWindowAndDisplayLocked(fromToken);
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005398
Arthur Hungabbb9d82021-09-01 14:52:30 +00005399 if (state == nullptr || touchedWindow == nullptr) {
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005400 ALOGD("Touch transfer failed because from window is not being touched.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005401 return false;
5402 }
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005403 std::set<int32_t> deviceIds = touchedWindow->getTouchingDeviceIds();
5404 if (deviceIds.size() != 1) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07005405 LOG(INFO) << "Can't transfer touch. Currently touching devices: " << dumpSet(deviceIds)
5406 << " for window: " << touchedWindow->dump();
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005407 return false;
5408 }
5409 const int32_t deviceId = *deviceIds.begin();
Arthur Hungabbb9d82021-09-01 14:52:30 +00005410
Arthur Hungabbb9d82021-09-01 14:52:30 +00005411 sp<WindowInfoHandle> toWindowHandle = getWindowHandleLocked(toToken, displayId);
5412 if (toWindowHandle == nullptr) {
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005413 ALOGW("Cannot transfer touch because to window not found.");
Arthur Hungabbb9d82021-09-01 14:52:30 +00005414 return false;
5415 }
5416
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005417 if (DEBUG_FOCUS) {
5418 ALOGD("transferTouchFocus: fromWindowHandle=%s, toWindowHandle=%s",
Arthur Hungabbb9d82021-09-01 14:52:30 +00005419 touchedWindow->windowHandle->getName().c_str(),
5420 toWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005421 }
5422
Arthur Hungabbb9d82021-09-01 14:52:30 +00005423 // Erase old window.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005424 ftl::Flags<InputTarget::Flags> oldTargetFlags = touchedWindow->targetFlags;
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005425 std::bitset<MAX_POINTER_ID + 1> pointerIds = touchedWindow->getTouchingPointers(deviceId);
Arthur Hungc539dbb2022-12-08 07:45:36 +00005426 sp<WindowInfoHandle> fromWindowHandle = touchedWindow->windowHandle;
Arthur Hungabbb9d82021-09-01 14:52:30 +00005427 state->removeWindowByToken(fromToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005428
Arthur Hungabbb9d82021-09-01 14:52:30 +00005429 // Add new window.
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00005430 nsecs_t downTimeInTarget = now();
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005431 ftl::Flags<InputTarget::Flags> newTargetFlags =
5432 oldTargetFlags & (InputTarget::Flags::SPLIT | InputTarget::Flags::DISPATCH_AS_IS);
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00005433 if (canReceiveForegroundTouches(*toWindowHandle->getInfo())) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005434 newTargetFlags |= InputTarget::Flags::FOREGROUND;
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00005435 }
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005436 state->addOrUpdateWindow(toWindowHandle, newTargetFlags, deviceId, pointerIds,
5437 downTimeInTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005438
Arthur Hungabbb9d82021-09-01 14:52:30 +00005439 // Store the dragging window.
5440 if (isDragDrop) {
Arthur Hungb75c2aa2022-07-15 09:35:36 +00005441 if (pointerIds.count() != 1) {
5442 ALOGW("The drag and drop cannot be started when there is no pointer or more than 1"
5443 " pointer on the window.");
Arthur Hung54745652022-04-20 07:17:41 +00005444 return false;
5445 }
Arthur Hungb75c2aa2022-07-15 09:35:36 +00005446 // Track the pointer id for drag window and generate the drag state.
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08005447 const size_t id = firstMarkedBit(pointerIds);
Arthur Hung54745652022-04-20 07:17:41 +00005448 mDragState = std::make_unique<DragState>(toWindowHandle, id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005449 }
5450
Arthur Hungabbb9d82021-09-01 14:52:30 +00005451 // Synthesize cancel for old window and down for new window.
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07005452 std::shared_ptr<Connection> fromConnection = getConnectionLocked(fromToken);
5453 std::shared_ptr<Connection> toConnection = getConnectionLocked(toToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005454 if (fromConnection != nullptr && toConnection != nullptr) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08005455 fromConnection->inputState.mergePointerStateTo(toConnection->inputState);
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005456 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
5457 "transferring touch from this window to another window");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005458 synthesizeCancelationEventsForConnectionLocked(fromConnection, options);
Arthur Hungc539dbb2022-12-08 07:45:36 +00005459 synthesizePointerDownEventsForConnectionLocked(downTimeInTarget, toConnection,
5460 newTargetFlags);
5461
5462 // Check if the wallpaper window should deliver the corresponding event.
5463 transferWallpaperTouch(oldTargetFlags, newTargetFlags, fromWindowHandle, toWindowHandle,
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005464 *state, deviceId, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005465 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005466 } // release lock
5467
5468 // Wake up poll loop since it may need to make new input dispatching choices.
5469 mLooper->wake();
5470 return true;
5471}
5472
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005473/**
5474 * Get the touched foreground window on the given display.
5475 * Return null if there are no windows touched on that display, or if more than one foreground
5476 * window is being touched.
5477 */
5478sp<WindowInfoHandle> InputDispatcher::findTouchedForegroundWindowLocked(int32_t displayId) const {
5479 auto stateIt = mTouchStatesByDisplay.find(displayId);
5480 if (stateIt == mTouchStatesByDisplay.end()) {
5481 ALOGI("No touch state on display %" PRId32, displayId);
5482 return nullptr;
5483 }
5484
5485 const TouchState& state = stateIt->second;
5486 sp<WindowInfoHandle> touchedForegroundWindow;
5487 // If multiple foreground windows are touched, return nullptr
5488 for (const TouchedWindow& window : state.windows) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005489 if (window.targetFlags.test(InputTarget::Flags::FOREGROUND)) {
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005490 if (touchedForegroundWindow != nullptr) {
5491 ALOGI("Two or more foreground windows: %s and %s",
5492 touchedForegroundWindow->getName().c_str(),
5493 window.windowHandle->getName().c_str());
5494 return nullptr;
5495 }
5496 touchedForegroundWindow = window.windowHandle;
5497 }
5498 }
5499 return touchedForegroundWindow;
5500}
5501
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005502// Binder call
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005503bool InputDispatcher::transferTouch(const sp<IBinder>& destChannelToken, int32_t displayId) {
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005504 sp<IBinder> fromToken;
5505 { // acquire lock
5506 std::scoped_lock _l(mLock);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005507 sp<WindowInfoHandle> toWindowHandle = getWindowHandleLocked(destChannelToken, displayId);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005508 if (toWindowHandle == nullptr) {
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005509 ALOGW("Could not find window associated with token=%p on display %" PRId32,
5510 destChannelToken.get(), displayId);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005511 return false;
5512 }
5513
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005514 sp<WindowInfoHandle> from = findTouchedForegroundWindowLocked(displayId);
5515 if (from == nullptr) {
5516 ALOGE("Could not find a source window in %s for %p", __func__, destChannelToken.get());
5517 return false;
5518 }
5519
5520 fromToken = from->getToken();
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005521 } // release lock
5522
5523 return transferTouchFocus(fromToken, destChannelToken);
5524}
5525
Michael Wrightd02c5b62014-02-10 15:10:22 -08005526void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005527 if (DEBUG_FOCUS) {
5528 ALOGD("Resetting and dropping all events (%s).", reason);
5529 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005530
Michael Wrightfb04fd52022-11-24 22:31:11 +00005531 CancelationOptions options(CancelationOptions::Mode::CANCEL_ALL_EVENTS, reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005532 synthesizeCancelationEventsForAllConnectionsLocked(options);
5533
5534 resetKeyRepeatLocked();
5535 releasePendingEventLocked();
5536 drainInboundQueueLocked();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005537 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005538
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005539 mAnrTracker.clear();
Jeff Brownf086ddb2014-02-11 14:28:48 -08005540 mTouchStatesByDisplay.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005541}
5542
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005543void InputDispatcher::logDispatchStateLocked() const {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005544 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005545 dumpDispatchStateLocked(dump);
5546
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005547 std::istringstream stream(dump);
5548 std::string line;
5549
5550 while (std::getline(stream, line, '\n')) {
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07005551 ALOGI("%s", line.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005552 }
5553}
5554
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005555std::string InputDispatcher::dumpPointerCaptureStateLocked() const {
Prabir Pradhan99987712020-11-10 18:43:05 -08005556 std::string dump;
5557
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005558 dump += StringPrintf(INDENT "Pointer Capture Requested: %s\n",
5559 toString(mCurrentPointerCaptureRequest.enable));
Prabir Pradhan99987712020-11-10 18:43:05 -08005560
5561 std::string windowName = "None";
5562 if (mWindowTokenWithPointerCapture) {
chaviw98318de2021-05-19 16:45:23 -05005563 const sp<WindowInfoHandle> captureWindowHandle =
Prabir Pradhan99987712020-11-10 18:43:05 -08005564 getWindowHandleLocked(mWindowTokenWithPointerCapture);
5565 windowName = captureWindowHandle ? captureWindowHandle->getName().c_str()
5566 : "token has capture without window";
5567 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005568 dump += StringPrintf(INDENT "Current Window with Pointer Capture: %s\n", windowName.c_str());
Prabir Pradhan99987712020-11-10 18:43:05 -08005569
5570 return dump;
5571}
5572
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005573void InputDispatcher::dumpDispatchStateLocked(std::string& dump) const {
Siarhei Vishniakou043a3ec2019-05-01 11:30:46 -07005574 dump += StringPrintf(INDENT "DispatchEnabled: %s\n", toString(mDispatchEnabled));
5575 dump += StringPrintf(INDENT "DispatchFrozen: %s\n", toString(mDispatchFrozen));
5576 dump += StringPrintf(INDENT "InputFilterEnabled: %s\n", toString(mInputFilterEnabled));
Tiger Huang721e26f2018-07-24 22:26:19 +08005577 dump += StringPrintf(INDENT "FocusedDisplayId: %" PRId32 "\n", mFocusedDisplayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005578
Tiger Huang721e26f2018-07-24 22:26:19 +08005579 if (!mFocusedApplicationHandlesByDisplay.empty()) {
5580 dump += StringPrintf(INDENT "FocusedApplications:\n");
5581 for (auto& it : mFocusedApplicationHandlesByDisplay) {
5582 const int32_t displayId = it.first;
Chris Yea209fde2020-07-22 13:54:51 -07005583 const std::shared_ptr<InputApplicationHandle>& applicationHandle = it.second;
Siarhei Vishniakou70622952020-07-30 11:17:23 -05005584 const std::chrono::duration timeout =
5585 applicationHandle->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005586 dump += StringPrintf(INDENT2 "displayId=%" PRId32
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005587 ", name='%s', dispatchingTimeout=%" PRId64 "ms\n",
Siarhei Vishniakou70622952020-07-30 11:17:23 -05005588 displayId, applicationHandle->getName().c_str(), millis(timeout));
Tiger Huang721e26f2018-07-24 22:26:19 +08005589 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005590 } else {
Tiger Huang721e26f2018-07-24 22:26:19 +08005591 dump += StringPrintf(INDENT "FocusedApplications: <none>\n");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005592 }
Tiger Huang721e26f2018-07-24 22:26:19 +08005593
Vishnu Nairc519ff72021-01-21 08:23:08 -08005594 dump += mFocusResolver.dump();
Prabir Pradhan99987712020-11-10 18:43:05 -08005595 dump += dumpPointerCaptureStateLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005596
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005597 if (!mTouchStatesByDisplay.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005598 dump += StringPrintf(INDENT "TouchStatesByDisplay:\n");
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005599 for (const auto& [displayId, state] : mTouchStatesByDisplay) {
Siarhei Vishniakou6e1e9872022-11-08 17:51:35 -08005600 std::string touchStateDump = addLinePrefix(state.dump(), INDENT2);
5601 dump += INDENT2 + std::to_string(displayId) + " : " + touchStateDump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005602 }
5603 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005604 dump += INDENT "TouchStates: <no displays touched>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005605 }
5606
arthurhung6d4bed92021-03-17 11:59:33 +08005607 if (mDragState) {
5608 dump += StringPrintf(INDENT "DragState:\n");
5609 mDragState->dump(dump, INDENT2);
5610 }
5611
Arthur Hungb92218b2018-08-14 12:00:21 +08005612 if (!mWindowHandlesByDisplay.empty()) {
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005613 for (const auto& [displayId, windowHandles] : mWindowHandlesByDisplay) {
5614 dump += StringPrintf(INDENT "Display: %" PRId32 "\n", displayId);
5615 if (const auto& it = mDisplayInfos.find(displayId); it != mDisplayInfos.end()) {
5616 const auto& displayInfo = it->second;
5617 dump += StringPrintf(INDENT2 "logicalSize=%dx%d\n", displayInfo.logicalWidth,
5618 displayInfo.logicalHeight);
5619 displayInfo.transform.dump(dump, "transform", INDENT4);
5620 } else {
5621 dump += INDENT2 "No DisplayInfo found!\n";
5622 }
5623
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08005624 if (!windowHandles.empty()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08005625 dump += INDENT2 "Windows:\n";
5626 for (size_t i = 0; i < windowHandles.size(); i++) {
chaviw98318de2021-05-19 16:45:23 -05005627 const sp<WindowInfoHandle>& windowHandle = windowHandles[i];
5628 const WindowInfo* windowInfo = windowHandle->getInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005629
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00005630 dump += StringPrintf(INDENT3 "%zu: name='%s', id=%" PRId32 ", displayId=%d, "
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005631 "inputConfig=%s, alpha=%.2f, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005632 "frame=[%d,%d][%d,%d], globalScale=%f, "
Bernardo Rufino49d99e42021-01-18 15:16:59 +00005633 "applicationInfo.name=%s, "
5634 "applicationInfo.token=%s, "
chaviw1ff3d1e2020-07-01 15:53:47 -07005635 "touchableRegion=",
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00005636 i, windowInfo->name.c_str(), windowInfo->id,
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005637 windowInfo->displayId,
5638 windowInfo->inputConfig.string().c_str(),
Chavi Weingarten7f019192023-08-08 20:39:01 +00005639 windowInfo->alpha, windowInfo->frame.left,
5640 windowInfo->frame.top, windowInfo->frame.right,
5641 windowInfo->frame.bottom, windowInfo->globalScaleFactor,
Bernardo Rufino49d99e42021-01-18 15:16:59 +00005642 windowInfo->applicationInfo.name.c_str(),
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07005643 binderToString(windowInfo->applicationInfo.token).c_str());
Bernardo Rufino53fc31e2020-11-03 11:01:07 +00005644 dump += dumpRegion(windowInfo->touchableRegion);
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005645 dump += StringPrintf(", ownerPid=%s, ownerUid=%s, dispatchingTimeout=%" PRId64
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005646 "ms, hasToken=%s, "
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005647 "touchOcclusionMode=%s\n",
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005648 windowInfo->ownerPid.toString().c_str(),
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00005649 windowInfo->ownerUid.toString().c_str(),
Bernardo Rufinoc2f1fad2020-11-04 17:30:57 +00005650 millis(windowInfo->dispatchingTimeout),
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07005651 binderToString(windowInfo->token).c_str(),
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005652 toString(windowInfo->touchOcclusionMode).c_str());
chaviw85b44202020-07-24 11:46:21 -07005653 windowInfo->transform.dump(dump, "transform", INDENT4);
Arthur Hungb92218b2018-08-14 12:00:21 +08005654 }
5655 } else {
5656 dump += INDENT2 "Windows: <none>\n";
5657 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005658 }
5659 } else {
Arthur Hungb92218b2018-08-14 12:00:21 +08005660 dump += INDENT "Displays: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005661 }
5662
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005663 if (!mGlobalMonitorsByDisplay.empty()) {
5664 for (const auto& [displayId, monitors] : mGlobalMonitorsByDisplay) {
5665 dump += StringPrintf(INDENT "Global monitors on display %d:\n", displayId);
Michael Wright3dd60e22019-03-27 22:06:44 +00005666 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005667 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005668 } else {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005669 dump += INDENT "Global Monitors: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005670 }
5671
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005672 const nsecs_t currentTime = now();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005673
5674 // Dump recently dispatched or dropped events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005675 if (!mRecentQueue.empty()) {
5676 dump += StringPrintf(INDENT "RecentQueue: length=%zu\n", mRecentQueue.size());
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005677 for (const std::shared_ptr<EventEntry>& entry : mRecentQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005678 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005679 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005680 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005681 }
5682 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005683 dump += INDENT "RecentQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005684 }
5685
5686 // Dump event currently being dispatched.
5687 if (mPendingEvent) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005688 dump += INDENT "PendingEvent:\n";
5689 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005690 dump += mPendingEvent->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005691 dump += StringPrintf(", age=%" PRId64 "ms\n",
5692 ns2ms(currentTime - mPendingEvent->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005693 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005694 dump += INDENT "PendingEvent: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005695 }
5696
5697 // Dump inbound events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005698 if (!mInboundQueue.empty()) {
5699 dump += StringPrintf(INDENT "InboundQueue: length=%zu\n", mInboundQueue.size());
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005700 for (const std::shared_ptr<EventEntry>& entry : mInboundQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005701 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005702 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005703 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005704 }
5705 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005706 dump += INDENT "InboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005707 }
5708
Prabir Pradhancef936d2021-07-21 16:17:52 +00005709 if (!mCommandQueue.empty()) {
5710 dump += StringPrintf(INDENT "CommandQueue: size=%zu\n", mCommandQueue.size());
5711 } else {
5712 dump += INDENT "CommandQueue: <empty>\n";
5713 }
5714
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005715 if (!mConnectionsByToken.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005716 dump += INDENT "Connections:\n";
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005717 for (const auto& [token, connection] : mConnectionsByToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005718 dump += StringPrintf(INDENT2 "%i: channelName='%s', windowName='%s', "
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005719 "status=%s, monitor=%s, responsive=%s\n",
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005720 connection->inputChannel->getFd().get(),
5721 connection->getInputChannelName().c_str(),
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08005722 connection->getWindowName().c_str(),
5723 ftl::enum_string(connection->status).c_str(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005724 toString(connection->monitor), toString(connection->responsive));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005725
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005726 if (!connection->outboundQueue.empty()) {
5727 dump += StringPrintf(INDENT3 "OutboundQueue: length=%zu\n",
5728 connection->outboundQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005729 dump += dumpQueue(connection->outboundQueue, currentTime);
5730
Michael Wrightd02c5b62014-02-10 15:10:22 -08005731 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005732 dump += INDENT3 "OutboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005733 }
5734
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005735 if (!connection->waitQueue.empty()) {
5736 dump += StringPrintf(INDENT3 "WaitQueue: length=%zu\n",
5737 connection->waitQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005738 dump += dumpQueue(connection->waitQueue, currentTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005739 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005740 dump += INDENT3 "WaitQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005741 }
Siarhei Vishniakoud38a1e02023-07-18 11:55:17 -07005742 std::stringstream inputStateDump;
5743 inputStateDump << connection->inputState;
5744 if (!isEmpty(inputStateDump)) {
5745 dump += INDENT3 "InputState: ";
5746 dump += inputStateDump.str() + "\n";
5747 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005748 }
5749 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005750 dump += INDENT "Connections: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005751 }
5752
5753 if (isAppSwitchPendingLocked()) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005754 dump += StringPrintf(INDENT "AppSwitch: pending, due in %" PRId64 "ms\n",
5755 ns2ms(mAppSwitchDueTime - now()));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005756 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005757 dump += INDENT "AppSwitch: not pending\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005758 }
5759
Antonio Kantek15beb512022-06-13 22:35:41 +00005760 if (!mTouchModePerDisplay.empty()) {
5761 dump += INDENT "TouchModePerDisplay:\n";
5762 for (const auto& [displayId, touchMode] : mTouchModePerDisplay) {
5763 dump += StringPrintf(INDENT2 "Display: %" PRId32 " TouchMode: %s\n", displayId,
5764 std::to_string(touchMode).c_str());
5765 }
5766 } else {
5767 dump += INDENT "TouchModePerDisplay: <none>\n";
5768 }
5769
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005770 dump += INDENT "Configuration:\n";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005771 dump += StringPrintf(INDENT2 "KeyRepeatDelay: %" PRId64 "ms\n", ns2ms(mConfig.keyRepeatDelay));
5772 dump += StringPrintf(INDENT2 "KeyRepeatTimeout: %" PRId64 "ms\n",
5773 ns2ms(mConfig.keyRepeatTimeout));
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00005774 dump += mLatencyTracker.dump(INDENT2);
Siarhei Vishniakoua04181f2021-03-26 05:56:49 +00005775 dump += mLatencyAggregator.dump(INDENT2);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005776}
5777
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005778void InputDispatcher::dumpMonitors(std::string& dump, const std::vector<Monitor>& monitors) const {
Michael Wright3dd60e22019-03-27 22:06:44 +00005779 const size_t numMonitors = monitors.size();
5780 for (size_t i = 0; i < numMonitors; i++) {
5781 const Monitor& monitor = monitors[i];
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005782 const std::shared_ptr<InputChannel>& channel = monitor.inputChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005783 dump += StringPrintf(INDENT2 "%zu: '%s', ", i, channel->getName().c_str());
5784 dump += "\n";
5785 }
5786}
5787
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005788class LooperEventCallback : public LooperCallback {
5789public:
5790 LooperEventCallback(std::function<int(int events)> callback) : mCallback(callback) {}
5791 int handleEvent(int /*fd*/, int events, void* /*data*/) override { return mCallback(events); }
5792
5793private:
5794 std::function<int(int events)> mCallback;
5795};
5796
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005797Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputChannel(const std::string& name) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00005798 if (DEBUG_CHANNEL_CREATION) {
5799 ALOGD("channel '%s' ~ createInputChannel", name.c_str());
5800 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005801
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005802 std::unique_ptr<InputChannel> serverChannel;
Garfield Tan15601662020-09-22 15:32:38 -07005803 std::unique_ptr<InputChannel> clientChannel;
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005804 status_t result = InputChannel::openInputChannelPair(name, serverChannel, clientChannel);
Garfield Tan15601662020-09-22 15:32:38 -07005805
5806 if (result) {
5807 return base::Error(result) << "Failed to open input channel pair with name " << name;
5808 }
5809
Michael Wrightd02c5b62014-02-10 15:10:22 -08005810 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005811 std::scoped_lock _l(mLock);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005812 const sp<IBinder>& token = serverChannel->getConnectionToken();
Garfield Tan15601662020-09-22 15:32:38 -07005813 int fd = serverChannel->getFd();
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07005814 std::shared_ptr<Connection> connection =
5815 std::make_shared<Connection>(std::move(serverChannel), /*monitor=*/false,
5816 mIdGenerator);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005817
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005818 if (mConnectionsByToken.find(token) != mConnectionsByToken.end()) {
5819 ALOGE("Created a new connection, but the token %p is already known", token.get());
5820 }
5821 mConnectionsByToken.emplace(token, connection);
5822
5823 std::function<int(int events)> callback = std::bind(&InputDispatcher::handleReceiveCallback,
5824 this, std::placeholders::_1, token);
5825
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005826 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, sp<LooperEventCallback>::make(callback),
5827 nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005828 } // release lock
5829
5830 // Wake the looper because some connections have changed.
5831 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07005832 return clientChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005833}
5834
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005835Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputMonitor(int32_t displayId,
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005836 const std::string& name,
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005837 gui::Pid pid) {
Garfield Tan15601662020-09-22 15:32:38 -07005838 std::shared_ptr<InputChannel> serverChannel;
5839 std::unique_ptr<InputChannel> clientChannel;
5840 status_t result = openInputChannelPair(name, serverChannel, clientChannel);
5841 if (result) {
5842 return base::Error(result) << "Failed to open input channel pair with name " << name;
5843 }
5844
Michael Wright3dd60e22019-03-27 22:06:44 +00005845 { // acquire lock
5846 std::scoped_lock _l(mLock);
5847
5848 if (displayId < 0) {
Garfield Tan15601662020-09-22 15:32:38 -07005849 return base::Error(BAD_VALUE) << "Attempted to create input monitor with name " << name
5850 << " without a specified display.";
Michael Wright3dd60e22019-03-27 22:06:44 +00005851 }
5852
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07005853 std::shared_ptr<Connection> connection =
5854 std::make_shared<Connection>(serverChannel, /*monitor=*/true, mIdGenerator);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005855 const sp<IBinder>& token = serverChannel->getConnectionToken();
Garfield Tan15601662020-09-22 15:32:38 -07005856 const int fd = serverChannel->getFd();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005857
5858 if (mConnectionsByToken.find(token) != mConnectionsByToken.end()) {
5859 ALOGE("Created a new connection, but the token %p is already known", token.get());
5860 }
5861 mConnectionsByToken.emplace(token, connection);
5862 std::function<int(int events)> callback = std::bind(&InputDispatcher::handleReceiveCallback,
5863 this, std::placeholders::_1, token);
Michael Wright3dd60e22019-03-27 22:06:44 +00005864
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005865 mGlobalMonitorsByDisplay[displayId].emplace_back(serverChannel, pid);
Michael Wright3dd60e22019-03-27 22:06:44 +00005866
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005867 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, sp<LooperEventCallback>::make(callback),
5868 nullptr);
Michael Wright3dd60e22019-03-27 22:06:44 +00005869 }
Garfield Tan15601662020-09-22 15:32:38 -07005870
Michael Wright3dd60e22019-03-27 22:06:44 +00005871 // Wake the looper because some connections have changed.
5872 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07005873 return clientChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005874}
5875
Garfield Tan15601662020-09-22 15:32:38 -07005876status_t InputDispatcher::removeInputChannel(const sp<IBinder>& connectionToken) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005877 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005878 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005879
Harry Cutts33476232023-01-30 19:57:29 +00005880 status_t status = removeInputChannelLocked(connectionToken, /*notify=*/false);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005881 if (status) {
5882 return status;
5883 }
5884 } // release lock
5885
5886 // Wake the poll loop because removing the connection may have changed the current
5887 // synchronization state.
5888 mLooper->wake();
5889 return OK;
5890}
5891
Garfield Tan15601662020-09-22 15:32:38 -07005892status_t InputDispatcher::removeInputChannelLocked(const sp<IBinder>& connectionToken,
5893 bool notify) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07005894 std::shared_ptr<Connection> connection = getConnectionLocked(connectionToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005895 if (connection == nullptr) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005896 // Connection can be removed via socket hang up or an explicit call to 'removeInputChannel'
Michael Wrightd02c5b62014-02-10 15:10:22 -08005897 return BAD_VALUE;
5898 }
5899
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005900 removeConnectionLocked(connection);
Robert Carr5c8a0262018-10-03 16:30:44 -07005901
Michael Wrightd02c5b62014-02-10 15:10:22 -08005902 if (connection->monitor) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005903 removeMonitorChannelLocked(connectionToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005904 }
5905
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005906 mLooper->removeFd(connection->inputChannel->getFd());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005907
5908 nsecs_t currentTime = now();
5909 abortBrokenDispatchCycleLocked(currentTime, connection, notify);
5910
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08005911 connection->status = Connection::Status::ZOMBIE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005912 return OK;
5913}
5914
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005915void InputDispatcher::removeMonitorChannelLocked(const sp<IBinder>& connectionToken) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005916 for (auto it = mGlobalMonitorsByDisplay.begin(); it != mGlobalMonitorsByDisplay.end();) {
5917 auto& [displayId, monitors] = *it;
5918 std::erase_if(monitors, [connectionToken](const Monitor& monitor) {
5919 return monitor.inputChannel->getConnectionToken() == connectionToken;
5920 });
Michael Wright3dd60e22019-03-27 22:06:44 +00005921
Michael Wright3dd60e22019-03-27 22:06:44 +00005922 if (monitors.empty()) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005923 it = mGlobalMonitorsByDisplay.erase(it);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005924 } else {
5925 ++it;
5926 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005927 }
5928}
5929
Michael Wright3dd60e22019-03-27 22:06:44 +00005930status_t InputDispatcher::pilferPointers(const sp<IBinder>& token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005931 std::scoped_lock _l(mLock);
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00005932 return pilferPointersLocked(token);
5933}
Michael Wright3dd60e22019-03-27 22:06:44 +00005934
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00005935status_t InputDispatcher::pilferPointersLocked(const sp<IBinder>& token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005936 const std::shared_ptr<InputChannel> requestingChannel = getInputChannelLocked(token);
5937 if (!requestingChannel) {
Siarhei Vishniakou8384e0d2023-09-18 18:48:27 -07005938 LOG(WARNING)
5939 << "Attempted to pilfer pointers from an un-registered channel or invalid token";
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005940 return BAD_VALUE;
Michael Wright3dd60e22019-03-27 22:06:44 +00005941 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005942
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005943 auto [statePtr, windowPtr, displayId] = findTouchStateWindowAndDisplayLocked(token);
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005944 if (statePtr == nullptr || windowPtr == nullptr) {
Siarhei Vishniakou8384e0d2023-09-18 18:48:27 -07005945 LOG(WARNING)
5946 << "Attempted to pilfer points from a channel without any on-going pointer streams."
5947 " Ignoring.";
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005948 return BAD_VALUE;
5949 }
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005950 std::set<int32_t> deviceIds = windowPtr->getTouchingDeviceIds();
5951 if (deviceIds.size() != 1) {
5952 LOG(WARNING) << "Can't pilfer. Currently touching devices: " << dumpSet(deviceIds)
5953 << " in window: " << windowPtr->dump();
5954 return BAD_VALUE;
5955 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005956
Siarhei Vishniakou8384e0d2023-09-18 18:48:27 -07005957 for (const DeviceId deviceId : deviceIds) {
5958 TouchState& state = *statePtr;
5959 TouchedWindow& window = *windowPtr;
5960 // Send cancel events to all the input channels we're stealing from.
5961 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
5962 "input channel stole pointer stream");
5963 options.deviceId = deviceId;
5964 options.displayId = displayId;
5965 std::bitset<MAX_POINTER_ID + 1> pointerIds = window.getTouchingPointers(deviceId);
5966 options.pointerIds = pointerIds;
5967 std::string canceledWindows;
5968 for (const TouchedWindow& w : state.windows) {
5969 const std::shared_ptr<InputChannel> channel =
5970 getInputChannelLocked(w.windowHandle->getToken());
5971 if (channel != nullptr && channel->getConnectionToken() != token) {
5972 synthesizeCancelationEventsForInputChannelLocked(channel, options);
5973 canceledWindows += canceledWindows.empty() ? "[" : ", ";
5974 canceledWindows += channel->getName();
5975 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005976 }
Siarhei Vishniakou8384e0d2023-09-18 18:48:27 -07005977 canceledWindows += canceledWindows.empty() ? "[]" : "]";
5978 LOG(INFO) << "Channel " << requestingChannel->getName()
5979 << " is stealing input gesture for device " << deviceId << " from "
5980 << canceledWindows;
5981
5982 // Prevent the gesture from being sent to any other windows.
5983 // This only blocks relevant pointers to be sent to other windows
5984 window.addPilferingPointers(deviceId, pointerIds);
5985
5986 state.cancelPointersForWindowsExcept(deviceId, pointerIds, token);
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005987 }
Michael Wright3dd60e22019-03-27 22:06:44 +00005988 return OK;
5989}
5990
Prabir Pradhan99987712020-11-10 18:43:05 -08005991void InputDispatcher::requestPointerCapture(const sp<IBinder>& windowToken, bool enabled) {
5992 { // acquire lock
5993 std::scoped_lock _l(mLock);
5994 if (DEBUG_FOCUS) {
chaviw98318de2021-05-19 16:45:23 -05005995 const sp<WindowInfoHandle> windowHandle = getWindowHandleLocked(windowToken);
Prabir Pradhan99987712020-11-10 18:43:05 -08005996 ALOGI("Request to %s Pointer Capture from: %s.", enabled ? "enable" : "disable",
5997 windowHandle != nullptr ? windowHandle->getName().c_str()
5998 : "token without window");
5999 }
6000
Vishnu Nairc519ff72021-01-21 08:23:08 -08006001 const sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Prabir Pradhan99987712020-11-10 18:43:05 -08006002 if (focusedToken != windowToken) {
6003 ALOGW("Ignoring request to %s Pointer Capture: window does not have focus.",
6004 enabled ? "enable" : "disable");
6005 return;
6006 }
6007
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006008 if (enabled == mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006009 ALOGW("Ignoring request to %s Pointer Capture: "
6010 "window has %s requested pointer capture.",
6011 enabled ? "enable" : "disable", enabled ? "already" : "not");
6012 return;
6013 }
6014
Christine Franksb768bb42021-11-29 12:11:31 -08006015 if (enabled) {
6016 if (std::find(mIneligibleDisplaysForPointerCapture.begin(),
6017 mIneligibleDisplaysForPointerCapture.end(),
6018 mFocusedDisplayId) != mIneligibleDisplaysForPointerCapture.end()) {
6019 ALOGW("Ignoring request to enable Pointer Capture: display is not eligible");
6020 return;
6021 }
6022 }
6023
Prabir Pradhan99987712020-11-10 18:43:05 -08006024 setPointerCaptureLocked(enabled);
6025 } // release lock
6026
6027 // Wake the thread to process command entries.
6028 mLooper->wake();
6029}
6030
Christine Franksb768bb42021-11-29 12:11:31 -08006031void InputDispatcher::setDisplayEligibilityForPointerCapture(int32_t displayId, bool isEligible) {
6032 { // acquire lock
6033 std::scoped_lock _l(mLock);
6034 std::erase(mIneligibleDisplaysForPointerCapture, displayId);
6035 if (!isEligible) {
6036 mIneligibleDisplaysForPointerCapture.push_back(displayId);
6037 }
6038 } // release lock
6039}
6040
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00006041std::optional<gui::Pid> InputDispatcher::findMonitorPidByTokenLocked(const sp<IBinder>& token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006042 for (const auto& [_, monitors] : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00006043 for (const Monitor& monitor : monitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07006044 if (monitor.inputChannel->getConnectionToken() == token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006045 return monitor.pid;
Michael Wright3dd60e22019-03-27 22:06:44 +00006046 }
6047 }
6048 }
6049 return std::nullopt;
6050}
6051
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006052std::shared_ptr<Connection> InputDispatcher::getConnectionLocked(
6053 const sp<IBinder>& inputConnectionToken) const {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07006054 if (inputConnectionToken == nullptr) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07006055 return nullptr;
Arthur Hung3b413f22018-10-26 18:05:34 +08006056 }
6057
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00006058 for (const auto& [token, connection] : mConnectionsByToken) {
6059 if (token == inputConnectionToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07006060 return connection;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006061 }
6062 }
Robert Carr4e670e52018-08-15 13:26:12 -07006063
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07006064 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006065}
6066
Siarhei Vishniakouad991402020-10-28 11:40:09 -05006067std::string InputDispatcher::getConnectionNameLocked(const sp<IBinder>& connectionToken) const {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006068 std::shared_ptr<Connection> connection = getConnectionLocked(connectionToken);
Siarhei Vishniakouad991402020-10-28 11:40:09 -05006069 if (connection == nullptr) {
6070 return "<nullptr>";
6071 }
6072 return connection->getInputChannelName();
6073}
6074
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006075void InputDispatcher::removeConnectionLocked(const std::shared_ptr<Connection>& connection) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006076 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00006077 mConnectionsByToken.erase(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07006078}
6079
Prabir Pradhancef936d2021-07-21 16:17:52 +00006080void InputDispatcher::doDispatchCycleFinishedCommand(nsecs_t finishTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006081 const std::shared_ptr<Connection>& connection,
6082 uint32_t seq, bool handled,
6083 nsecs_t consumeTime) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006084 // Handle post-event policy actions.
Prabir Pradhancef936d2021-07-21 16:17:52 +00006085 bool restartEvent;
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006086
6087 { // Start critical section
6088 auto dispatchEntryIt =
6089 std::find_if(connection->waitQueue.begin(), connection->waitQueue.end(),
6090 [seq](auto& e) { return e->seq == seq; });
6091 if (dispatchEntryIt == connection->waitQueue.end()) {
6092 return;
6093 }
6094
6095 DispatchEntry& dispatchEntry = **dispatchEntryIt;
6096
6097 const nsecs_t eventDuration = finishTime - dispatchEntry.deliveryTime;
6098 if (eventDuration > SLOW_EVENT_PROCESSING_WARNING_TIMEOUT) {
6099 ALOGI("%s spent %" PRId64 "ms processing %s", connection->getWindowName().c_str(),
6100 ns2ms(eventDuration), dispatchEntry.eventEntry->getDescription().c_str());
6101 }
6102 if (shouldReportFinishedEvent(dispatchEntry, *connection)) {
6103 mLatencyTracker.trackFinishedEvent(dispatchEntry.eventEntry->id,
6104 connection->inputChannel->getConnectionToken(),
6105 dispatchEntry.deliveryTime, consumeTime, finishTime);
6106 }
6107
6108 if (dispatchEntry.eventEntry->type == EventEntry::Type::KEY) {
6109 KeyEntry& keyEntry = static_cast<KeyEntry&>(*(dispatchEntry.eventEntry));
6110 restartEvent =
6111 afterKeyEventLockedInterruptable(connection, dispatchEntry, keyEntry, handled);
6112 } else if (dispatchEntry.eventEntry->type == EventEntry::Type::MOTION) {
6113 MotionEntry& motionEntry = static_cast<MotionEntry&>(*(dispatchEntry.eventEntry));
6114 restartEvent = afterMotionEventLockedInterruptable(connection, dispatchEntry,
6115 motionEntry, handled);
6116 } else {
6117 restartEvent = false;
6118 }
6119 } // End critical section: The -LockedInterruptable methods may have released the lock.
Prabir Pradhancef936d2021-07-21 16:17:52 +00006120
6121 // Dequeue the event and start the next cycle.
6122 // Because the lock might have been released, it is possible that the
6123 // contents of the wait queue to have been drained, so we need to double-check
6124 // a few things.
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006125 auto entryIt = std::find_if(connection->waitQueue.begin(), connection->waitQueue.end(),
6126 [seq](auto& e) { return e->seq == seq; });
6127 if (entryIt != connection->waitQueue.end()) {
6128 std::unique_ptr<DispatchEntry> dispatchEntry = std::move(*entryIt);
6129 connection->waitQueue.erase(entryIt);
6130
Prabir Pradhancef936d2021-07-21 16:17:52 +00006131 const sp<IBinder>& connectionToken = connection->inputChannel->getConnectionToken();
6132 mAnrTracker.erase(dispatchEntry->timeoutTime, connectionToken);
6133 if (!connection->responsive) {
6134 connection->responsive = isConnectionResponsive(*connection);
6135 if (connection->responsive) {
6136 // The connection was unresponsive, and now it's responsive.
6137 processConnectionResponsiveLocked(*connection);
6138 }
6139 }
6140 traceWaitQueueLength(*connection);
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08006141 if (restartEvent && connection->status == Connection::Status::NORMAL) {
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006142 connection->outboundQueue.emplace_front(std::move(dispatchEntry));
Prabir Pradhancef936d2021-07-21 16:17:52 +00006143 traceOutboundQueueLength(*connection);
6144 } else {
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006145 releaseDispatchEntry(std::move(dispatchEntry));
Prabir Pradhancef936d2021-07-21 16:17:52 +00006146 }
6147 }
6148
6149 // Start the next dispatch cycle for this connection.
6150 startDispatchCycleLocked(now(), connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006151}
6152
Prabir Pradhancef936d2021-07-21 16:17:52 +00006153void InputDispatcher::sendFocusChangedCommandLocked(const sp<IBinder>& oldToken,
6154 const sp<IBinder>& newToken) {
6155 auto command = [this, oldToken, newToken]() REQUIRES(mLock) {
6156 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00006157 mPolicy.notifyFocusChanged(oldToken, newToken);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006158 };
6159 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08006160}
6161
Prabir Pradhancef936d2021-07-21 16:17:52 +00006162void InputDispatcher::sendDropWindowCommandLocked(const sp<IBinder>& token, float x, float y) {
6163 auto command = [this, token, x, y]() REQUIRES(mLock) {
6164 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00006165 mPolicy.notifyDropWindow(token, x, y);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006166 };
6167 postCommandLocked(std::move(command));
Robert Carrf759f162018-11-13 12:57:11 -08006168}
6169
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006170void InputDispatcher::onAnrLocked(const std::shared_ptr<Connection>& connection) {
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006171 if (connection == nullptr) {
6172 LOG_ALWAYS_FATAL("Caller must check for nullness");
6173 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006174 // Since we are allowing the policy to extend the timeout, maybe the waitQueue
6175 // is already healthy again. Don't raise ANR in this situation
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006176 if (connection->waitQueue.empty()) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006177 ALOGI("Not raising ANR because the connection %s has recovered",
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006178 connection->inputChannel->getName().c_str());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006179 return;
6180 }
6181 /**
6182 * The "oldestEntry" is the entry that was first sent to the application. That entry, however,
6183 * may not be the one that caused the timeout to occur. One possibility is that window timeout
6184 * has changed. This could cause newer entries to time out before the already dispatched
6185 * entries. In that situation, the newest entries caused ANR. But in all likelihood, the app
6186 * processes the events linearly. So providing information about the oldest entry seems to be
6187 * most useful.
6188 */
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006189 DispatchEntry& oldestEntry = *connection->waitQueue.front();
6190 const nsecs_t currentWait = now() - oldestEntry.deliveryTime;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006191 std::string reason =
6192 android::base::StringPrintf("%s is not responding. Waited %" PRId64 "ms for %s",
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006193 connection->inputChannel->getName().c_str(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006194 ns2ms(currentWait),
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006195 oldestEntry.eventEntry->getDescription().c_str());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006196 sp<IBinder> connectionToken = connection->inputChannel->getConnectionToken();
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -06006197 updateLastAnrStateLocked(getWindowHandleLocked(connectionToken), reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006198
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006199 processConnectionUnresponsiveLocked(*connection, std::move(reason));
6200
6201 // Stop waking up for events on this connection, it is already unresponsive
6202 cancelEventsForAnrLocked(connection);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006203}
6204
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05006205void InputDispatcher::onAnrLocked(std::shared_ptr<InputApplicationHandle> application) {
6206 std::string reason =
6207 StringPrintf("%s does not have a focused window", application->getName().c_str());
6208 updateLastAnrStateLocked(*application, reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006209
Yabin Cui8eb9c552023-06-08 18:05:07 +00006210 auto command = [this, app = std::move(application)]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006211 scoped_unlock unlock(mLock);
Yabin Cuiced952f2023-06-09 21:12:51 +00006212 mPolicy.notifyNoFocusedWindowAnr(app);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006213 };
6214 postCommandLocked(std::move(command));
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00006215}
6216
chaviw98318de2021-05-19 16:45:23 -05006217void InputDispatcher::updateLastAnrStateLocked(const sp<WindowInfoHandle>& window,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006218 const std::string& reason) {
6219 const std::string windowLabel = getApplicationWindowLabel(nullptr, window);
6220 updateLastAnrStateLocked(windowLabel, reason);
6221}
6222
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05006223void InputDispatcher::updateLastAnrStateLocked(const InputApplicationHandle& application,
6224 const std::string& reason) {
6225 const std::string windowLabel = getApplicationWindowLabel(&application, nullptr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006226 updateLastAnrStateLocked(windowLabel, reason);
6227}
6228
6229void InputDispatcher::updateLastAnrStateLocked(const std::string& windowLabel,
6230 const std::string& reason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006231 // Capture a record of the InputDispatcher state at the time of the ANR.
Yi Kong9b14ac62018-07-17 13:48:38 -07006232 time_t t = time(nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006233 struct tm tm;
6234 localtime_r(&t, &tm);
6235 char timestr[64];
6236 strftime(timestr, sizeof(timestr), "%F %T", &tm);
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006237 mLastAnrState.clear();
6238 mLastAnrState += INDENT "ANR:\n";
6239 mLastAnrState += StringPrintf(INDENT2 "Time: %s\n", timestr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006240 mLastAnrState += StringPrintf(INDENT2 "Reason: %s\n", reason.c_str());
6241 mLastAnrState += StringPrintf(INDENT2 "Window: %s\n", windowLabel.c_str());
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006242 dumpDispatchStateLocked(mLastAnrState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006243}
6244
Prabir Pradhancef936d2021-07-21 16:17:52 +00006245void InputDispatcher::doInterceptKeyBeforeDispatchingCommand(const sp<IBinder>& focusedWindowToken,
6246 KeyEntry& entry) {
6247 const KeyEvent event = createKeyEvent(entry);
6248 nsecs_t delay = 0;
6249 { // release lock
6250 scoped_unlock unlock(mLock);
6251 android::base::Timer t;
Prabir Pradhana41d2442023-04-20 21:30:40 +00006252 delay = mPolicy.interceptKeyBeforeDispatching(focusedWindowToken, event, entry.policyFlags);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006253 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
6254 ALOGW("Excessive delay in interceptKeyBeforeDispatching; took %s ms",
6255 std::to_string(t.duration().count()).c_str());
6256 }
6257 } // acquire lock
Michael Wrightd02c5b62014-02-10 15:10:22 -08006258
6259 if (delay < 0) {
Michael Wright5caf55a2022-11-24 22:31:42 +00006260 entry.interceptKeyResult = KeyEntry::InterceptKeyResult::SKIP;
Prabir Pradhancef936d2021-07-21 16:17:52 +00006261 } else if (delay == 0) {
Michael Wright5caf55a2022-11-24 22:31:42 +00006262 entry.interceptKeyResult = KeyEntry::InterceptKeyResult::CONTINUE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006263 } else {
Michael Wright5caf55a2022-11-24 22:31:42 +00006264 entry.interceptKeyResult = KeyEntry::InterceptKeyResult::TRY_AGAIN_LATER;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006265 entry.interceptKeyWakeupTime = now() + delay;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006266 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006267}
6268
Prabir Pradhancef936d2021-07-21 16:17:52 +00006269void InputDispatcher::sendWindowUnresponsiveCommandLocked(const sp<IBinder>& token,
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00006270 std::optional<gui::Pid> pid,
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006271 std::string reason) {
Yabin Cui8eb9c552023-06-08 18:05:07 +00006272 auto command = [this, token, pid, r = std::move(reason)]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006273 scoped_unlock unlock(mLock);
Yabin Cuiced952f2023-06-09 21:12:51 +00006274 mPolicy.notifyWindowUnresponsive(token, pid, r);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006275 };
6276 postCommandLocked(std::move(command));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006277}
6278
Prabir Pradhanedd96402022-02-15 01:46:16 -08006279void InputDispatcher::sendWindowResponsiveCommandLocked(const sp<IBinder>& token,
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00006280 std::optional<gui::Pid> pid) {
Prabir Pradhanedd96402022-02-15 01:46:16 -08006281 auto command = [this, token, pid]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006282 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00006283 mPolicy.notifyWindowResponsive(token, pid);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006284 };
6285 postCommandLocked(std::move(command));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006286}
6287
6288/**
6289 * Tell the policy that a connection has become unresponsive so that it can start ANR.
6290 * Check whether the connection of interest is a monitor or a window, and add the corresponding
6291 * command entry to the command queue.
6292 */
6293void InputDispatcher::processConnectionUnresponsiveLocked(const Connection& connection,
6294 std::string reason) {
6295 const sp<IBinder>& connectionToken = connection.inputChannel->getConnectionToken();
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00006296 std::optional<gui::Pid> pid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006297 if (connection.monitor) {
6298 ALOGW("Monitor %s is unresponsive: %s", connection.inputChannel->getName().c_str(),
6299 reason.c_str());
Prabir Pradhanedd96402022-02-15 01:46:16 -08006300 pid = findMonitorPidByTokenLocked(connectionToken);
6301 } else {
6302 // The connection is a window
6303 ALOGW("Window %s is unresponsive: %s", connection.inputChannel->getName().c_str(),
6304 reason.c_str());
6305 const sp<WindowInfoHandle> handle = getWindowHandleLocked(connectionToken);
6306 if (handle != nullptr) {
6307 pid = handle->getInfo()->ownerPid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006308 }
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006309 }
Prabir Pradhanedd96402022-02-15 01:46:16 -08006310 sendWindowUnresponsiveCommandLocked(connectionToken, pid, std::move(reason));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006311}
6312
6313/**
6314 * Tell the policy that a connection has become responsive so that it can stop ANR.
6315 */
6316void InputDispatcher::processConnectionResponsiveLocked(const Connection& connection) {
6317 const sp<IBinder>& connectionToken = connection.inputChannel->getConnectionToken();
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00006318 std::optional<gui::Pid> pid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006319 if (connection.monitor) {
Prabir Pradhanedd96402022-02-15 01:46:16 -08006320 pid = findMonitorPidByTokenLocked(connectionToken);
6321 } else {
6322 // The connection is a window
6323 const sp<WindowInfoHandle> handle = getWindowHandleLocked(connectionToken);
6324 if (handle != nullptr) {
6325 pid = handle->getInfo()->ownerPid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006326 }
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006327 }
Prabir Pradhanedd96402022-02-15 01:46:16 -08006328 sendWindowResponsiveCommandLocked(connectionToken, pid);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006329}
6330
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006331bool InputDispatcher::afterKeyEventLockedInterruptable(
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006332 const std::shared_ptr<Connection>& connection, DispatchEntry& dispatchEntry,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006333 KeyEntry& keyEntry, bool handled) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006334 if (keyEntry.flags & AKEY_EVENT_FLAG_FALLBACK) {
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006335 if (!handled) {
6336 // Report the key as unhandled, since the fallback was not handled.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006337 mReporter->reportUnhandledKey(keyEntry.id);
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006338 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006339 return false;
6340 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006341
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006342 // Get the fallback key state.
6343 // Clear it out after dispatching the UP.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006344 int32_t originalKeyCode = keyEntry.keyCode;
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006345 std::optional<int32_t> fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006346 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006347 connection->inputState.removeFallbackKey(originalKeyCode);
6348 }
6349
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006350 if (handled || !dispatchEntry.hasForegroundTarget()) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006351 // If the application handles the original key for which we previously
6352 // generated a fallback or if the window is not a foreground window,
6353 // then cancel the associated fallback key, if any.
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006354 if (fallbackKeyCode) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006355 // Dispatch the unhandled key to the policy with the cancel flag.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006356 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6357 ALOGD("Unhandled key event: Asking policy to cancel fallback action. "
6358 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6359 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount,
6360 keyEntry.policyFlags);
6361 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006362 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006363 event.setFlags(event.getFlags() | AKEY_EVENT_FLAG_CANCELED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006364
6365 mLock.unlock();
6366
Prabir Pradhana41d2442023-04-20 21:30:40 +00006367 if (const auto unhandledKeyFallback =
6368 mPolicy.dispatchUnhandledKey(connection->inputChannel->getConnectionToken(),
6369 event, keyEntry.policyFlags);
6370 unhandledKeyFallback) {
6371 event = *unhandledKeyFallback;
6372 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006373
6374 mLock.lock();
6375
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006376 // Cancel the fallback key.
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006377 if (*fallbackKeyCode != AKEYCODE_UNKNOWN) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00006378 CancelationOptions options(CancelationOptions::Mode::CANCEL_FALLBACK_EVENTS,
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006379 "application handled the original non-fallback key "
6380 "or is no longer a foreground target, "
6381 "canceling previously dispatched fallback key");
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006382 options.keyCode = *fallbackKeyCode;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006383 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006384 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006385 connection->inputState.removeFallbackKey(originalKeyCode);
6386 }
6387 } else {
6388 // If the application did not handle a non-fallback key, first check
6389 // that we are in a good state to perform unhandled key event processing
6390 // Then ask the policy what to do with it.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006391 bool initialDown = keyEntry.action == AKEY_EVENT_ACTION_DOWN && keyEntry.repeatCount == 0;
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006392 if (!fallbackKeyCode && !initialDown) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006393 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6394 ALOGD("Unhandled key event: Skipping unhandled key event processing "
6395 "since this is not an initial down. "
6396 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6397 originalKeyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
6398 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006399 return false;
6400 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006401
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006402 // Dispatch the unhandled key to the policy.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006403 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6404 ALOGD("Unhandled key event: Asking policy to perform fallback action. "
6405 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6406 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
6407 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006408 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006409
6410 mLock.unlock();
6411
Prabir Pradhana41d2442023-04-20 21:30:40 +00006412 bool fallback = false;
6413 if (auto fb = mPolicy.dispatchUnhandledKey(connection->inputChannel->getConnectionToken(),
6414 event, keyEntry.policyFlags);
6415 fb) {
6416 fallback = true;
6417 event = *fb;
6418 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006419
6420 mLock.lock();
6421
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08006422 if (connection->status != Connection::Status::NORMAL) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006423 connection->inputState.removeFallbackKey(originalKeyCode);
6424 return false;
6425 }
6426
6427 // Latch the fallback keycode for this key on an initial down.
6428 // The fallback keycode cannot change at any other point in the lifecycle.
6429 if (initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006430 if (fallback) {
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006431 *fallbackKeyCode = event.getKeyCode();
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006432 } else {
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006433 *fallbackKeyCode = AKEYCODE_UNKNOWN;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006434 }
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006435 connection->inputState.setFallbackKey(originalKeyCode, *fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006436 }
6437
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006438 ALOG_ASSERT(fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006439
6440 // Cancel the fallback key if the policy decides not to send it anymore.
6441 // We will continue to dispatch the key to the policy but we will no
6442 // longer dispatch a fallback key to the application.
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006443 if (*fallbackKeyCode != AKEYCODE_UNKNOWN &&
6444 (!fallback || *fallbackKeyCode != event.getKeyCode())) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006445 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6446 if (fallback) {
6447 ALOGD("Unhandled key event: Policy requested to send key %d"
6448 "as a fallback for %d, but on the DOWN it had requested "
6449 "to send %d instead. Fallback canceled.",
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006450 event.getKeyCode(), originalKeyCode, *fallbackKeyCode);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006451 } else {
6452 ALOGD("Unhandled key event: Policy did not request fallback for %d, "
6453 "but on the DOWN it had requested to send %d. "
6454 "Fallback canceled.",
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006455 originalKeyCode, *fallbackKeyCode);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006456 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006457 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006458
Michael Wrightfb04fd52022-11-24 22:31:11 +00006459 CancelationOptions options(CancelationOptions::Mode::CANCEL_FALLBACK_EVENTS,
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006460 "canceling fallback, policy no longer desires it");
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006461 options.keyCode = *fallbackKeyCode;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006462 synthesizeCancelationEventsForConnectionLocked(connection, options);
6463
6464 fallback = false;
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006465 *fallbackKeyCode = AKEYCODE_UNKNOWN;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006466 if (keyEntry.action != AKEY_EVENT_ACTION_UP) {
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006467 connection->inputState.setFallbackKey(originalKeyCode, *fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006468 }
6469 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006470
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006471 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6472 {
6473 std::string msg;
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006474 const std::map<int32_t, int32_t>& fallbackKeys =
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006475 connection->inputState.getFallbackKeys();
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006476 for (const auto& [key, value] : fallbackKeys) {
6477 msg += StringPrintf(", %d->%d", key, value);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006478 }
6479 ALOGD("Unhandled key event: %zu currently tracked fallback keys%s.",
6480 fallbackKeys.size(), msg.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006481 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006482 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006483
6484 if (fallback) {
6485 // Restart the dispatch cycle using the fallback key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006486 keyEntry.eventTime = event.getEventTime();
6487 keyEntry.deviceId = event.getDeviceId();
6488 keyEntry.source = event.getSource();
6489 keyEntry.displayId = event.getDisplayId();
6490 keyEntry.flags = event.getFlags() | AKEY_EVENT_FLAG_FALLBACK;
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006491 keyEntry.keyCode = *fallbackKeyCode;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006492 keyEntry.scanCode = event.getScanCode();
6493 keyEntry.metaState = event.getMetaState();
6494 keyEntry.repeatCount = event.getRepeatCount();
6495 keyEntry.downTime = event.getDownTime();
6496 keyEntry.syntheticRepeat = false;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006497
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006498 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6499 ALOGD("Unhandled key event: Dispatching fallback key. "
6500 "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006501 originalKeyCode, *fallbackKeyCode, keyEntry.metaState);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006502 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006503 return true; // restart the event
6504 } else {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006505 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6506 ALOGD("Unhandled key event: No fallback key.");
6507 }
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006508
6509 // Report the key as unhandled, since there is no fallback key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006510 mReporter->reportUnhandledKey(keyEntry.id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006511 }
6512 }
6513 return false;
6514}
6515
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006516bool InputDispatcher::afterMotionEventLockedInterruptable(
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006517 const std::shared_ptr<Connection>& connection, DispatchEntry& dispatchEntry,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006518 MotionEntry& motionEntry, bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006519 return false;
6520}
6521
Michael Wrightd02c5b62014-02-10 15:10:22 -08006522void InputDispatcher::traceInboundQueueLengthLocked() {
6523 if (ATRACE_ENABLED()) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07006524 ATRACE_INT("iq", mInboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006525 }
6526}
6527
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006528void InputDispatcher::traceOutboundQueueLength(const Connection& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006529 if (ATRACE_ENABLED()) {
6530 char counterName[40];
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006531 snprintf(counterName, sizeof(counterName), "oq:%s", connection.getWindowName().c_str());
6532 ATRACE_INT(counterName, connection.outboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006533 }
6534}
6535
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006536void InputDispatcher::traceWaitQueueLength(const Connection& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006537 if (ATRACE_ENABLED()) {
6538 char counterName[40];
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006539 snprintf(counterName, sizeof(counterName), "wq:%s", connection.getWindowName().c_str());
6540 ATRACE_INT(counterName, connection.waitQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006541 }
6542}
6543
Siarhei Vishniakou5e20f272023-06-08 17:24:44 -07006544void InputDispatcher::dump(std::string& dump) const {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006545 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006546
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006547 dump += "Input Dispatcher State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08006548 dumpDispatchStateLocked(dump);
6549
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006550 if (!mLastAnrState.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006551 dump += "\nInput Dispatcher State at time of last ANR:\n";
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006552 dump += mLastAnrState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006553 }
6554}
6555
6556void InputDispatcher::monitor() {
6557 // Acquire and release the lock to ensure that the dispatcher has not deadlocked.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006558 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006559 mLooper->wake();
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006560 mDispatcherIsAlive.wait(_l);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006561}
6562
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08006563/**
6564 * Wake up the dispatcher and wait until it processes all events and commands.
6565 * The notification of mDispatcherEnteredIdle is guaranteed to happen after wake(), so
6566 * this method can be safely called from any thread, as long as you've ensured that
6567 * the work you are interested in completing has already been queued.
6568 */
Siarhei Vishniakoua66d65e2023-06-16 10:32:51 -07006569bool InputDispatcher::waitForIdle() const {
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08006570 /**
6571 * Timeout should represent the longest possible time that a device might spend processing
6572 * events and commands.
6573 */
6574 constexpr std::chrono::duration TIMEOUT = 100ms;
6575 std::unique_lock lock(mLock);
6576 mLooper->wake();
6577 std::cv_status result = mDispatcherEnteredIdle.wait_for(lock, TIMEOUT);
6578 return result == std::cv_status::no_timeout;
6579}
6580
Vishnu Naire798b472020-07-23 13:52:21 -07006581/**
6582 * Sets focus to the window identified by the token. This must be called
6583 * after updating any input window handles.
6584 *
6585 * Params:
6586 * request.token - input channel token used to identify the window that should gain focus.
6587 * request.focusedToken - the token that the caller expects currently to be focused. If the
6588 * specified token does not match the currently focused window, this request will be dropped.
6589 * If the specified focused token matches the currently focused window, the call will succeed.
6590 * Set this to "null" if this call should succeed no matter what the currently focused token is.
6591 * request.timestamp - SYSTEM_TIME_MONOTONIC timestamp in nanos set by the client (wm)
6592 * when requesting the focus change. This determines which request gets
6593 * precedence if there is a focus change request from another source such as pointer down.
6594 */
Vishnu Nair958da932020-08-21 17:12:37 -07006595void InputDispatcher::setFocusedWindow(const FocusRequest& request) {
6596 { // acquire lock
6597 std::scoped_lock _l(mLock);
Vishnu Nairc519ff72021-01-21 08:23:08 -08006598 std::optional<FocusResolver::FocusChanges> changes =
6599 mFocusResolver.setFocusedWindow(request, getWindowHandlesLocked(request.displayId));
6600 if (changes) {
6601 onFocusChangedLocked(*changes);
Vishnu Nair958da932020-08-21 17:12:37 -07006602 }
6603 } // release lock
6604 // Wake up poll loop since it may need to make new input dispatching choices.
6605 mLooper->wake();
6606}
6607
Vishnu Nairc519ff72021-01-21 08:23:08 -08006608void InputDispatcher::onFocusChangedLocked(const FocusResolver::FocusChanges& changes) {
6609 if (changes.oldFocus) {
6610 std::shared_ptr<InputChannel> focusedInputChannel = getInputChannelLocked(changes.oldFocus);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006611 if (focusedInputChannel) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00006612 CancelationOptions options(CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS,
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006613 "focus left window");
6614 synthesizeCancelationEventsForInputChannelLocked(focusedInputChannel, options);
Harry Cutts33476232023-01-30 19:57:29 +00006615 enqueueFocusEventLocked(changes.oldFocus, /*hasFocus=*/false, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006616 }
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006617 }
Vishnu Nairc519ff72021-01-21 08:23:08 -08006618 if (changes.newFocus) {
Siarhei Vishniakouc033dfb2023-10-03 10:45:16 -07006619 resetNoFocusedWindowTimeoutLocked();
Harry Cutts33476232023-01-30 19:57:29 +00006620 enqueueFocusEventLocked(changes.newFocus, /*hasFocus=*/true, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006621 }
6622
Prabir Pradhan99987712020-11-10 18:43:05 -08006623 // If a window has pointer capture, then it must have focus. We need to ensure that this
6624 // contract is upheld when pointer capture is being disabled due to a loss of window focus.
6625 // If the window loses focus before it loses pointer capture, then the window can be in a state
6626 // where it has pointer capture but not focus, violating the contract. Therefore we must
6627 // dispatch the pointer capture event before the focus event. Since focus events are added to
6628 // the front of the queue (above), we add the pointer capture event to the front of the queue
6629 // after the focus events are added. This ensures the pointer capture event ends up at the
6630 // front.
6631 disablePointerCaptureForcedLocked();
6632
Vishnu Nairc519ff72021-01-21 08:23:08 -08006633 if (mFocusedDisplayId == changes.displayId) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006634 sendFocusChangedCommandLocked(changes.oldFocus, changes.newFocus);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006635 }
6636}
Vishnu Nair958da932020-08-21 17:12:37 -07006637
Prabir Pradhan99987712020-11-10 18:43:05 -08006638void InputDispatcher::disablePointerCaptureForcedLocked() {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006639 if (!mCurrentPointerCaptureRequest.enable && !mWindowTokenWithPointerCapture) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006640 return;
6641 }
6642
6643 ALOGD_IF(DEBUG_FOCUS, "Disabling Pointer Capture because the window lost focus.");
6644
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006645 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006646 setPointerCaptureLocked(false);
6647 }
6648
6649 if (!mWindowTokenWithPointerCapture) {
6650 // No need to send capture changes because no window has capture.
6651 return;
6652 }
6653
6654 if (mPendingEvent != nullptr) {
6655 // Move the pending event to the front of the queue. This will give the chance
6656 // for the pending event to be dropped if it is a captured event.
6657 mInboundQueue.push_front(mPendingEvent);
6658 mPendingEvent = nullptr;
6659 }
6660
6661 auto entry = std::make_unique<PointerCaptureChangedEntry>(mIdGenerator.nextId(), now(),
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006662 mCurrentPointerCaptureRequest);
Prabir Pradhan99987712020-11-10 18:43:05 -08006663 mInboundQueue.push_front(std::move(entry));
6664}
6665
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006666void InputDispatcher::setPointerCaptureLocked(bool enable) {
6667 mCurrentPointerCaptureRequest.enable = enable;
6668 mCurrentPointerCaptureRequest.seq++;
6669 auto command = [this, request = mCurrentPointerCaptureRequest]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006670 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00006671 mPolicy.setPointerCapture(request);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006672 };
6673 postCommandLocked(std::move(command));
Prabir Pradhan99987712020-11-10 18:43:05 -08006674}
6675
Vishnu Nair599f1412021-06-21 10:39:58 -07006676void InputDispatcher::displayRemoved(int32_t displayId) {
6677 { // acquire lock
6678 std::scoped_lock _l(mLock);
6679 // Set an empty list to remove all handles from the specific display.
Harry Cutts101ee9b2023-07-06 18:04:14 +00006680 setInputWindowsLocked(/*windowInfoHandles=*/{}, displayId);
Vishnu Nair599f1412021-06-21 10:39:58 -07006681 setFocusedApplicationLocked(displayId, nullptr);
6682 // Call focus resolver to clean up stale requests. This must be called after input windows
6683 // have been removed for the removed display.
6684 mFocusResolver.displayRemoved(displayId);
Christine Franksb768bb42021-11-29 12:11:31 -08006685 // Reset pointer capture eligibility, regardless of previous state.
6686 std::erase(mIneligibleDisplaysForPointerCapture, displayId);
Antonio Kantek15beb512022-06-13 22:35:41 +00006687 // Remove the associated touch mode state.
6688 mTouchModePerDisplay.erase(displayId);
Siarhei Vishniakou5c02a712023-05-15 15:45:02 -07006689 mVerifiersByDisplay.erase(displayId);
Vishnu Nair599f1412021-06-21 10:39:58 -07006690 } // release lock
6691
6692 // Wake up poll loop since it may need to make new input dispatching choices.
6693 mLooper->wake();
6694}
6695
Patrick Williamsd828f302023-04-28 17:52:08 -05006696void InputDispatcher::onWindowInfosChanged(const gui::WindowInfosUpdate& update) {
chaviw15fab6f2021-06-07 14:15:52 -05006697 // The listener sends the windows as a flattened array. Separate the windows by display for
6698 // more convenient parsing.
6699 std::unordered_map<int32_t, std::vector<sp<WindowInfoHandle>>> handlesPerDisplay;
Patrick Williamsd828f302023-04-28 17:52:08 -05006700 for (const auto& info : update.windowInfos) {
chaviw15fab6f2021-06-07 14:15:52 -05006701 handlesPerDisplay.emplace(info.displayId, std::vector<sp<WindowInfoHandle>>());
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07006702 handlesPerDisplay[info.displayId].push_back(sp<WindowInfoHandle>::make(info));
chaviw15fab6f2021-06-07 14:15:52 -05006703 }
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006704
6705 { // acquire lock
6706 std::scoped_lock _l(mLock);
Prabir Pradhan814fe082022-07-22 20:22:18 +00006707
6708 // Ensure that we have an entry created for all existing displays so that if a displayId has
6709 // no windows, we can tell that the windows were removed from the display.
6710 for (const auto& [displayId, _] : mWindowHandlesByDisplay) {
6711 handlesPerDisplay[displayId];
6712 }
6713
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006714 mDisplayInfos.clear();
Patrick Williamsd828f302023-04-28 17:52:08 -05006715 for (const auto& displayInfo : update.displayInfos) {
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006716 mDisplayInfos.emplace(displayInfo.displayId, displayInfo);
6717 }
6718
6719 for (const auto& [displayId, handles] : handlesPerDisplay) {
6720 setInputWindowsLocked(handles, displayId);
6721 }
Patrick Williams9464b2c2023-05-23 11:22:04 -05006722
6723 if (update.vsyncId < mWindowInfosVsyncId) {
6724 ALOGE("Received out of order window infos update. Last update vsync id: %" PRId64
6725 ", current update vsync id: %" PRId64,
6726 mWindowInfosVsyncId, update.vsyncId);
6727 }
6728 mWindowInfosVsyncId = update.vsyncId;
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006729 }
6730 // Wake up poll loop since it may need to make new input dispatching choices.
6731 mLooper->wake();
chaviw15fab6f2021-06-07 14:15:52 -05006732}
6733
Vishnu Nair062a8672021-09-03 16:07:44 -07006734bool InputDispatcher::shouldDropInput(
6735 const EventEntry& entry, const sp<android::gui::WindowInfoHandle>& windowHandle) const {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006736 if (windowHandle->getInfo()->inputConfig.test(WindowInfo::InputConfig::DROP_INPUT) ||
6737 (windowHandle->getInfo()->inputConfig.test(
6738 WindowInfo::InputConfig::DROP_INPUT_IF_OBSCURED) &&
Vishnu Nair062a8672021-09-03 16:07:44 -07006739 isWindowObscuredLocked(windowHandle))) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006740 ALOGW("Dropping %s event targeting %s as requested by the input configuration {%s} on "
6741 "display %" PRId32 ".",
Vishnu Nair062a8672021-09-03 16:07:44 -07006742 ftl::enum_string(entry.type).c_str(), windowHandle->getName().c_str(),
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006743 windowHandle->getInfo()->inputConfig.string().c_str(),
Vishnu Nair062a8672021-09-03 16:07:44 -07006744 windowHandle->getInfo()->displayId);
6745 return true;
6746 }
6747 return false;
6748}
6749
Siarhei Vishniakou18050092021-09-01 13:32:49 -07006750void InputDispatcher::DispatcherWindowListener::onWindowInfosChanged(
Patrick Williamsd828f302023-04-28 17:52:08 -05006751 const gui::WindowInfosUpdate& update) {
6752 mDispatcher.onWindowInfosChanged(update);
Siarhei Vishniakou18050092021-09-01 13:32:49 -07006753}
6754
Arthur Hungdfd528e2021-12-08 13:23:04 +00006755void InputDispatcher::cancelCurrentTouch() {
6756 {
6757 std::scoped_lock _l(mLock);
6758 ALOGD("Canceling all ongoing pointer gestures on all displays.");
Michael Wrightfb04fd52022-11-24 22:31:11 +00006759 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
Arthur Hungdfd528e2021-12-08 13:23:04 +00006760 "cancel current touch");
6761 synthesizeCancelationEventsForAllConnectionsLocked(options);
6762
6763 mTouchStatesByDisplay.clear();
Arthur Hungdfd528e2021-12-08 13:23:04 +00006764 }
6765 // Wake up poll loop since there might be work to do.
6766 mLooper->wake();
6767}
6768
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006769void InputDispatcher::setMonitorDispatchingTimeoutForTest(std::chrono::nanoseconds timeout) {
6770 std::scoped_lock _l(mLock);
6771 mMonitorDispatchingTimeout = timeout;
6772}
6773
Arthur Hungc539dbb2022-12-08 07:45:36 +00006774void InputDispatcher::slipWallpaperTouch(ftl::Flags<InputTarget::Flags> targetFlags,
6775 const sp<WindowInfoHandle>& oldWindowHandle,
6776 const sp<WindowInfoHandle>& newWindowHandle,
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07006777 TouchState& state, int32_t deviceId, int32_t pointerId,
Siarhei Vishniakoubf880522023-05-01 11:03:22 -07006778 std::vector<InputTarget>& targets) const {
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08006779 std::bitset<MAX_POINTER_ID + 1> pointerIds;
6780 pointerIds.set(pointerId);
Arthur Hungc539dbb2022-12-08 07:45:36 +00006781 const bool oldHasWallpaper = oldWindowHandle->getInfo()->inputConfig.test(
6782 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
6783 const bool newHasWallpaper = targetFlags.test(InputTarget::Flags::FOREGROUND) &&
6784 newWindowHandle->getInfo()->inputConfig.test(
6785 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
6786 const sp<WindowInfoHandle> oldWallpaper =
6787 oldHasWallpaper ? state.getWallpaperWindow() : nullptr;
6788 const sp<WindowInfoHandle> newWallpaper =
6789 newHasWallpaper ? findWallpaperWindowBelow(newWindowHandle) : nullptr;
6790 if (oldWallpaper == newWallpaper) {
6791 return;
6792 }
6793
6794 if (oldWallpaper != nullptr) {
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08006795 const TouchedWindow& oldTouchedWindow = state.getTouchedWindow(oldWallpaper);
6796 addWindowTargetLocked(oldWallpaper,
6797 oldTouchedWindow.targetFlags |
6798 InputTarget::Flags::DISPATCH_AS_SLIPPERY_EXIT,
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07006799 pointerIds, oldTouchedWindow.getDownTimeInTarget(deviceId), targets);
6800 state.removeTouchingPointerFromWindow(deviceId, pointerId, oldWallpaper);
Arthur Hungc539dbb2022-12-08 07:45:36 +00006801 }
6802
6803 if (newWallpaper != nullptr) {
6804 state.addOrUpdateWindow(newWallpaper,
6805 InputTarget::Flags::DISPATCH_AS_SLIPPERY_ENTER |
6806 InputTarget::Flags::WINDOW_IS_OBSCURED |
6807 InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED,
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07006808 deviceId, pointerIds);
Arthur Hungc539dbb2022-12-08 07:45:36 +00006809 }
6810}
6811
6812void InputDispatcher::transferWallpaperTouch(ftl::Flags<InputTarget::Flags> oldTargetFlags,
6813 ftl::Flags<InputTarget::Flags> newTargetFlags,
6814 const sp<WindowInfoHandle> fromWindowHandle,
6815 const sp<WindowInfoHandle> toWindowHandle,
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07006816 TouchState& state, int32_t deviceId,
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08006817 std::bitset<MAX_POINTER_ID + 1> pointerIds) {
Arthur Hungc539dbb2022-12-08 07:45:36 +00006818 const bool oldHasWallpaper = oldTargetFlags.test(InputTarget::Flags::FOREGROUND) &&
6819 fromWindowHandle->getInfo()->inputConfig.test(
6820 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
6821 const bool newHasWallpaper = newTargetFlags.test(InputTarget::Flags::FOREGROUND) &&
6822 toWindowHandle->getInfo()->inputConfig.test(
6823 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
6824
6825 const sp<WindowInfoHandle> oldWallpaper =
6826 oldHasWallpaper ? state.getWallpaperWindow() : nullptr;
6827 const sp<WindowInfoHandle> newWallpaper =
6828 newHasWallpaper ? findWallpaperWindowBelow(toWindowHandle) : nullptr;
6829 if (oldWallpaper == newWallpaper) {
6830 return;
6831 }
6832
6833 if (oldWallpaper != nullptr) {
6834 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
6835 "transferring touch focus to another window");
6836 state.removeWindowByToken(oldWallpaper->getToken());
6837 synthesizeCancelationEventsForWindowLocked(oldWallpaper, options);
6838 }
6839
6840 if (newWallpaper != nullptr) {
6841 nsecs_t downTimeInTarget = now();
6842 ftl::Flags<InputTarget::Flags> wallpaperFlags =
6843 oldTargetFlags & (InputTarget::Flags::SPLIT | InputTarget::Flags::DISPATCH_AS_IS);
6844 wallpaperFlags |= InputTarget::Flags::WINDOW_IS_OBSCURED |
6845 InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED;
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07006846 state.addOrUpdateWindow(newWallpaper, wallpaperFlags, deviceId, pointerIds,
6847 downTimeInTarget);
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006848 std::shared_ptr<Connection> wallpaperConnection =
6849 getConnectionLocked(newWallpaper->getToken());
Arthur Hungc539dbb2022-12-08 07:45:36 +00006850 if (wallpaperConnection != nullptr) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006851 std::shared_ptr<Connection> toConnection =
6852 getConnectionLocked(toWindowHandle->getToken());
Arthur Hungc539dbb2022-12-08 07:45:36 +00006853 toConnection->inputState.mergePointerStateTo(wallpaperConnection->inputState);
6854 synthesizePointerDownEventsForConnectionLocked(downTimeInTarget, wallpaperConnection,
6855 wallpaperFlags);
6856 }
6857 }
6858}
6859
6860sp<WindowInfoHandle> InputDispatcher::findWallpaperWindowBelow(
6861 const sp<WindowInfoHandle>& windowHandle) const {
6862 const std::vector<sp<WindowInfoHandle>>& windowHandles =
6863 getWindowHandlesLocked(windowHandle->getInfo()->displayId);
6864 bool foundWindow = false;
6865 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
6866 if (!foundWindow && otherHandle != windowHandle) {
6867 continue;
6868 }
6869 if (windowHandle == otherHandle) {
6870 foundWindow = true;
6871 continue;
6872 }
6873
6874 if (otherHandle->getInfo()->inputConfig.test(WindowInfo::InputConfig::IS_WALLPAPER)) {
6875 return otherHandle;
6876 }
6877 }
6878 return nullptr;
6879}
6880
Nergi Rahardi730cf3c2023-04-13 12:41:17 +09006881void InputDispatcher::setKeyRepeatConfiguration(nsecs_t timeout, nsecs_t delay) {
6882 std::scoped_lock _l(mLock);
6883
6884 mConfig.keyRepeatTimeout = timeout;
6885 mConfig.keyRepeatDelay = delay;
6886}
6887
Garfield Tane84e6f92019-08-29 17:28:41 -07006888} // namespace android::inputdispatcher