blob: 1589278a687614ff0e00696c757cba321b3bf48f [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) {
Linnan Li5af92f92023-07-14 14:36:22 +08003924 if ((options.mode == CancelationOptions::Mode::CANCEL_POINTER_EVENTS ||
3925 options.mode == CancelationOptions::Mode::CANCEL_ALL_EVENTS) &&
3926 mDragState && mDragState->dragWindow->getToken() == connection->inputChannel->getToken()) {
3927 LOG(INFO) << __func__
3928 << ": Canceling drag and drop because the pointers for the drag window are being "
3929 "canceled.";
3930 sendDropWindowCommandLocked(nullptr, /*x=*/0, /*y=*/0);
3931 mDragState.reset();
3932 }
3933
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003934 if (connection->status == Connection::Status::BROKEN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003935 return;
3936 }
3937
3938 nsecs_t currentTime = now();
3939
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003940 std::vector<std::unique_ptr<EventEntry>> cancelationEvents =
Siarhei Vishniakou00fca7c2019-10-29 13:05:57 -07003941 connection->inputState.synthesizeCancelationEvents(currentTime, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003942
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003943 if (cancelationEvents.empty()) {
3944 return;
3945 }
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003946 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
3947 ALOGD("channel '%s' ~ Synthesized %zu cancelation events to bring channel back in sync "
Siarhei Vishniakou2e3e4432023-02-09 18:34:11 -08003948 "with reality: %s, mode=%s.",
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003949 connection->getInputChannelName().c_str(), cancelationEvents.size(), options.reason,
Siarhei Vishniakou2e3e4432023-02-09 18:34:11 -08003950 ftl::enum_string(options.mode).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003951 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08003952
Arthur Hungb3307ee2021-10-14 10:57:37 +00003953 std::string reason = std::string("reason=").append(options.reason);
3954 android_log_event_list(LOGTAG_INPUT_CANCEL)
3955 << connection->getInputChannelName().c_str() << reason << LOG_ID_EVENTS;
3956
Hu Guo771a7692023-09-17 20:51:08 +08003957 sp<WindowInfoHandle> windowHandle;
3958 if (options.displayId) {
3959 windowHandle = getWindowHandleLocked(connection->inputChannel->getConnectionToken(),
3960 options.displayId.value());
3961 } else {
3962 windowHandle = getWindowHandleLocked(connection->inputChannel->getConnectionToken());
3963 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08003964
hongzuo liu95785e22022-09-06 02:51:35 +00003965 const bool wasEmpty = connection->outboundQueue.empty();
3966
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003967 for (size_t i = 0; i < cancelationEvents.size(); i++) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003968 std::unique_ptr<EventEntry> cancelationEventEntry = std::move(cancelationEvents[i]);
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00003969 std::vector<InputTarget> targets{};
3970 // The target to use if we don't find a window associated with the channel.
3971 const InputTarget fallbackTarget{.inputChannel = connection->inputChannel,
3972 .flags = InputTarget::Flags::DISPATCH_AS_IS};
3973
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003974 switch (cancelationEventEntry->type) {
3975 case EventEntry::Type::KEY: {
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00003976 const auto& keyEntry = static_cast<const KeyEntry&>(*cancelationEventEntry);
3977 if (windowHandle != nullptr) {
3978 addWindowTargetLocked(windowHandle, InputTarget::Flags::DISPATCH_AS_IS,
3979 /*pointerIds=*/{}, keyEntry.downTime, targets);
3980 } else {
3981 targets.emplace_back(fallbackTarget);
3982 }
3983 logOutboundKeyDetails("cancel - ", keyEntry);
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003984 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003985 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003986 case EventEntry::Type::MOTION: {
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00003987 const auto& motionEntry = static_cast<const MotionEntry&>(*cancelationEventEntry);
3988 if (windowHandle != nullptr) {
3989 std::bitset<MAX_POINTER_ID + 1> pointerIds;
3990 for (uint32_t pointerIndex = 0; pointerIndex < motionEntry.pointerCount;
3991 pointerIndex++) {
3992 pointerIds.set(motionEntry.pointerProperties[pointerIndex].id);
3993 }
3994 addWindowTargetLocked(windowHandle, InputTarget::Flags::DISPATCH_AS_IS,
3995 pointerIds, motionEntry.downTime, targets);
3996 } else {
3997 targets.emplace_back(fallbackTarget);
3998 const auto it = mDisplayInfos.find(motionEntry.displayId);
3999 if (it != mDisplayInfos.end()) {
4000 targets.back().displayTransform = it->second.transform;
4001 targets.back().setDefaultPointerTransform(it->second.transform);
4002 }
4003 }
4004 logOutboundMotionDetails("cancel - ", motionEntry);
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004005 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004006 }
Prabir Pradhan99987712020-11-10 18:43:05 -08004007 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07004008 case EventEntry::Type::TOUCH_MODE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08004009 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
4010 case EventEntry::Type::DRAG: {
Prabir Pradhan99987712020-11-10 18:43:05 -08004011 LOG_ALWAYS_FATAL("Canceling %s events is not supported",
Dominik Laskowski75788452021-02-09 18:51:25 -08004012 ftl::enum_string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004013 break;
4014 }
4015 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07004016 case EventEntry::Type::DEVICE_RESET:
4017 case EventEntry::Type::SENSOR: {
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004018 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Dominik Laskowski75788452021-02-09 18:51:25 -08004019 ftl::enum_string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004020 break;
4021 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004022 }
4023
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00004024 if (targets.size() != 1) LOG(FATAL) << __func__ << ": InputTarget not created";
4025 enqueueDispatchEntryLocked(connection, std::move(cancelationEventEntry), targets[0],
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08004026 InputTarget::Flags::DISPATCH_AS_IS);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004027 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004028
hongzuo liu95785e22022-09-06 02:51:35 +00004029 // If the outbound queue was previously empty, start the dispatch cycle going.
4030 if (wasEmpty && !connection->outboundQueue.empty()) {
4031 startDispatchCycleLocked(currentTime, connection);
4032 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004033}
4034
Svet Ganov5d3bc372020-01-26 23:11:07 -08004035void InputDispatcher::synthesizePointerDownEventsForConnectionLocked(
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07004036 const nsecs_t downTime, const std::shared_ptr<Connection>& connection,
Arthur Hungc539dbb2022-12-08 07:45:36 +00004037 ftl::Flags<InputTarget::Flags> targetFlags) {
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08004038 if (connection->status == Connection::Status::BROKEN) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08004039 return;
4040 }
4041
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004042 std::vector<std::unique_ptr<EventEntry>> downEvents =
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00004043 connection->inputState.synthesizePointerDownEvents(downTime);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004044
4045 if (downEvents.empty()) {
4046 return;
4047 }
4048
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004049 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08004050 ALOGD("channel '%s' ~ Synthesized %zu down events to ensure consistent event stream.",
4051 connection->getInputChannelName().c_str(), downEvents.size());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004052 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08004053
chaviw98318de2021-05-19 16:45:23 -05004054 sp<WindowInfoHandle> windowHandle =
Svet Ganov5d3bc372020-01-26 23:11:07 -08004055 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
Svet Ganov5d3bc372020-01-26 23:11:07 -08004056
hongzuo liu95785e22022-09-06 02:51:35 +00004057 const bool wasEmpty = connection->outboundQueue.empty();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004058 for (std::unique_ptr<EventEntry>& downEventEntry : downEvents) {
Prabir Pradhan1c29a092023-09-21 10:29:29 +00004059 std::vector<InputTarget> targets{};
Svet Ganov5d3bc372020-01-26 23:11:07 -08004060 switch (downEventEntry->type) {
4061 case EventEntry::Type::MOTION: {
Prabir Pradhan1c29a092023-09-21 10:29:29 +00004062 const auto& motionEntry = static_cast<const MotionEntry&>(*downEventEntry);
4063 if (windowHandle != nullptr) {
4064 std::bitset<MAX_POINTER_ID + 1> pointerIds;
4065 for (uint32_t pointerIndex = 0; pointerIndex < motionEntry.pointerCount;
4066 pointerIndex++) {
4067 pointerIds.set(motionEntry.pointerProperties[pointerIndex].id);
4068 }
4069 addWindowTargetLocked(windowHandle, targetFlags, pointerIds,
4070 motionEntry.downTime, targets);
4071 } else {
4072 targets.emplace_back(InputTarget{.inputChannel = connection->inputChannel,
4073 .flags = targetFlags});
4074 const auto it = mDisplayInfos.find(motionEntry.displayId);
4075 if (it != mDisplayInfos.end()) {
4076 targets.back().displayTransform = it->second.transform;
4077 targets.back().setDefaultPointerTransform(it->second.transform);
4078 }
4079 }
4080 logOutboundMotionDetails("down - ", motionEntry);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004081 break;
4082 }
4083
4084 case EventEntry::Type::KEY:
4085 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07004086 case EventEntry::Type::TOUCH_MODE_CHANGED:
Svet Ganov5d3bc372020-01-26 23:11:07 -08004087 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08004088 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07004089 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08004090 case EventEntry::Type::SENSOR:
4091 case EventEntry::Type::DRAG: {
Svet Ganov5d3bc372020-01-26 23:11:07 -08004092 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Dominik Laskowski75788452021-02-09 18:51:25 -08004093 ftl::enum_string(downEventEntry->type).c_str());
Svet Ganov5d3bc372020-01-26 23:11:07 -08004094 break;
4095 }
4096 }
4097
Prabir Pradhan1c29a092023-09-21 10:29:29 +00004098 if (targets.size() != 1) LOG(FATAL) << __func__ << ": InputTarget not created";
4099 enqueueDispatchEntryLocked(connection, std::move(downEventEntry), targets[0],
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08004100 InputTarget::Flags::DISPATCH_AS_IS);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004101 }
4102
hongzuo liu95785e22022-09-06 02:51:35 +00004103 // If the outbound queue was previously empty, start the dispatch cycle going.
4104 if (wasEmpty && !connection->outboundQueue.empty()) {
4105 startDispatchCycleLocked(downTime, connection);
4106 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08004107}
4108
Arthur Hungc539dbb2022-12-08 07:45:36 +00004109void InputDispatcher::synthesizeCancelationEventsForWindowLocked(
4110 const sp<WindowInfoHandle>& windowHandle, const CancelationOptions& options) {
4111 if (windowHandle != nullptr) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07004112 std::shared_ptr<Connection> wallpaperConnection =
4113 getConnectionLocked(windowHandle->getToken());
Arthur Hungc539dbb2022-12-08 07:45:36 +00004114 if (wallpaperConnection != nullptr) {
4115 synthesizeCancelationEventsForConnectionLocked(wallpaperConnection, options);
4116 }
4117 }
4118}
4119
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004120std::unique_ptr<MotionEntry> InputDispatcher::splitMotionEvent(
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08004121 const MotionEntry& originalMotionEntry, std::bitset<MAX_POINTER_ID + 1> pointerIds,
4122 nsecs_t splitDownTime) {
4123 ALOG_ASSERT(pointerIds.any());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004124
4125 uint32_t splitPointerIndexMap[MAX_POINTERS];
4126 PointerProperties splitPointerProperties[MAX_POINTERS];
4127 PointerCoords splitPointerCoords[MAX_POINTERS];
4128
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07004129 uint32_t originalPointerCount = originalMotionEntry.pointerCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004130 uint32_t splitPointerCount = 0;
4131
4132 for (uint32_t originalPointerIndex = 0; originalPointerIndex < originalPointerCount;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004133 originalPointerIndex++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004134 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07004135 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08004136 uint32_t pointerId = uint32_t(pointerProperties.id);
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08004137 if (pointerIds.test(pointerId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004138 splitPointerIndexMap[splitPointerCount] = originalPointerIndex;
Siarhei Vishniakou73e6d372023-07-06 18:07:21 -07004139 splitPointerProperties[splitPointerCount] = pointerProperties;
4140 splitPointerCoords[splitPointerCount] =
4141 originalMotionEntry.pointerCoords[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08004142 splitPointerCount += 1;
4143 }
4144 }
4145
4146 if (splitPointerCount != pointerIds.count()) {
4147 // This is bad. We are missing some of the pointers that we expected to deliver.
4148 // Most likely this indicates that we received an ACTION_MOVE events that has
4149 // different pointer ids than we expected based on the previous ACTION_DOWN
4150 // or ACTION_POINTER_DOWN events that caused us to decide to split the pointers
4151 // in this way.
4152 ALOGW("Dropping split motion event because the pointer count is %d but "
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08004153 "we expected there to be %zu pointers. This probably means we received "
Siarhei Vishniakou16e4fa02023-02-16 17:48:56 -08004154 "a broken sequence of pointer ids from the input device: %s",
4155 splitPointerCount, pointerIds.count(), originalMotionEntry.getDescription().c_str());
Yi Kong9b14ac62018-07-17 13:48:38 -07004156 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004157 }
4158
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07004159 int32_t action = originalMotionEntry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004160 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004161 if (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN ||
4162 maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
Siarhei Vishniakou5b9766d2023-07-18 14:06:29 -07004163 int32_t originalPointerIndex = MotionEvent::getActionIndex(action);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004164 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07004165 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08004166 uint32_t pointerId = uint32_t(pointerProperties.id);
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08004167 if (pointerIds.test(pointerId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004168 if (pointerIds.count() == 1) {
4169 // The first/last pointer went down/up.
4170 action = maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004171 ? AMOTION_EVENT_ACTION_DOWN
arthurhungea3f4fc2020-12-21 23:18:53 +08004172 : (originalMotionEntry.flags & AMOTION_EVENT_FLAG_CANCELED) != 0
4173 ? AMOTION_EVENT_ACTION_CANCEL
4174 : AMOTION_EVENT_ACTION_UP;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004175 } else {
4176 // A secondary pointer went down/up.
4177 uint32_t splitPointerIndex = 0;
4178 while (pointerId != uint32_t(splitPointerProperties[splitPointerIndex].id)) {
4179 splitPointerIndex += 1;
4180 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004181 action = maskedAction |
4182 (splitPointerIndex << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004183 }
4184 } else {
4185 // An unrelated pointer changed.
4186 action = AMOTION_EVENT_ACTION_MOVE;
4187 }
4188 }
4189
Siarhei Vishniakou59e302b2023-06-05 08:04:53 -07004190 if (action == AMOTION_EVENT_ACTION_DOWN && splitDownTime != originalMotionEntry.eventTime) {
4191 logDispatchStateLocked();
4192 LOG_ALWAYS_FATAL("Split motion event has mismatching downTime and eventTime for "
4193 "ACTION_DOWN, motionEntry=%s, splitDownTime=%" PRId64,
4194 originalMotionEntry.getDescription().c_str(), splitDownTime);
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00004195 }
4196
Garfield Tanff1f1bb2020-01-28 13:24:04 -08004197 int32_t newId = mIdGenerator.nextId();
Prabir Pradhan2dac8b82023-09-06 01:11:51 +00004198 ATRACE_NAME_IF(ATRACE_ENABLED(),
4199 StringPrintf("Split MotionEvent(id=0x%" PRIx32 ") to MotionEvent(id=0x%" PRIx32
4200 ").",
4201 originalMotionEntry.id, newId));
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004202 std::unique_ptr<MotionEntry> splitMotionEntry =
4203 std::make_unique<MotionEntry>(newId, originalMotionEntry.eventTime,
4204 originalMotionEntry.deviceId, originalMotionEntry.source,
4205 originalMotionEntry.displayId,
4206 originalMotionEntry.policyFlags, action,
4207 originalMotionEntry.actionButton,
4208 originalMotionEntry.flags, originalMotionEntry.metaState,
4209 originalMotionEntry.buttonState,
4210 originalMotionEntry.classification,
4211 originalMotionEntry.edgeFlags,
4212 originalMotionEntry.xPrecision,
4213 originalMotionEntry.yPrecision,
4214 originalMotionEntry.xCursorPosition,
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00004215 originalMotionEntry.yCursorPosition, splitDownTime,
4216 splitPointerCount, splitPointerProperties,
4217 splitPointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004218
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07004219 if (originalMotionEntry.injectionState) {
4220 splitMotionEntry->injectionState = originalMotionEntry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004221 splitMotionEntry->injectionState->refCount += 1;
4222 }
4223
4224 return splitMotionEntry;
4225}
4226
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004227void InputDispatcher::notifyConfigurationChanged(const NotifyConfigurationChangedArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004228 if (debugInboundEventDetails()) {
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004229 ALOGD("notifyConfigurationChanged - eventTime=%" PRId64, args.eventTime);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004230 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004231
Antonio Kantekf16f2832021-09-28 04:39:20 +00004232 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004233 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004234 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004235
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004236 std::unique_ptr<ConfigurationChangedEntry> newEntry =
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004237 std::make_unique<ConfigurationChangedEntry>(args.id, args.eventTime);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004238 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004239 } // release lock
4240
4241 if (needWake) {
4242 mLooper->wake();
4243 }
4244}
4245
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004246void InputDispatcher::notifyKey(const NotifyKeyArgs& args) {
Prabir Pradhan96282b02023-02-24 22:36:17 +00004247 ALOGD_IF(debugInboundEventDetails(),
4248 "notifyKey - id=%" PRIx32 ", eventTime=%" PRId64
4249 ", deviceId=%d, source=%s, displayId=%" PRId32
4250 "policyFlags=0x%x, action=%s, flags=0x%x, keyCode=%s, scanCode=0x%x, metaState=0x%x, "
4251 "downTime=%" PRId64,
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004252 args.id, args.eventTime, args.deviceId, inputEventSourceToString(args.source).c_str(),
4253 args.displayId, args.policyFlags, KeyEvent::actionToString(args.action), args.flags,
4254 KeyEvent::getLabel(args.keyCode), args.scanCode, args.metaState, args.downTime);
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004255 Result<void> keyCheck = validateKeyEvent(args.action);
4256 if (!keyCheck.ok()) {
4257 LOG(ERROR) << "invalid key event: " << keyCheck.error();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004258 return;
4259 }
4260
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004261 uint32_t policyFlags = args.policyFlags;
4262 int32_t flags = args.flags;
4263 int32_t metaState = args.metaState;
Siarhei Vishniakou622bd322018-10-29 18:02:27 -07004264 // InputDispatcher tracks and generates key repeats on behalf of
4265 // whatever notifies it, so repeatCount should always be set to 0
4266 constexpr int32_t repeatCount = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004267 if ((policyFlags & POLICY_FLAG_VIRTUAL) || (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY)) {
4268 policyFlags |= POLICY_FLAG_VIRTUAL;
4269 flags |= AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
4270 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004271 if (policyFlags & POLICY_FLAG_FUNCTION) {
4272 metaState |= AMETA_FUNCTION_ON;
4273 }
4274
4275 policyFlags |= POLICY_FLAG_TRUSTED;
4276
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004277 int32_t keyCode = args.keyCode;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004278 KeyEvent event;
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004279 event.initialize(args.id, args.deviceId, args.source, args.displayId, INVALID_HMAC, args.action,
4280 flags, keyCode, args.scanCode, metaState, repeatCount, args.downTime,
4281 args.eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004282
Michael Wright2b3c3302018-03-02 17:19:13 +00004283 android::base::Timer t;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004284 mPolicy.interceptKeyBeforeQueueing(event, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00004285 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4286 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004287 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00004288 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004289
Antonio Kantekf16f2832021-09-28 04:39:20 +00004290 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004291 { // acquire lock
4292 mLock.lock();
4293
4294 if (shouldSendKeyToInputFilterLocked(args)) {
4295 mLock.unlock();
4296
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004297 policyFlags |= POLICY_FLAG_FILTERED;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004298 if (!mPolicy.filterInputEvent(event, policyFlags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004299 return; // event was consumed by the filter
4300 }
4301
4302 mLock.lock();
4303 }
4304
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004305 std::unique_ptr<KeyEntry> newEntry =
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004306 std::make_unique<KeyEntry>(args.id, args.eventTime, args.deviceId, args.source,
4307 args.displayId, policyFlags, args.action, flags, keyCode,
4308 args.scanCode, metaState, repeatCount, args.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004309
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004310 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004311 mLock.unlock();
4312 } // release lock
4313
4314 if (needWake) {
4315 mLooper->wake();
4316 }
4317}
4318
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004319bool InputDispatcher::shouldSendKeyToInputFilterLocked(const NotifyKeyArgs& args) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004320 return mInputFilterEnabled;
4321}
4322
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004323void InputDispatcher::notifyMotion(const NotifyMotionArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004324 if (debugInboundEventDetails()) {
Prabir Pradhan96282b02023-02-24 22:36:17 +00004325 ALOGD("notifyMotion - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=%s, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004326 "displayId=%" PRId32 ", policyFlags=0x%x, "
Siarhei Vishniakou6ebd0692022-10-20 15:05:45 -07004327 "action=%s, actionButton=0x%x, flags=0x%x, metaState=0x%x, buttonState=0x%x, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004328 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, xCursorPosition=%f, "
4329 "yCursorPosition=%f, downTime=%" PRId64,
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004330 args.id, args.eventTime, args.deviceId, inputEventSourceToString(args.source).c_str(),
4331 args.displayId, args.policyFlags, MotionEvent::actionToString(args.action).c_str(),
4332 args.actionButton, args.flags, args.metaState, args.buttonState, args.edgeFlags,
4333 args.xPrecision, args.yPrecision, args.xCursorPosition, args.yCursorPosition,
4334 args.downTime);
Siarhei Vishniakou3218fc02023-06-15 20:41:02 -07004335 for (uint32_t i = 0; i < args.getPointerCount(); i++) {
Prabir Pradhan96282b02023-02-24 22:36:17 +00004336 ALOGD(" Pointer %d: id=%d, toolType=%s, x=%f, y=%f, pressure=%f, size=%f, "
4337 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, orientation=%f",
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004338 i, args.pointerProperties[i].id,
4339 ftl::enum_string(args.pointerProperties[i].toolType).c_str(),
4340 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
4341 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
4342 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
4343 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
4344 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
4345 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
4346 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
4347 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
4348 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004349 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004350 }
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004351
Siarhei Vishniakou3218fc02023-06-15 20:41:02 -07004352 Result<void> motionCheck =
4353 validateMotionEvent(args.action, args.actionButton, args.getPointerCount(),
4354 args.pointerProperties.data());
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004355 if (!motionCheck.ok()) {
4356 LOG(FATAL) << "Invalid event: " << args.dump() << "; reason: " << motionCheck.error();
4357 return;
4358 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004359
Siarhei Vishniakou5c02a712023-05-15 15:45:02 -07004360 if (DEBUG_VERIFY_EVENTS) {
4361 auto [it, _] =
4362 mVerifiersByDisplay.try_emplace(args.displayId,
4363 StringPrintf("display %" PRId32, args.displayId));
4364 Result<void> result =
Siarhei Vishniakou2d151ac2023-09-19 13:30:24 -07004365 it->second.processMovement(args.deviceId, args.source, args.action,
4366 args.getPointerCount(), args.pointerProperties.data(),
4367 args.pointerCoords.data(), args.flags);
Siarhei Vishniakou5c02a712023-05-15 15:45:02 -07004368 if (!result.ok()) {
4369 LOG(FATAL) << "Bad stream: " << result.error() << " caused by " << args.dump();
4370 }
4371 }
4372
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004373 uint32_t policyFlags = args.policyFlags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004374 policyFlags |= POLICY_FLAG_TRUSTED;
Michael Wright2b3c3302018-03-02 17:19:13 +00004375
4376 android::base::Timer t;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004377 mPolicy.interceptMotionBeforeQueueing(args.displayId, args.eventTime, policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00004378 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4379 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004380 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00004381 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004382
Antonio Kantekf16f2832021-09-28 04:39:20 +00004383 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004384 { // acquire lock
4385 mLock.lock();
Siarhei Vishniakou5bf25d92023-02-08 15:43:38 -08004386 if (!(policyFlags & POLICY_FLAG_PASS_TO_USER)) {
4387 // Set the flag anyway if we already have an ongoing gesture. That would allow us to
4388 // complete the processing of the current stroke.
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004389 const auto touchStateIt = mTouchStatesByDisplay.find(args.displayId);
Siarhei Vishniakou5bf25d92023-02-08 15:43:38 -08004390 if (touchStateIt != mTouchStatesByDisplay.end()) {
4391 const TouchState& touchState = touchStateIt->second;
Siarhei Vishniakou45504fe2023-05-05 16:05:10 -07004392 if (touchState.hasTouchingPointers(args.deviceId)) {
Siarhei Vishniakou5bf25d92023-02-08 15:43:38 -08004393 policyFlags |= POLICY_FLAG_PASS_TO_USER;
4394 }
4395 }
4396 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004397
4398 if (shouldSendMotionToInputFilterLocked(args)) {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004399 ui::Transform displayTransform;
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004400 if (const auto it = mDisplayInfos.find(args.displayId); it != mDisplayInfos.end()) {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004401 displayTransform = it->second.transform;
4402 }
4403
Michael Wrightd02c5b62014-02-10 15:10:22 -08004404 mLock.unlock();
4405
4406 MotionEvent event;
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004407 event.initialize(args.id, args.deviceId, args.source, args.displayId, INVALID_HMAC,
4408 args.action, args.actionButton, args.flags, args.edgeFlags,
4409 args.metaState, args.buttonState, args.classification,
4410 displayTransform, args.xPrecision, args.yPrecision,
4411 args.xCursorPosition, args.yCursorPosition, displayTransform,
Siarhei Vishniakou3218fc02023-06-15 20:41:02 -07004412 args.downTime, args.eventTime, args.getPointerCount(),
4413 args.pointerProperties.data(), args.pointerCoords.data());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004414
4415 policyFlags |= POLICY_FLAG_FILTERED;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004416 if (!mPolicy.filterInputEvent(event, policyFlags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004417 return; // event was consumed by the filter
4418 }
4419
4420 mLock.lock();
4421 }
4422
4423 // Just enqueue a new motion event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004424 std::unique_ptr<MotionEntry> newEntry =
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004425 std::make_unique<MotionEntry>(args.id, args.eventTime, args.deviceId, args.source,
4426 args.displayId, policyFlags, args.action,
4427 args.actionButton, args.flags, args.metaState,
4428 args.buttonState, args.classification, args.edgeFlags,
4429 args.xPrecision, args.yPrecision,
4430 args.xCursorPosition, args.yCursorPosition,
Siarhei Vishniakou3218fc02023-06-15 20:41:02 -07004431 args.downTime, args.getPointerCount(),
4432 args.pointerProperties.data(),
4433 args.pointerCoords.data());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004434
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004435 if (args.id != android::os::IInputConstants::INVALID_INPUT_EVENT_ID &&
4436 IdGenerator::getSource(args.id) == IdGenerator::Source::INPUT_READER &&
Siarhei Vishniakou363e7292021-07-09 03:22:42 +00004437 !mInputFilterEnabled) {
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004438 const bool isDown = args.action == AMOTION_EVENT_ACTION_DOWN;
4439 mLatencyTracker.trackListener(args.id, isDown, args.eventTime, args.readTime);
Siarhei Vishniakou363e7292021-07-09 03:22:42 +00004440 }
4441
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004442 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004443 mLock.unlock();
4444 } // release lock
4445
4446 if (needWake) {
4447 mLooper->wake();
4448 }
4449}
4450
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004451void InputDispatcher::notifySensor(const NotifySensorArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004452 if (debugInboundEventDetails()) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004453 ALOGD("notifySensor - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=0x%x, "
4454 " sensorType=%s",
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004455 args.id, args.eventTime, args.deviceId, args.source,
4456 ftl::enum_string(args.sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004457 }
Chris Yef59a2f42020-10-16 12:55:26 -07004458
Antonio Kantekf16f2832021-09-28 04:39:20 +00004459 bool needWake = false;
Chris Yef59a2f42020-10-16 12:55:26 -07004460 { // acquire lock
4461 mLock.lock();
4462
4463 // Just enqueue a new sensor event.
4464 std::unique_ptr<SensorEntry> newEntry =
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004465 std::make_unique<SensorEntry>(args.id, args.eventTime, args.deviceId, args.source,
4466 /* policyFlags=*/0, args.hwTimestamp, args.sensorType,
4467 args.accuracy, args.accuracyChanged, args.values);
Chris Yef59a2f42020-10-16 12:55:26 -07004468
4469 needWake = enqueueInboundEventLocked(std::move(newEntry));
4470 mLock.unlock();
4471 } // release lock
4472
4473 if (needWake) {
4474 mLooper->wake();
4475 }
4476}
4477
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004478void InputDispatcher::notifyVibratorState(const NotifyVibratorStateArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004479 if (debugInboundEventDetails()) {
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004480 ALOGD("notifyVibratorState - eventTime=%" PRId64 ", device=%d, isOn=%d", args.eventTime,
4481 args.deviceId, args.isOn);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004482 }
Prabir Pradhana41d2442023-04-20 21:30:40 +00004483 mPolicy.notifyVibratorState(args.deviceId, args.isOn);
Chris Yefb552902021-02-03 17:18:37 -08004484}
4485
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004486bool InputDispatcher::shouldSendMotionToInputFilterLocked(const NotifyMotionArgs& args) {
Jackal Guof9696682018-10-05 12:23:23 +08004487 return mInputFilterEnabled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004488}
4489
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004490void InputDispatcher::notifySwitch(const NotifySwitchArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004491 if (debugInboundEventDetails()) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004492 ALOGD("notifySwitch - eventTime=%" PRId64 ", policyFlags=0x%x, switchValues=0x%08x, "
4493 "switchMask=0x%08x",
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004494 args.eventTime, args.policyFlags, args.switchValues, args.switchMask);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004495 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004496
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004497 uint32_t policyFlags = args.policyFlags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004498 policyFlags |= POLICY_FLAG_TRUSTED;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004499 mPolicy.notifySwitch(args.eventTime, args.switchValues, args.switchMask, policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004500}
4501
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004502void InputDispatcher::notifyDeviceReset(const NotifyDeviceResetArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004503 if (debugInboundEventDetails()) {
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004504 ALOGD("notifyDeviceReset - eventTime=%" PRId64 ", deviceId=%d", args.eventTime,
4505 args.deviceId);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004506 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004507
Antonio Kantekf16f2832021-09-28 04:39:20 +00004508 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004509 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004510 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004511
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004512 std::unique_ptr<DeviceResetEntry> newEntry =
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004513 std::make_unique<DeviceResetEntry>(args.id, args.eventTime, args.deviceId);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004514 needWake = enqueueInboundEventLocked(std::move(newEntry));
Siarhei Vishniakou1160ecd2023-06-28 15:57:47 -07004515
4516 for (auto& [_, verifier] : mVerifiersByDisplay) {
4517 verifier.resetDevice(args.deviceId);
4518 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004519 } // release lock
4520
4521 if (needWake) {
4522 mLooper->wake();
4523 }
4524}
4525
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004526void InputDispatcher::notifyPointerCaptureChanged(const NotifyPointerCaptureChangedArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004527 if (debugInboundEventDetails()) {
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004528 ALOGD("notifyPointerCaptureChanged - eventTime=%" PRId64 ", enabled=%s", args.eventTime,
4529 args.request.enable ? "true" : "false");
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004530 }
Prabir Pradhan7e186182020-11-10 13:56:45 -08004531
Antonio Kantekf16f2832021-09-28 04:39:20 +00004532 bool needWake = false;
Prabir Pradhan99987712020-11-10 18:43:05 -08004533 { // acquire lock
4534 std::scoped_lock _l(mLock);
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004535 auto entry =
4536 std::make_unique<PointerCaptureChangedEntry>(args.id, args.eventTime, args.request);
Prabir Pradhan99987712020-11-10 18:43:05 -08004537 needWake = enqueueInboundEventLocked(std::move(entry));
4538 } // release lock
4539
4540 if (needWake) {
4541 mLooper->wake();
4542 }
Prabir Pradhan7e186182020-11-10 13:56:45 -08004543}
4544
Prabir Pradhan5735a322022-04-11 17:23:34 +00004545InputEventInjectionResult InputDispatcher::injectInputEvent(const InputEvent* event,
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00004546 std::optional<gui::Uid> targetUid,
Prabir Pradhan5735a322022-04-11 17:23:34 +00004547 InputEventInjectionSync syncMode,
4548 std::chrono::milliseconds timeout,
4549 uint32_t policyFlags) {
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004550 Result<void> eventValidation = validateInputEvent(*event);
4551 if (!eventValidation.ok()) {
4552 LOG(INFO) << "Injection failed: invalid event: " << eventValidation.error();
4553 return InputEventInjectionResult::FAILED;
4554 }
4555
Prabir Pradhan65613802023-02-22 23:36:58 +00004556 if (debugInboundEventDetails()) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07004557 LOG(INFO) << __func__ << ": targetUid=" << toString(targetUid, &uidString)
4558 << ", syncMode=" << ftl::enum_string(syncMode) << ", timeout=" << timeout.count()
4559 << "ms, policyFlags=0x" << std::hex << policyFlags << std::dec
4560 << ", event=" << *event;
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004561 }
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07004562 nsecs_t endTime = now() + std::chrono::duration_cast<std::chrono::nanoseconds>(timeout).count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004563
Prabir Pradhan5735a322022-04-11 17:23:34 +00004564 policyFlags |= POLICY_FLAG_INJECTED | POLICY_FLAG_TRUSTED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004565
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004566 // For all injected events, set device id = VIRTUAL_KEYBOARD_ID. The only exception is events
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004567 // that have gone through the InputFilter. If the event passed through the InputFilter, assign
4568 // the provided device id. If the InputFilter is accessibility, and it modifies or synthesizes
4569 // the injected event, it is responsible for setting POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY.
4570 // For those events, we will set FLAG_IS_ACCESSIBILITY_EVENT to allow apps to distinguish them
4571 // from events that originate from actual hardware.
Siarhei Vishniakouf4043212023-09-18 19:33:03 -07004572 DeviceId resolvedDeviceId = VIRTUAL_KEYBOARD_ID;
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004573 if (policyFlags & POLICY_FLAG_FILTERED) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004574 resolvedDeviceId = event->getDeviceId();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004575 }
4576
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004577 std::queue<std::unique_ptr<EventEntry>> injectedEntries;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004578 switch (event->getType()) {
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004579 case InputEventType::KEY: {
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004580 const KeyEvent& incomingKey = static_cast<const KeyEvent&>(*event);
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004581 const int32_t action = incomingKey.getAction();
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004582 int32_t flags = incomingKey.getFlags();
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004583 if (policyFlags & POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY) {
4584 flags |= AKEY_EVENT_FLAG_IS_ACCESSIBILITY_EVENT;
4585 }
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004586 int32_t keyCode = incomingKey.getKeyCode();
4587 int32_t metaState = incomingKey.getMetaState();
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004588 KeyEvent keyEvent;
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004589 keyEvent.initialize(incomingKey.getId(), resolvedDeviceId, incomingKey.getSource(),
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004590 incomingKey.getDisplayId(), INVALID_HMAC, action, flags, keyCode,
4591 incomingKey.getScanCode(), metaState, incomingKey.getRepeatCount(),
4592 incomingKey.getDownTime(), incomingKey.getEventTime());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004593
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004594 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
4595 policyFlags |= POLICY_FLAG_VIRTUAL;
Michael Wright2b3c3302018-03-02 17:19:13 +00004596 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004597
4598 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
4599 android::base::Timer t;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004600 mPolicy.interceptKeyBeforeQueueing(keyEvent, /*byref*/ policyFlags);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004601 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4602 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
4603 std::to_string(t.duration().count()).c_str());
4604 }
4605 }
4606
4607 mLock.lock();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004608 std::unique_ptr<KeyEntry> injectedEntry =
4609 std::make_unique<KeyEntry>(incomingKey.getId(), incomingKey.getEventTime(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004610 resolvedDeviceId, incomingKey.getSource(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004611 incomingKey.getDisplayId(), policyFlags, action,
4612 flags, keyCode, incomingKey.getScanCode(), metaState,
4613 incomingKey.getRepeatCount(),
4614 incomingKey.getDownTime());
4615 injectedEntries.push(std::move(injectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004616 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004617 }
4618
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004619 case InputEventType::MOTION: {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004620 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(*event);
Prabir Pradhanaa561d12021-09-24 06:57:33 -07004621 const bool isPointerEvent =
4622 isFromSource(event->getSource(), AINPUT_SOURCE_CLASS_POINTER);
4623 // If a pointer event has no displayId specified, inject it to the default display.
4624 const uint32_t displayId = isPointerEvent && (event->getDisplayId() == ADISPLAY_ID_NONE)
4625 ? ADISPLAY_ID_DEFAULT
4626 : event->getDisplayId();
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004627 int32_t flags = motionEvent.getFlags();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004628
4629 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004630 nsecs_t eventTime = motionEvent.getEventTime();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004631 android::base::Timer t;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004632 mPolicy.interceptMotionBeforeQueueing(displayId, eventTime, /*byref*/ policyFlags);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004633 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4634 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
4635 std::to_string(t.duration().count()).c_str());
4636 }
4637 }
4638
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004639 if (policyFlags & POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY) {
4640 flags |= AMOTION_EVENT_FLAG_IS_ACCESSIBILITY_EVENT;
4641 }
4642
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004643 mLock.lock();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004644 const nsecs_t* sampleEventTimes = motionEvent.getSampleEventTimes();
4645 const PointerCoords* samplePointerCoords = motionEvent.getSamplePointerCoords();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004646 std::unique_ptr<MotionEntry> injectedEntry =
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004647 std::make_unique<MotionEntry>(motionEvent.getId(), *sampleEventTimes,
4648 resolvedDeviceId, motionEvent.getSource(),
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004649 displayId, policyFlags, motionEvent.getAction(),
4650 motionEvent.getActionButton(), flags,
4651 motionEvent.getMetaState(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004652 motionEvent.getButtonState(),
4653 motionEvent.getClassification(),
4654 motionEvent.getEdgeFlags(),
4655 motionEvent.getXPrecision(),
4656 motionEvent.getYPrecision(),
4657 motionEvent.getRawXCursorPosition(),
4658 motionEvent.getRawYCursorPosition(),
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004659 motionEvent.getDownTime(),
4660 motionEvent.getPointerCount(),
4661 motionEvent.getPointerProperties(),
4662 samplePointerCoords);
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004663 transformMotionEntryForInjectionLocked(*injectedEntry, motionEvent.getTransform());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004664 injectedEntries.push(std::move(injectedEntry));
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004665 for (size_t i = motionEvent.getHistorySize(); i > 0; i--) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004666 sampleEventTimes += 1;
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004667 samplePointerCoords += motionEvent.getPointerCount();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004668 std::unique_ptr<MotionEntry> nextInjectedEntry =
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004669 std::make_unique<MotionEntry>(motionEvent.getId(), *sampleEventTimes,
4670 resolvedDeviceId, motionEvent.getSource(),
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004671 displayId, policyFlags,
4672 motionEvent.getAction(),
4673 motionEvent.getActionButton(), flags,
4674 motionEvent.getMetaState(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004675 motionEvent.getButtonState(),
4676 motionEvent.getClassification(),
4677 motionEvent.getEdgeFlags(),
4678 motionEvent.getXPrecision(),
4679 motionEvent.getYPrecision(),
4680 motionEvent.getRawXCursorPosition(),
4681 motionEvent.getRawYCursorPosition(),
4682 motionEvent.getDownTime(),
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004683 motionEvent.getPointerCount(),
4684 motionEvent.getPointerProperties(),
Prabir Pradhan5beda762021-12-10 09:30:08 +00004685 samplePointerCoords);
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004686 transformMotionEntryForInjectionLocked(*nextInjectedEntry,
4687 motionEvent.getTransform());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004688 injectedEntries.push(std::move(nextInjectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004689 }
4690 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004691 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004692
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004693 default:
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004694 LOG(WARNING) << "Cannot inject " << ftl::enum_string(event->getType()) << " events";
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004695 return InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004696 }
4697
Prabir Pradhan5735a322022-04-11 17:23:34 +00004698 InjectionState* injectionState = new InjectionState(targetUid);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004699 if (syncMode == InputEventInjectionSync::NONE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004700 injectionState->injectionIsAsync = true;
4701 }
4702
4703 injectionState->refCount += 1;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004704 injectedEntries.back()->injectionState = injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004705
4706 bool needWake = false;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004707 while (!injectedEntries.empty()) {
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08004708 if (DEBUG_INJECTION) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07004709 LOG(INFO) << "Injecting " << injectedEntries.front()->getDescription();
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08004710 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004711 needWake |= enqueueInboundEventLocked(std::move(injectedEntries.front()));
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004712 injectedEntries.pop();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004713 }
4714
4715 mLock.unlock();
4716
4717 if (needWake) {
4718 mLooper->wake();
4719 }
4720
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004721 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004722 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004723 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004724
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004725 if (syncMode == InputEventInjectionSync::NONE) {
4726 injectionResult = InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004727 } else {
4728 for (;;) {
4729 injectionResult = injectionState->injectionResult;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004730 if (injectionResult != InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004731 break;
4732 }
4733
4734 nsecs_t remainingTimeout = endTime - now();
4735 if (remainingTimeout <= 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004736 if (DEBUG_INJECTION) {
4737 ALOGD("injectInputEvent - Timed out waiting for injection result "
4738 "to become available.");
4739 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004740 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004741 break;
4742 }
4743
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004744 mInjectionResultAvailable.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004745 }
4746
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004747 if (injectionResult == InputEventInjectionResult::SUCCEEDED &&
4748 syncMode == InputEventInjectionSync::WAIT_FOR_FINISHED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004749 while (injectionState->pendingForegroundDispatches != 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004750 if (DEBUG_INJECTION) {
4751 ALOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
4752 injectionState->pendingForegroundDispatches);
4753 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004754 nsecs_t remainingTimeout = endTime - now();
4755 if (remainingTimeout <= 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004756 if (DEBUG_INJECTION) {
4757 ALOGD("injectInputEvent - Timed out waiting for pending foreground "
4758 "dispatches to finish.");
4759 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004760 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004761 break;
4762 }
4763
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004764 mInjectionSyncFinished.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004765 }
4766 }
4767 }
4768
4769 injectionState->release();
4770 } // release lock
4771
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004772 if (DEBUG_INJECTION) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07004773 LOG(INFO) << "injectInputEvent - Finished with result "
4774 << ftl::enum_string(injectionResult);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004775 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004776
4777 return injectionResult;
4778}
4779
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004780std::unique_ptr<VerifiedInputEvent> InputDispatcher::verifyInputEvent(const InputEvent& event) {
Gang Wange9087892020-01-07 12:17:14 -05004781 std::array<uint8_t, 32> calculatedHmac;
4782 std::unique_ptr<VerifiedInputEvent> result;
4783 switch (event.getType()) {
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004784 case InputEventType::KEY: {
Gang Wange9087892020-01-07 12:17:14 -05004785 const KeyEvent& keyEvent = static_cast<const KeyEvent&>(event);
4786 VerifiedKeyEvent verifiedKeyEvent = verifiedKeyEventFromKeyEvent(keyEvent);
4787 result = std::make_unique<VerifiedKeyEvent>(verifiedKeyEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004788 calculatedHmac = sign(verifiedKeyEvent);
Gang Wange9087892020-01-07 12:17:14 -05004789 break;
4790 }
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004791 case InputEventType::MOTION: {
Gang Wange9087892020-01-07 12:17:14 -05004792 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(event);
4793 VerifiedMotionEvent verifiedMotionEvent =
4794 verifiedMotionEventFromMotionEvent(motionEvent);
4795 result = std::make_unique<VerifiedMotionEvent>(verifiedMotionEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004796 calculatedHmac = sign(verifiedMotionEvent);
Gang Wange9087892020-01-07 12:17:14 -05004797 break;
4798 }
4799 default: {
4800 ALOGE("Cannot verify events of type %" PRId32, event.getType());
4801 return nullptr;
4802 }
4803 }
4804 if (calculatedHmac == INVALID_HMAC) {
4805 return nullptr;
4806 }
tyiu1573a672023-02-21 22:38:32 +00004807 if (0 != CRYPTO_memcmp(calculatedHmac.data(), event.getHmac().data(), calculatedHmac.size())) {
Gang Wange9087892020-01-07 12:17:14 -05004808 return nullptr;
4809 }
4810 return result;
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004811}
4812
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004813void InputDispatcher::setInjectionResult(EventEntry& entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004814 InputEventInjectionResult injectionResult) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004815 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004816 if (injectionState) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004817 if (DEBUG_INJECTION) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07004818 LOG(INFO) << "Setting input event injection result to "
4819 << ftl::enum_string(injectionResult);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004820 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004821
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004822 if (injectionState->injectionIsAsync && !(entry.policyFlags & POLICY_FLAG_FILTERED)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004823 // Log the outcome since the injector did not wait for the injection result.
4824 switch (injectionResult) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004825 case InputEventInjectionResult::SUCCEEDED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004826 ALOGV("Asynchronous input event injection succeeded.");
4827 break;
Prabir Pradhan5735a322022-04-11 17:23:34 +00004828 case InputEventInjectionResult::TARGET_MISMATCH:
4829 ALOGV("Asynchronous input event injection target mismatch.");
4830 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004831 case InputEventInjectionResult::FAILED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004832 ALOGW("Asynchronous input event injection failed.");
4833 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004834 case InputEventInjectionResult::TIMED_OUT:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004835 ALOGW("Asynchronous input event injection timed out.");
4836 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004837 case InputEventInjectionResult::PENDING:
4838 ALOGE("Setting result to 'PENDING' for asynchronous injection");
4839 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004840 }
4841 }
4842
4843 injectionState->injectionResult = injectionResult;
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004844 mInjectionResultAvailable.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004845 }
4846}
4847
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004848void InputDispatcher::transformMotionEntryForInjectionLocked(
4849 MotionEntry& entry, const ui::Transform& injectedTransform) const {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004850 // Input injection works in the logical display coordinate space, but the input pipeline works
4851 // display space, so we need to transform the injected events accordingly.
4852 const auto it = mDisplayInfos.find(entry.displayId);
4853 if (it == mDisplayInfos.end()) return;
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004854 const auto& transformToDisplay = it->second.transform.inverse() * injectedTransform;
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004855
Prabir Pradhand9a2ebe2022-07-20 19:25:13 +00004856 if (entry.xCursorPosition != AMOTION_EVENT_INVALID_CURSOR_POSITION &&
4857 entry.yCursorPosition != AMOTION_EVENT_INVALID_CURSOR_POSITION) {
4858 const vec2 cursor =
4859 MotionEvent::calculateTransformedXY(entry.source, transformToDisplay,
4860 {entry.xCursorPosition, entry.yCursorPosition});
4861 entry.xCursorPosition = cursor.x;
4862 entry.yCursorPosition = cursor.y;
4863 }
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004864 for (uint32_t i = 0; i < entry.pointerCount; i++) {
Prabir Pradhan8e6ce222022-02-24 09:08:54 -08004865 entry.pointerCoords[i] =
4866 MotionEvent::calculateTransformedCoords(entry.source, transformToDisplay,
4867 entry.pointerCoords[i]);
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004868 }
4869}
4870
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004871void InputDispatcher::incrementPendingForegroundDispatches(EventEntry& entry) {
4872 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004873 if (injectionState) {
4874 injectionState->pendingForegroundDispatches += 1;
4875 }
4876}
4877
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004878void InputDispatcher::decrementPendingForegroundDispatches(EventEntry& entry) {
4879 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004880 if (injectionState) {
4881 injectionState->pendingForegroundDispatches -= 1;
4882
4883 if (injectionState->pendingForegroundDispatches == 0) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004884 mInjectionSyncFinished.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004885 }
4886 }
4887}
4888
chaviw98318de2021-05-19 16:45:23 -05004889const std::vector<sp<WindowInfoHandle>>& InputDispatcher::getWindowHandlesLocked(
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004890 int32_t displayId) const {
chaviw98318de2021-05-19 16:45:23 -05004891 static const std::vector<sp<WindowInfoHandle>> EMPTY_WINDOW_HANDLES;
Vishnu Nairad321cd2020-08-20 16:40:21 -07004892 auto it = mWindowHandlesByDisplay.find(displayId);
4893 return it != mWindowHandlesByDisplay.end() ? it->second : EMPTY_WINDOW_HANDLES;
Arthur Hungb92218b2018-08-14 12:00:21 +08004894}
4895
chaviw98318de2021-05-19 16:45:23 -05004896sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(
chaviwfbe5d9c2018-12-26 12:23:37 -08004897 const sp<IBinder>& windowHandleToken) const {
arthurhungbe737672020-06-24 12:29:21 +08004898 if (windowHandleToken == nullptr) {
4899 return nullptr;
4900 }
4901
Arthur Hungb92218b2018-08-14 12:00:21 +08004902 for (auto& it : mWindowHandlesByDisplay) {
chaviw98318de2021-05-19 16:45:23 -05004903 const std::vector<sp<WindowInfoHandle>>& windowHandles = it.second;
4904 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
chaviwfbe5d9c2018-12-26 12:23:37 -08004905 if (windowHandle->getToken() == windowHandleToken) {
Arthur Hungb92218b2018-08-14 12:00:21 +08004906 return windowHandle;
4907 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004908 }
4909 }
Yi Kong9b14ac62018-07-17 13:48:38 -07004910 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004911}
4912
chaviw98318de2021-05-19 16:45:23 -05004913sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(const sp<IBinder>& windowHandleToken,
4914 int displayId) const {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004915 if (windowHandleToken == nullptr) {
4916 return nullptr;
4917 }
4918
chaviw98318de2021-05-19 16:45:23 -05004919 for (const sp<WindowInfoHandle>& windowHandle : getWindowHandlesLocked(displayId)) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004920 if (windowHandle->getToken() == windowHandleToken) {
4921 return windowHandle;
4922 }
4923 }
4924 return nullptr;
4925}
4926
chaviw98318de2021-05-19 16:45:23 -05004927sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(
4928 const sp<WindowInfoHandle>& windowHandle) const {
Mady Mellor017bcd12020-06-23 19:12:00 +00004929 for (auto& it : mWindowHandlesByDisplay) {
chaviw98318de2021-05-19 16:45:23 -05004930 const std::vector<sp<WindowInfoHandle>>& windowHandles = it.second;
4931 for (const sp<WindowInfoHandle>& handle : windowHandles) {
arthurhungbe737672020-06-24 12:29:21 +08004932 if (handle->getId() == windowHandle->getId() &&
4933 handle->getToken() == windowHandle->getToken()) {
Mady Mellor017bcd12020-06-23 19:12:00 +00004934 if (windowHandle->getInfo()->displayId != it.first) {
4935 ALOGE("Found window %s in display %" PRId32
4936 ", but it should belong to display %" PRId32,
4937 windowHandle->getName().c_str(), it.first,
4938 windowHandle->getInfo()->displayId);
4939 }
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004940 return handle;
Arthur Hungb92218b2018-08-14 12:00:21 +08004941 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004942 }
4943 }
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004944 return nullptr;
4945}
4946
chaviw98318de2021-05-19 16:45:23 -05004947sp<WindowInfoHandle> InputDispatcher::getFocusedWindowHandleLocked(int displayId) const {
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004948 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(displayId);
4949 return getWindowHandleLocked(focusedToken, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004950}
4951
Prabir Pradhan33e3baa2022-12-06 20:30:22 +00004952ui::Transform InputDispatcher::getTransformLocked(int32_t displayId) const {
4953 auto displayInfoIt = mDisplayInfos.find(displayId);
4954 return displayInfoIt != mDisplayInfos.end() ? displayInfoIt->second.transform
4955 : kIdentityTransform;
4956}
4957
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004958bool InputDispatcher::canWindowReceiveMotionLocked(const sp<WindowInfoHandle>& window,
4959 const MotionEntry& motionEntry) const {
4960 const WindowInfo& info = *window->getInfo();
4961
4962 // Skip spy window targets that are not valid for targeted injection.
4963 if (const auto err = verifyTargetedInjection(window, motionEntry); err) {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004964 return false;
4965 }
4966
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004967 if (info.inputConfig.test(WindowInfo::InputConfig::PAUSE_DISPATCHING)) {
4968 ALOGI("Not sending touch event to %s because it is paused", window->getName().c_str());
4969 return false;
4970 }
4971
4972 if (info.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL)) {
4973 ALOGW("Not sending touch gesture to %s because it has config NO_INPUT_CHANNEL",
4974 window->getName().c_str());
4975 return false;
4976 }
4977
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07004978 std::shared_ptr<Connection> connection = getConnectionLocked(window->getToken());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004979 if (connection == nullptr) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004980 ALOGW("Not sending touch to %s because there's no corresponding connection",
4981 window->getName().c_str());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004982 return false;
4983 }
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004984
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004985 if (!connection->responsive) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004986 ALOGW("Not sending touch to %s because it is not responsive", window->getName().c_str());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004987 return false;
4988 }
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004989
4990 // Drop events that can't be trusted due to occlusion
4991 const auto [x, y] = resolveTouchedPosition(motionEntry);
4992 TouchOcclusionInfo occlusionInfo = computeTouchOcclusionInfoLocked(window, x, y);
4993 if (!isTouchTrustedLocked(occlusionInfo)) {
4994 if (DEBUG_TOUCH_OCCLUSION) {
Prabir Pradhan82e081e2022-12-06 09:50:09 +00004995 ALOGD("Stack of obscuring windows during untrusted touch (%.1f, %.1f):", x, y);
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004996 for (const auto& log : occlusionInfo.debugInfo) {
4997 ALOGD("%s", log.c_str());
4998 }
4999 }
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00005000 ALOGW("Dropping untrusted touch event due to %s/%s", occlusionInfo.obscuringPackage.c_str(),
5001 occlusionInfo.obscuringUid.toString().c_str());
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07005002 return false;
5003 }
5004
5005 // Drop touch events if requested by input feature
5006 if (shouldDropInput(motionEntry, window)) {
5007 return false;
5008 }
5009
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005010 return true;
5011}
5012
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005013std::shared_ptr<InputChannel> InputDispatcher::getInputChannelLocked(
5014 const sp<IBinder>& token) const {
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005015 auto connectionIt = mConnectionsByToken.find(token);
5016 if (connectionIt == mConnectionsByToken.end()) {
Robert Carr5c8a0262018-10-03 16:30:44 -07005017 return nullptr;
5018 }
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005019 return connectionIt->second->inputChannel;
Robert Carr5c8a0262018-10-03 16:30:44 -07005020}
5021
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005022void InputDispatcher::updateWindowHandlesForDisplayLocked(
chaviw98318de2021-05-19 16:45:23 -05005023 const std::vector<sp<WindowInfoHandle>>& windowInfoHandles, int32_t displayId) {
5024 if (windowInfoHandles.empty()) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005025 // Remove all handles on a display if there are no windows left.
5026 mWindowHandlesByDisplay.erase(displayId);
5027 return;
5028 }
5029
5030 // Since we compare the pointer of input window handles across window updates, we need
5031 // to make sure the handle object for the same window stays unchanged across updates.
chaviw98318de2021-05-19 16:45:23 -05005032 const std::vector<sp<WindowInfoHandle>>& oldHandles = getWindowHandlesLocked(displayId);
5033 std::unordered_map<int32_t /*id*/, sp<WindowInfoHandle>> oldHandlesById;
5034 for (const sp<WindowInfoHandle>& handle : oldHandles) {
chaviwaf87b3e2019-10-01 16:59:28 -07005035 oldHandlesById[handle->getId()] = handle;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005036 }
5037
chaviw98318de2021-05-19 16:45:23 -05005038 std::vector<sp<WindowInfoHandle>> newHandles;
5039 for (const sp<WindowInfoHandle>& handle : windowInfoHandles) {
chaviw98318de2021-05-19 16:45:23 -05005040 const WindowInfo* info = handle->getInfo();
Siarhei Vishniakou64452932020-11-06 17:51:32 -06005041 if (getInputChannelLocked(handle->getToken()) == nullptr) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005042 const bool noInputChannel =
Prabir Pradhan51e7db02022-02-07 06:02:57 -08005043 info->inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005044 const bool canReceiveInput =
5045 !info->inputConfig.test(WindowInfo::InputConfig::NOT_TOUCHABLE) ||
5046 !info->inputConfig.test(WindowInfo::InputConfig::NOT_FOCUSABLE);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005047 if (canReceiveInput && !noInputChannel) {
John Recke0710582019-09-26 13:46:12 -07005048 ALOGV("Window handle %s has no registered input channel",
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005049 handle->getName().c_str());
Robert Carr2984b7a2020-04-13 17:06:45 -07005050 continue;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005051 }
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005052 }
5053
5054 if (info->displayId != displayId) {
5055 ALOGE("Window %s updated by wrong display %d, should belong to display %d",
5056 handle->getName().c_str(), displayId, info->displayId);
5057 continue;
5058 }
5059
Robert Carredd13602020-04-13 17:24:34 -07005060 if ((oldHandlesById.find(handle->getId()) != oldHandlesById.end()) &&
5061 (oldHandlesById.at(handle->getId())->getToken() == handle->getToken())) {
chaviw98318de2021-05-19 16:45:23 -05005062 const sp<WindowInfoHandle>& oldHandle = oldHandlesById.at(handle->getId());
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005063 oldHandle->updateFrom(handle);
5064 newHandles.push_back(oldHandle);
5065 } else {
5066 newHandles.push_back(handle);
5067 }
5068 }
5069
5070 // Insert or replace
5071 mWindowHandlesByDisplay[displayId] = newHandles;
5072}
5073
Arthur Hungb92218b2018-08-14 12:00:21 +08005074/**
5075 * Called from InputManagerService, update window handle list by displayId that can receive input.
5076 * A window handle contains information about InputChannel, Touch Region, Types, Focused,...
5077 * If set an empty list, remove all handles from the specific display.
5078 * For focused handle, check if need to change and send a cancel event to previous one.
5079 * For removed handle, check if need to send a cancel event if already in touch.
5080 */
Arthur Hung72d8dc32020-03-28 00:48:39 +00005081void InputDispatcher::setInputWindowsLocked(
chaviw98318de2021-05-19 16:45:23 -05005082 const std::vector<sp<WindowInfoHandle>>& windowInfoHandles, int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005083 if (DEBUG_FOCUS) {
5084 std::string windowList;
chaviw98318de2021-05-19 16:45:23 -05005085 for (const sp<WindowInfoHandle>& iwh : windowInfoHandles) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005086 windowList += iwh->getName() + " ";
5087 }
5088 ALOGD("setInputWindows displayId=%" PRId32 " %s", displayId, windowList.c_str());
5089 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005090
Prabir Pradhand65552b2021-10-07 11:23:50 -07005091 // Check preconditions for new input windows
chaviw98318de2021-05-19 16:45:23 -05005092 for (const sp<WindowInfoHandle>& window : windowInfoHandles) {
Prabir Pradhand65552b2021-10-07 11:23:50 -07005093 const WindowInfo& info = *window->getInfo();
5094
5095 // Ensure all tokens are null if the window has feature NO_INPUT_CHANNEL
Prabir Pradhan51e7db02022-02-07 06:02:57 -08005096 const bool noInputWindow = info.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005097 if (noInputWindow && window->getToken() != nullptr) {
5098 ALOGE("%s has feature NO_INPUT_WINDOW, but a non-null token. Clearing",
5099 window->getName().c_str());
5100 window->releaseChannel();
5101 }
Prabir Pradhand65552b2021-10-07 11:23:50 -07005102
Prabir Pradhan5c85e052021-12-22 02:27:12 -08005103 // Ensure all spy windows are trusted overlays
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005104 LOG_ALWAYS_FATAL_IF(info.isSpy() &&
5105 !info.inputConfig.test(
5106 WindowInfo::InputConfig::TRUSTED_OVERLAY),
Prabir Pradhan5c85e052021-12-22 02:27:12 -08005107 "%s has feature SPY, but is not a trusted overlay.",
5108 window->getName().c_str());
5109
Prabir Pradhand65552b2021-10-07 11:23:50 -07005110 // Ensure all stylus interceptors are trusted overlays
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005111 LOG_ALWAYS_FATAL_IF(info.interceptsStylus() &&
5112 !info.inputConfig.test(
5113 WindowInfo::InputConfig::TRUSTED_OVERLAY),
Prabir Pradhand65552b2021-10-07 11:23:50 -07005114 "%s has feature INTERCEPTS_STYLUS, but is not a trusted overlay.",
5115 window->getName().c_str());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005116 }
5117
Arthur Hung72d8dc32020-03-28 00:48:39 +00005118 // Copy old handles for release if they are no longer present.
chaviw98318de2021-05-19 16:45:23 -05005119 const std::vector<sp<WindowInfoHandle>> oldWindowHandles = getWindowHandlesLocked(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005120
chaviw98318de2021-05-19 16:45:23 -05005121 updateWindowHandlesForDisplayLocked(windowInfoHandles, displayId);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005122
chaviw98318de2021-05-19 16:45:23 -05005123 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Arthur Hung72d8dc32020-03-28 00:48:39 +00005124
Vishnu Nairc519ff72021-01-21 08:23:08 -08005125 std::optional<FocusResolver::FocusChanges> changes =
5126 mFocusResolver.setInputWindows(displayId, windowHandles);
5127 if (changes) {
5128 onFocusChangedLocked(*changes);
Arthur Hung72d8dc32020-03-28 00:48:39 +00005129 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005130
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005131 std::unordered_map<int32_t, TouchState>::iterator stateIt =
5132 mTouchStatesByDisplay.find(displayId);
5133 if (stateIt != mTouchStatesByDisplay.end()) {
5134 TouchState& state = stateIt->second;
Arthur Hung72d8dc32020-03-28 00:48:39 +00005135 for (size_t i = 0; i < state.windows.size();) {
5136 TouchedWindow& touchedWindow = state.windows[i];
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07005137 if (getWindowHandleLocked(touchedWindow.windowHandle) == nullptr) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005138 if (DEBUG_FOCUS) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00005139 ALOGD("Touched window was removed: %s in display %" PRId32,
5140 touchedWindow.windowHandle->getName().c_str(), displayId);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005141 }
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005142 std::shared_ptr<InputChannel> touchedInputChannel =
Arthur Hung72d8dc32020-03-28 00:48:39 +00005143 getInputChannelLocked(touchedWindow.windowHandle->getToken());
5144 if (touchedInputChannel != nullptr) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00005145 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
Arthur Hung72d8dc32020-03-28 00:48:39 +00005146 "touched window was removed");
5147 synthesizeCancelationEventsForInputChannelLocked(touchedInputChannel, options);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00005148 // Since we are about to drop the touch, cancel the events for the wallpaper as
5149 // well.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005150 if (touchedWindow.targetFlags.test(InputTarget::Flags::FOREGROUND) &&
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005151 touchedWindow.windowHandle->getInfo()->inputConfig.test(
5152 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER)) {
Siarhei Vishniakouca205502021-07-16 21:31:58 +00005153 sp<WindowInfoHandle> wallpaper = state.getWallpaperWindow();
Arthur Hungc539dbb2022-12-08 07:45:36 +00005154 synthesizeCancelationEventsForWindowLocked(wallpaper, options);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00005155 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005156 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00005157 state.windows.erase(state.windows.begin() + i);
5158 } else {
5159 ++i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005160 }
5161 }
arthurhungb89ccb02020-12-30 16:19:01 +08005162
arthurhung6d4bed92021-03-17 11:59:33 +08005163 // If drag window is gone, it would receive a cancel event and broadcast the DRAG_END. We
arthurhungb89ccb02020-12-30 16:19:01 +08005164 // could just clear the state here.
Arthur Hung3915c1f2022-05-31 07:17:17 +00005165 if (mDragState && mDragState->dragWindow->getInfo()->displayId == displayId &&
arthurhung6d4bed92021-03-17 11:59:33 +08005166 std::find(windowHandles.begin(), windowHandles.end(), mDragState->dragWindow) ==
arthurhungb89ccb02020-12-30 16:19:01 +08005167 windowHandles.end()) {
Arthur Hung3915c1f2022-05-31 07:17:17 +00005168 ALOGI("Drag window went away: %s", mDragState->dragWindow->getName().c_str());
5169 sendDropWindowCommandLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08005170 mDragState.reset();
arthurhungb89ccb02020-12-30 16:19:01 +08005171 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00005172 }
Arthur Hung25e2af12020-03-26 12:58:37 +00005173
Arthur Hung72d8dc32020-03-28 00:48:39 +00005174 // Release information for windows that are no longer present.
5175 // This ensures that unused input channels are released promptly.
5176 // Otherwise, they might stick around until the window handle is destroyed
5177 // which might not happen until the next GC.
chaviw98318de2021-05-19 16:45:23 -05005178 for (const sp<WindowInfoHandle>& oldWindowHandle : oldWindowHandles) {
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07005179 if (getWindowHandleLocked(oldWindowHandle) == nullptr) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00005180 if (DEBUG_FOCUS) {
5181 ALOGD("Window went away: %s", oldWindowHandle->getName().c_str());
Arthur Hung25e2af12020-03-26 12:58:37 +00005182 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00005183 oldWindowHandle->releaseChannel();
Arthur Hung25e2af12020-03-26 12:58:37 +00005184 }
chaviw291d88a2019-02-14 10:33:58 -08005185 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005186}
5187
5188void InputDispatcher::setFocusedApplication(
Chris Yea209fde2020-07-22 13:54:51 -07005189 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005190 if (DEBUG_FOCUS) {
5191 ALOGD("setFocusedApplication displayId=%" PRId32 " %s", displayId,
5192 inputApplicationHandle ? inputApplicationHandle->getName().c_str() : "<nullptr>");
5193 }
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05005194 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005195 std::scoped_lock _l(mLock);
Vishnu Nair599f1412021-06-21 10:39:58 -07005196 setFocusedApplicationLocked(displayId, inputApplicationHandle);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005197 } // release lock
5198
5199 // Wake up poll loop since it may need to make new input dispatching choices.
5200 mLooper->wake();
5201}
5202
Vishnu Nair599f1412021-06-21 10:39:58 -07005203void InputDispatcher::setFocusedApplicationLocked(
5204 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
5205 std::shared_ptr<InputApplicationHandle> oldFocusedApplicationHandle =
5206 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
5207
5208 if (sharedPointersEqual(oldFocusedApplicationHandle, inputApplicationHandle)) {
5209 return; // This application is already focused. No need to wake up or change anything.
5210 }
5211
5212 // Set the new application handle.
5213 if (inputApplicationHandle != nullptr) {
5214 mFocusedApplicationHandlesByDisplay[displayId] = inputApplicationHandle;
5215 } else {
5216 mFocusedApplicationHandlesByDisplay.erase(displayId);
5217 }
5218
5219 // No matter what the old focused application was, stop waiting on it because it is
5220 // no longer focused.
5221 resetNoFocusedWindowTimeoutLocked();
5222}
5223
Tiger Huang721e26f2018-07-24 22:26:19 +08005224/**
5225 * Sets the focused display, which is responsible for receiving focus-dispatched input events where
5226 * the display not specified.
5227 *
5228 * We track any unreleased events for each window. If a window loses the ability to receive the
5229 * released event, we will send a cancel event to it. So when the focused display is changed, we
5230 * cancel all the unreleased display-unspecified events for the focused window on the old focused
5231 * display. The display-specified events won't be affected.
5232 */
5233void InputDispatcher::setFocusedDisplay(int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005234 if (DEBUG_FOCUS) {
5235 ALOGD("setFocusedDisplay displayId=%" PRId32, displayId);
5236 }
Tiger Huang721e26f2018-07-24 22:26:19 +08005237 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005238 std::scoped_lock _l(mLock);
Tiger Huang721e26f2018-07-24 22:26:19 +08005239
5240 if (mFocusedDisplayId != displayId) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07005241 sp<IBinder> oldFocusedWindowToken =
Vishnu Nairc519ff72021-01-21 08:23:08 -08005242 mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07005243 if (oldFocusedWindowToken != nullptr) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005244 std::shared_ptr<InputChannel> inputChannel =
Vishnu Nairad321cd2020-08-20 16:40:21 -07005245 getInputChannelLocked(oldFocusedWindowToken);
Tiger Huang721e26f2018-07-24 22:26:19 +08005246 if (inputChannel != nullptr) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005247 CancelationOptions
Michael Wrightfb04fd52022-11-24 22:31:11 +00005248 options(CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005249 "The display which contains this window no longer has focus.");
Michael Wright3dd60e22019-03-27 22:06:44 +00005250 options.displayId = ADISPLAY_ID_NONE;
Tiger Huang721e26f2018-07-24 22:26:19 +08005251 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
5252 }
5253 }
5254 mFocusedDisplayId = displayId;
5255
Chris Ye3c2d6f52020-08-09 10:39:48 -07005256 // Find new focused window and validate
Vishnu Nairc519ff72021-01-21 08:23:08 -08005257 sp<IBinder> newFocusedWindowToken = mFocusResolver.getFocusedWindowToken(displayId);
Prabir Pradhancef936d2021-07-21 16:17:52 +00005258 sendFocusChangedCommandLocked(oldFocusedWindowToken, newFocusedWindowToken);
Robert Carrf759f162018-11-13 12:57:11 -08005259
Vishnu Nairad321cd2020-08-20 16:40:21 -07005260 if (newFocusedWindowToken == nullptr) {
Tiger Huang721e26f2018-07-24 22:26:19 +08005261 ALOGW("Focused display #%" PRId32 " does not have a focused window.", displayId);
Vishnu Nairc519ff72021-01-21 08:23:08 -08005262 if (mFocusResolver.hasFocusedWindowTokens()) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07005263 ALOGE("But another display has a focused window\n%s",
Vishnu Nairc519ff72021-01-21 08:23:08 -08005264 mFocusResolver.dumpFocusedWindows().c_str());
Tiger Huang721e26f2018-07-24 22:26:19 +08005265 }
5266 }
5267 }
Tiger Huang721e26f2018-07-24 22:26:19 +08005268 } // release lock
5269
5270 // Wake up poll loop since it may need to make new input dispatching choices.
5271 mLooper->wake();
5272}
5273
Michael Wrightd02c5b62014-02-10 15:10:22 -08005274void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005275 if (DEBUG_FOCUS) {
5276 ALOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
5277 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005278
5279 bool changed;
5280 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005281 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005282
5283 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
5284 if (mDispatchFrozen && !frozen) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005285 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005286 }
5287
5288 if (mDispatchEnabled && !enabled) {
5289 resetAndDropEverythingLocked("dispatcher is being disabled");
5290 }
5291
5292 mDispatchEnabled = enabled;
5293 mDispatchFrozen = frozen;
5294 changed = true;
5295 } else {
5296 changed = false;
5297 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005298 } // release lock
5299
5300 if (changed) {
5301 // Wake up poll loop since it may need to make new input dispatching choices.
5302 mLooper->wake();
5303 }
5304}
5305
5306void InputDispatcher::setInputFilterEnabled(bool enabled) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005307 if (DEBUG_FOCUS) {
5308 ALOGD("setInputFilterEnabled: enabled=%d", enabled);
5309 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005310
5311 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005312 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005313
5314 if (mInputFilterEnabled == enabled) {
5315 return;
5316 }
5317
5318 mInputFilterEnabled = enabled;
5319 resetAndDropEverythingLocked("input filter is being enabled or disabled");
5320 } // release lock
5321
5322 // Wake up poll loop since there might be work to do to drop everything.
5323 mLooper->wake();
5324}
5325
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005326bool InputDispatcher::setInTouchMode(bool inTouchMode, gui::Pid pid, gui::Uid uid,
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00005327 bool hasPermission, int32_t displayId) {
Antonio Kantekf16f2832021-09-28 04:39:20 +00005328 bool needWake = false;
5329 {
5330 std::scoped_lock lock(mLock);
Antonio Kantek15beb512022-06-13 22:35:41 +00005331 ALOGD_IF(DEBUG_TOUCH_MODE,
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005332 "Request to change touch mode to %s (calling pid=%s, uid=%s, "
Antonio Kantek15beb512022-06-13 22:35:41 +00005333 "hasPermission=%s, target displayId=%d, mTouchModePerDisplay[displayId]=%s)",
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005334 toString(inTouchMode), pid.toString().c_str(), uid.toString().c_str(),
5335 toString(hasPermission), displayId,
Antonio Kantek15beb512022-06-13 22:35:41 +00005336 mTouchModePerDisplay.count(displayId) == 0
5337 ? "not set"
5338 : std::to_string(mTouchModePerDisplay[displayId]).c_str());
5339
Antonio Kantek15beb512022-06-13 22:35:41 +00005340 auto touchModeIt = mTouchModePerDisplay.find(displayId);
5341 if (touchModeIt != mTouchModePerDisplay.end() && touchModeIt->second == inTouchMode) {
Antonio Kantekea47acb2021-12-23 12:41:25 -08005342 return false;
Antonio Kantekf16f2832021-09-28 04:39:20 +00005343 }
Antonio Kantekea47acb2021-12-23 12:41:25 -08005344 if (!hasPermission) {
Antonio Kantek48710e42022-03-24 14:19:30 -07005345 if (!focusedWindowIsOwnedByLocked(pid, uid) &&
5346 !recentWindowsAreOwnedByLocked(pid, uid)) {
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005347 ALOGD("Touch mode switch rejected, caller (pid=%s, uid=%s) doesn't own the focused "
Antonio Kantek48710e42022-03-24 14:19:30 -07005348 "window nor none of the previously interacted window",
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005349 pid.toString().c_str(), uid.toString().c_str());
Antonio Kantekea47acb2021-12-23 12:41:25 -08005350 return false;
5351 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00005352 }
Antonio Kantek15beb512022-06-13 22:35:41 +00005353 mTouchModePerDisplay[displayId] = inTouchMode;
5354 auto entry = std::make_unique<TouchModeEntry>(mIdGenerator.nextId(), now(), inTouchMode,
5355 displayId);
Antonio Kantekf16f2832021-09-28 04:39:20 +00005356 needWake = enqueueInboundEventLocked(std::move(entry));
5357 } // release lock
5358
5359 if (needWake) {
5360 mLooper->wake();
5361 }
Antonio Kantekea47acb2021-12-23 12:41:25 -08005362 return true;
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -08005363}
5364
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005365bool InputDispatcher::focusedWindowIsOwnedByLocked(gui::Pid pid, gui::Uid uid) {
Antonio Kantek48710e42022-03-24 14:19:30 -07005366 const sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
5367 if (focusedToken == nullptr) {
5368 return false;
5369 }
5370 sp<WindowInfoHandle> windowHandle = getWindowHandleLocked(focusedToken);
5371 return isWindowOwnedBy(windowHandle, pid, uid);
5372}
5373
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005374bool InputDispatcher::recentWindowsAreOwnedByLocked(gui::Pid pid, gui::Uid uid) {
Antonio Kantek48710e42022-03-24 14:19:30 -07005375 return std::find_if(mInteractionConnectionTokens.begin(), mInteractionConnectionTokens.end(),
5376 [&](const sp<IBinder>& connectionToken) REQUIRES(mLock) {
5377 const sp<WindowInfoHandle> windowHandle =
5378 getWindowHandleLocked(connectionToken);
5379 return isWindowOwnedBy(windowHandle, pid, uid);
5380 }) != mInteractionConnectionTokens.end();
5381}
5382
Bernardo Rufinoea97d182020-08-19 14:43:14 +01005383void InputDispatcher::setMaximumObscuringOpacityForTouch(float opacity) {
5384 if (opacity < 0 || opacity > 1) {
5385 LOG_ALWAYS_FATAL("Maximum obscuring opacity for touch should be >= 0 and <= 1");
5386 return;
5387 }
5388
5389 std::scoped_lock lock(mLock);
5390 mMaximumObscuringOpacityForTouch = opacity;
5391}
5392
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005393std::tuple<TouchState*, TouchedWindow*, int32_t /*displayId*/>
5394InputDispatcher::findTouchStateWindowAndDisplayLocked(const sp<IBinder>& token) {
Arthur Hungabbb9d82021-09-01 14:52:30 +00005395 for (auto& [displayId, state] : mTouchStatesByDisplay) {
5396 for (TouchedWindow& w : state.windows) {
5397 if (w.windowHandle->getToken() == token) {
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005398 return std::make_tuple(&state, &w, displayId);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005399 }
5400 }
5401 }
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005402 return std::make_tuple(nullptr, nullptr, ADISPLAY_ID_DEFAULT);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005403}
5404
arthurhungb89ccb02020-12-30 16:19:01 +08005405bool InputDispatcher::transferTouchFocus(const sp<IBinder>& fromToken, const sp<IBinder>& toToken,
5406 bool isDragDrop) {
chaviwfbe5d9c2018-12-26 12:23:37 -08005407 if (fromToken == toToken) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005408 if (DEBUG_FOCUS) {
5409 ALOGD("Trivial transfer to same window.");
5410 }
chaviwfbe5d9c2018-12-26 12:23:37 -08005411 return true;
5412 }
5413
Michael Wrightd02c5b62014-02-10 15:10:22 -08005414 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005415 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005416
Arthur Hungabbb9d82021-09-01 14:52:30 +00005417 // Find the target touch state and touched window by fromToken.
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005418 auto [state, touchedWindow, displayId] = findTouchStateWindowAndDisplayLocked(fromToken);
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005419
Arthur Hungabbb9d82021-09-01 14:52:30 +00005420 if (state == nullptr || touchedWindow == nullptr) {
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005421 ALOGD("Touch transfer failed because from window is not being touched.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005422 return false;
5423 }
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005424 std::set<int32_t> deviceIds = touchedWindow->getTouchingDeviceIds();
5425 if (deviceIds.size() != 1) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07005426 LOG(INFO) << "Can't transfer touch. Currently touching devices: " << dumpSet(deviceIds)
5427 << " for window: " << touchedWindow->dump();
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005428 return false;
5429 }
5430 const int32_t deviceId = *deviceIds.begin();
Arthur Hungabbb9d82021-09-01 14:52:30 +00005431
Arthur Hungabbb9d82021-09-01 14:52:30 +00005432 sp<WindowInfoHandle> toWindowHandle = getWindowHandleLocked(toToken, displayId);
5433 if (toWindowHandle == nullptr) {
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005434 ALOGW("Cannot transfer touch because to window not found.");
Arthur Hungabbb9d82021-09-01 14:52:30 +00005435 return false;
5436 }
5437
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005438 if (DEBUG_FOCUS) {
5439 ALOGD("transferTouchFocus: fromWindowHandle=%s, toWindowHandle=%s",
Arthur Hungabbb9d82021-09-01 14:52:30 +00005440 touchedWindow->windowHandle->getName().c_str(),
5441 toWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005442 }
5443
Arthur Hungabbb9d82021-09-01 14:52:30 +00005444 // Erase old window.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005445 ftl::Flags<InputTarget::Flags> oldTargetFlags = touchedWindow->targetFlags;
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005446 std::bitset<MAX_POINTER_ID + 1> pointerIds = touchedWindow->getTouchingPointers(deviceId);
Arthur Hungc539dbb2022-12-08 07:45:36 +00005447 sp<WindowInfoHandle> fromWindowHandle = touchedWindow->windowHandle;
Arthur Hungabbb9d82021-09-01 14:52:30 +00005448 state->removeWindowByToken(fromToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005449
Arthur Hungabbb9d82021-09-01 14:52:30 +00005450 // Add new window.
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00005451 nsecs_t downTimeInTarget = now();
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005452 ftl::Flags<InputTarget::Flags> newTargetFlags =
5453 oldTargetFlags & (InputTarget::Flags::SPLIT | InputTarget::Flags::DISPATCH_AS_IS);
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00005454 if (canReceiveForegroundTouches(*toWindowHandle->getInfo())) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005455 newTargetFlags |= InputTarget::Flags::FOREGROUND;
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00005456 }
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005457 state->addOrUpdateWindow(toWindowHandle, newTargetFlags, deviceId, pointerIds,
5458 downTimeInTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005459
Arthur Hungabbb9d82021-09-01 14:52:30 +00005460 // Store the dragging window.
5461 if (isDragDrop) {
Arthur Hungb75c2aa2022-07-15 09:35:36 +00005462 if (pointerIds.count() != 1) {
5463 ALOGW("The drag and drop cannot be started when there is no pointer or more than 1"
5464 " pointer on the window.");
Arthur Hung54745652022-04-20 07:17:41 +00005465 return false;
5466 }
Arthur Hungb75c2aa2022-07-15 09:35:36 +00005467 // Track the pointer id for drag window and generate the drag state.
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08005468 const size_t id = firstMarkedBit(pointerIds);
Arthur Hung54745652022-04-20 07:17:41 +00005469 mDragState = std::make_unique<DragState>(toWindowHandle, id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005470 }
5471
Arthur Hungabbb9d82021-09-01 14:52:30 +00005472 // Synthesize cancel for old window and down for new window.
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07005473 std::shared_ptr<Connection> fromConnection = getConnectionLocked(fromToken);
5474 std::shared_ptr<Connection> toConnection = getConnectionLocked(toToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005475 if (fromConnection != nullptr && toConnection != nullptr) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08005476 fromConnection->inputState.mergePointerStateTo(toConnection->inputState);
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005477 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
5478 "transferring touch from this window to another window");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005479 synthesizeCancelationEventsForConnectionLocked(fromConnection, options);
Arthur Hungc539dbb2022-12-08 07:45:36 +00005480 synthesizePointerDownEventsForConnectionLocked(downTimeInTarget, toConnection,
5481 newTargetFlags);
5482
5483 // Check if the wallpaper window should deliver the corresponding event.
5484 transferWallpaperTouch(oldTargetFlags, newTargetFlags, fromWindowHandle, toWindowHandle,
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005485 *state, deviceId, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005486 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005487 } // release lock
5488
5489 // Wake up poll loop since it may need to make new input dispatching choices.
5490 mLooper->wake();
5491 return true;
5492}
5493
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005494/**
5495 * Get the touched foreground window on the given display.
5496 * Return null if there are no windows touched on that display, or if more than one foreground
5497 * window is being touched.
5498 */
5499sp<WindowInfoHandle> InputDispatcher::findTouchedForegroundWindowLocked(int32_t displayId) const {
5500 auto stateIt = mTouchStatesByDisplay.find(displayId);
5501 if (stateIt == mTouchStatesByDisplay.end()) {
5502 ALOGI("No touch state on display %" PRId32, displayId);
5503 return nullptr;
5504 }
5505
5506 const TouchState& state = stateIt->second;
5507 sp<WindowInfoHandle> touchedForegroundWindow;
5508 // If multiple foreground windows are touched, return nullptr
5509 for (const TouchedWindow& window : state.windows) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005510 if (window.targetFlags.test(InputTarget::Flags::FOREGROUND)) {
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005511 if (touchedForegroundWindow != nullptr) {
5512 ALOGI("Two or more foreground windows: %s and %s",
5513 touchedForegroundWindow->getName().c_str(),
5514 window.windowHandle->getName().c_str());
5515 return nullptr;
5516 }
5517 touchedForegroundWindow = window.windowHandle;
5518 }
5519 }
5520 return touchedForegroundWindow;
5521}
5522
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005523// Binder call
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005524bool InputDispatcher::transferTouch(const sp<IBinder>& destChannelToken, int32_t displayId) {
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005525 sp<IBinder> fromToken;
5526 { // acquire lock
5527 std::scoped_lock _l(mLock);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005528 sp<WindowInfoHandle> toWindowHandle = getWindowHandleLocked(destChannelToken, displayId);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005529 if (toWindowHandle == nullptr) {
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005530 ALOGW("Could not find window associated with token=%p on display %" PRId32,
5531 destChannelToken.get(), displayId);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005532 return false;
5533 }
5534
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005535 sp<WindowInfoHandle> from = findTouchedForegroundWindowLocked(displayId);
5536 if (from == nullptr) {
5537 ALOGE("Could not find a source window in %s for %p", __func__, destChannelToken.get());
5538 return false;
5539 }
5540
5541 fromToken = from->getToken();
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005542 } // release lock
5543
5544 return transferTouchFocus(fromToken, destChannelToken);
5545}
5546
Michael Wrightd02c5b62014-02-10 15:10:22 -08005547void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005548 if (DEBUG_FOCUS) {
5549 ALOGD("Resetting and dropping all events (%s).", reason);
5550 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005551
Michael Wrightfb04fd52022-11-24 22:31:11 +00005552 CancelationOptions options(CancelationOptions::Mode::CANCEL_ALL_EVENTS, reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005553 synthesizeCancelationEventsForAllConnectionsLocked(options);
5554
5555 resetKeyRepeatLocked();
5556 releasePendingEventLocked();
5557 drainInboundQueueLocked();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005558 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005559
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005560 mAnrTracker.clear();
Jeff Brownf086ddb2014-02-11 14:28:48 -08005561 mTouchStatesByDisplay.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005562}
5563
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005564void InputDispatcher::logDispatchStateLocked() const {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005565 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005566 dumpDispatchStateLocked(dump);
5567
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005568 std::istringstream stream(dump);
5569 std::string line;
5570
5571 while (std::getline(stream, line, '\n')) {
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07005572 ALOGI("%s", line.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005573 }
5574}
5575
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005576std::string InputDispatcher::dumpPointerCaptureStateLocked() const {
Prabir Pradhan99987712020-11-10 18:43:05 -08005577 std::string dump;
5578
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005579 dump += StringPrintf(INDENT "Pointer Capture Requested: %s\n",
5580 toString(mCurrentPointerCaptureRequest.enable));
Prabir Pradhan99987712020-11-10 18:43:05 -08005581
5582 std::string windowName = "None";
5583 if (mWindowTokenWithPointerCapture) {
chaviw98318de2021-05-19 16:45:23 -05005584 const sp<WindowInfoHandle> captureWindowHandle =
Prabir Pradhan99987712020-11-10 18:43:05 -08005585 getWindowHandleLocked(mWindowTokenWithPointerCapture);
5586 windowName = captureWindowHandle ? captureWindowHandle->getName().c_str()
5587 : "token has capture without window";
5588 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005589 dump += StringPrintf(INDENT "Current Window with Pointer Capture: %s\n", windowName.c_str());
Prabir Pradhan99987712020-11-10 18:43:05 -08005590
5591 return dump;
5592}
5593
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005594void InputDispatcher::dumpDispatchStateLocked(std::string& dump) const {
Siarhei Vishniakou043a3ec2019-05-01 11:30:46 -07005595 dump += StringPrintf(INDENT "DispatchEnabled: %s\n", toString(mDispatchEnabled));
5596 dump += StringPrintf(INDENT "DispatchFrozen: %s\n", toString(mDispatchFrozen));
5597 dump += StringPrintf(INDENT "InputFilterEnabled: %s\n", toString(mInputFilterEnabled));
Tiger Huang721e26f2018-07-24 22:26:19 +08005598 dump += StringPrintf(INDENT "FocusedDisplayId: %" PRId32 "\n", mFocusedDisplayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005599
Tiger Huang721e26f2018-07-24 22:26:19 +08005600 if (!mFocusedApplicationHandlesByDisplay.empty()) {
5601 dump += StringPrintf(INDENT "FocusedApplications:\n");
5602 for (auto& it : mFocusedApplicationHandlesByDisplay) {
5603 const int32_t displayId = it.first;
Chris Yea209fde2020-07-22 13:54:51 -07005604 const std::shared_ptr<InputApplicationHandle>& applicationHandle = it.second;
Siarhei Vishniakou70622952020-07-30 11:17:23 -05005605 const std::chrono::duration timeout =
5606 applicationHandle->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005607 dump += StringPrintf(INDENT2 "displayId=%" PRId32
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005608 ", name='%s', dispatchingTimeout=%" PRId64 "ms\n",
Siarhei Vishniakou70622952020-07-30 11:17:23 -05005609 displayId, applicationHandle->getName().c_str(), millis(timeout));
Tiger Huang721e26f2018-07-24 22:26:19 +08005610 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005611 } else {
Tiger Huang721e26f2018-07-24 22:26:19 +08005612 dump += StringPrintf(INDENT "FocusedApplications: <none>\n");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005613 }
Tiger Huang721e26f2018-07-24 22:26:19 +08005614
Vishnu Nairc519ff72021-01-21 08:23:08 -08005615 dump += mFocusResolver.dump();
Prabir Pradhan99987712020-11-10 18:43:05 -08005616 dump += dumpPointerCaptureStateLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005617
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005618 if (!mTouchStatesByDisplay.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005619 dump += StringPrintf(INDENT "TouchStatesByDisplay:\n");
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005620 for (const auto& [displayId, state] : mTouchStatesByDisplay) {
Siarhei Vishniakou6e1e9872022-11-08 17:51:35 -08005621 std::string touchStateDump = addLinePrefix(state.dump(), INDENT2);
5622 dump += INDENT2 + std::to_string(displayId) + " : " + touchStateDump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005623 }
5624 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005625 dump += INDENT "TouchStates: <no displays touched>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005626 }
5627
arthurhung6d4bed92021-03-17 11:59:33 +08005628 if (mDragState) {
5629 dump += StringPrintf(INDENT "DragState:\n");
5630 mDragState->dump(dump, INDENT2);
5631 }
5632
Arthur Hungb92218b2018-08-14 12:00:21 +08005633 if (!mWindowHandlesByDisplay.empty()) {
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005634 for (const auto& [displayId, windowHandles] : mWindowHandlesByDisplay) {
5635 dump += StringPrintf(INDENT "Display: %" PRId32 "\n", displayId);
5636 if (const auto& it = mDisplayInfos.find(displayId); it != mDisplayInfos.end()) {
5637 const auto& displayInfo = it->second;
5638 dump += StringPrintf(INDENT2 "logicalSize=%dx%d\n", displayInfo.logicalWidth,
5639 displayInfo.logicalHeight);
5640 displayInfo.transform.dump(dump, "transform", INDENT4);
5641 } else {
5642 dump += INDENT2 "No DisplayInfo found!\n";
5643 }
5644
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08005645 if (!windowHandles.empty()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08005646 dump += INDENT2 "Windows:\n";
5647 for (size_t i = 0; i < windowHandles.size(); i++) {
chaviw98318de2021-05-19 16:45:23 -05005648 const sp<WindowInfoHandle>& windowHandle = windowHandles[i];
5649 const WindowInfo* windowInfo = windowHandle->getInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005650
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00005651 dump += StringPrintf(INDENT3 "%zu: name='%s', id=%" PRId32 ", displayId=%d, "
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005652 "inputConfig=%s, alpha=%.2f, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005653 "frame=[%d,%d][%d,%d], globalScale=%f, "
Bernardo Rufino49d99e42021-01-18 15:16:59 +00005654 "applicationInfo.name=%s, "
5655 "applicationInfo.token=%s, "
chaviw1ff3d1e2020-07-01 15:53:47 -07005656 "touchableRegion=",
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00005657 i, windowInfo->name.c_str(), windowInfo->id,
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005658 windowInfo->displayId,
5659 windowInfo->inputConfig.string().c_str(),
Chavi Weingarten7f019192023-08-08 20:39:01 +00005660 windowInfo->alpha, windowInfo->frame.left,
5661 windowInfo->frame.top, windowInfo->frame.right,
5662 windowInfo->frame.bottom, windowInfo->globalScaleFactor,
Bernardo Rufino49d99e42021-01-18 15:16:59 +00005663 windowInfo->applicationInfo.name.c_str(),
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07005664 binderToString(windowInfo->applicationInfo.token).c_str());
Bernardo Rufino53fc31e2020-11-03 11:01:07 +00005665 dump += dumpRegion(windowInfo->touchableRegion);
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005666 dump += StringPrintf(", ownerPid=%s, ownerUid=%s, dispatchingTimeout=%" PRId64
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005667 "ms, hasToken=%s, "
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005668 "touchOcclusionMode=%s\n",
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005669 windowInfo->ownerPid.toString().c_str(),
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00005670 windowInfo->ownerUid.toString().c_str(),
Bernardo Rufinoc2f1fad2020-11-04 17:30:57 +00005671 millis(windowInfo->dispatchingTimeout),
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07005672 binderToString(windowInfo->token).c_str(),
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005673 toString(windowInfo->touchOcclusionMode).c_str());
chaviw85b44202020-07-24 11:46:21 -07005674 windowInfo->transform.dump(dump, "transform", INDENT4);
Arthur Hungb92218b2018-08-14 12:00:21 +08005675 }
5676 } else {
5677 dump += INDENT2 "Windows: <none>\n";
5678 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005679 }
5680 } else {
Arthur Hungb92218b2018-08-14 12:00:21 +08005681 dump += INDENT "Displays: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005682 }
5683
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005684 if (!mGlobalMonitorsByDisplay.empty()) {
5685 for (const auto& [displayId, monitors] : mGlobalMonitorsByDisplay) {
5686 dump += StringPrintf(INDENT "Global monitors on display %d:\n", displayId);
Michael Wright3dd60e22019-03-27 22:06:44 +00005687 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005688 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005689 } else {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005690 dump += INDENT "Global Monitors: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005691 }
5692
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005693 const nsecs_t currentTime = now();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005694
5695 // Dump recently dispatched or dropped events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005696 if (!mRecentQueue.empty()) {
5697 dump += StringPrintf(INDENT "RecentQueue: length=%zu\n", mRecentQueue.size());
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005698 for (const std::shared_ptr<EventEntry>& entry : mRecentQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005699 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005700 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005701 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005702 }
5703 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005704 dump += INDENT "RecentQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005705 }
5706
5707 // Dump event currently being dispatched.
5708 if (mPendingEvent) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005709 dump += INDENT "PendingEvent:\n";
5710 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005711 dump += mPendingEvent->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005712 dump += StringPrintf(", age=%" PRId64 "ms\n",
5713 ns2ms(currentTime - mPendingEvent->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005714 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005715 dump += INDENT "PendingEvent: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005716 }
5717
5718 // Dump inbound events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005719 if (!mInboundQueue.empty()) {
5720 dump += StringPrintf(INDENT "InboundQueue: length=%zu\n", mInboundQueue.size());
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005721 for (const std::shared_ptr<EventEntry>& entry : mInboundQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005722 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005723 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005724 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005725 }
5726 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005727 dump += INDENT "InboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005728 }
5729
Prabir Pradhancef936d2021-07-21 16:17:52 +00005730 if (!mCommandQueue.empty()) {
5731 dump += StringPrintf(INDENT "CommandQueue: size=%zu\n", mCommandQueue.size());
5732 } else {
5733 dump += INDENT "CommandQueue: <empty>\n";
5734 }
5735
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005736 if (!mConnectionsByToken.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005737 dump += INDENT "Connections:\n";
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005738 for (const auto& [token, connection] : mConnectionsByToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005739 dump += StringPrintf(INDENT2 "%i: channelName='%s', windowName='%s', "
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005740 "status=%s, monitor=%s, responsive=%s\n",
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005741 connection->inputChannel->getFd().get(),
5742 connection->getInputChannelName().c_str(),
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08005743 connection->getWindowName().c_str(),
5744 ftl::enum_string(connection->status).c_str(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005745 toString(connection->monitor), toString(connection->responsive));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005746
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005747 if (!connection->outboundQueue.empty()) {
5748 dump += StringPrintf(INDENT3 "OutboundQueue: length=%zu\n",
5749 connection->outboundQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005750 dump += dumpQueue(connection->outboundQueue, currentTime);
5751
Michael Wrightd02c5b62014-02-10 15:10:22 -08005752 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005753 dump += INDENT3 "OutboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005754 }
5755
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005756 if (!connection->waitQueue.empty()) {
5757 dump += StringPrintf(INDENT3 "WaitQueue: length=%zu\n",
5758 connection->waitQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005759 dump += dumpQueue(connection->waitQueue, currentTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005760 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005761 dump += INDENT3 "WaitQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005762 }
Siarhei Vishniakoud38a1e02023-07-18 11:55:17 -07005763 std::stringstream inputStateDump;
5764 inputStateDump << connection->inputState;
5765 if (!isEmpty(inputStateDump)) {
5766 dump += INDENT3 "InputState: ";
5767 dump += inputStateDump.str() + "\n";
5768 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005769 }
5770 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005771 dump += INDENT "Connections: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005772 }
5773
5774 if (isAppSwitchPendingLocked()) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005775 dump += StringPrintf(INDENT "AppSwitch: pending, due in %" PRId64 "ms\n",
5776 ns2ms(mAppSwitchDueTime - now()));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005777 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005778 dump += INDENT "AppSwitch: not pending\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005779 }
5780
Antonio Kantek15beb512022-06-13 22:35:41 +00005781 if (!mTouchModePerDisplay.empty()) {
5782 dump += INDENT "TouchModePerDisplay:\n";
5783 for (const auto& [displayId, touchMode] : mTouchModePerDisplay) {
5784 dump += StringPrintf(INDENT2 "Display: %" PRId32 " TouchMode: %s\n", displayId,
5785 std::to_string(touchMode).c_str());
5786 }
5787 } else {
5788 dump += INDENT "TouchModePerDisplay: <none>\n";
5789 }
5790
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005791 dump += INDENT "Configuration:\n";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005792 dump += StringPrintf(INDENT2 "KeyRepeatDelay: %" PRId64 "ms\n", ns2ms(mConfig.keyRepeatDelay));
5793 dump += StringPrintf(INDENT2 "KeyRepeatTimeout: %" PRId64 "ms\n",
5794 ns2ms(mConfig.keyRepeatTimeout));
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00005795 dump += mLatencyTracker.dump(INDENT2);
Siarhei Vishniakoua04181f2021-03-26 05:56:49 +00005796 dump += mLatencyAggregator.dump(INDENT2);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005797}
5798
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005799void InputDispatcher::dumpMonitors(std::string& dump, const std::vector<Monitor>& monitors) const {
Michael Wright3dd60e22019-03-27 22:06:44 +00005800 const size_t numMonitors = monitors.size();
5801 for (size_t i = 0; i < numMonitors; i++) {
5802 const Monitor& monitor = monitors[i];
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005803 const std::shared_ptr<InputChannel>& channel = monitor.inputChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005804 dump += StringPrintf(INDENT2 "%zu: '%s', ", i, channel->getName().c_str());
5805 dump += "\n";
5806 }
5807}
5808
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005809class LooperEventCallback : public LooperCallback {
5810public:
5811 LooperEventCallback(std::function<int(int events)> callback) : mCallback(callback) {}
5812 int handleEvent(int /*fd*/, int events, void* /*data*/) override { return mCallback(events); }
5813
5814private:
5815 std::function<int(int events)> mCallback;
5816};
5817
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005818Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputChannel(const std::string& name) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00005819 if (DEBUG_CHANNEL_CREATION) {
5820 ALOGD("channel '%s' ~ createInputChannel", name.c_str());
5821 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005822
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005823 std::unique_ptr<InputChannel> serverChannel;
Garfield Tan15601662020-09-22 15:32:38 -07005824 std::unique_ptr<InputChannel> clientChannel;
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005825 status_t result = InputChannel::openInputChannelPair(name, serverChannel, clientChannel);
Garfield Tan15601662020-09-22 15:32:38 -07005826
5827 if (result) {
5828 return base::Error(result) << "Failed to open input channel pair with name " << name;
5829 }
5830
Michael Wrightd02c5b62014-02-10 15:10:22 -08005831 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005832 std::scoped_lock _l(mLock);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005833 const sp<IBinder>& token = serverChannel->getConnectionToken();
Garfield Tan15601662020-09-22 15:32:38 -07005834 int fd = serverChannel->getFd();
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07005835 std::shared_ptr<Connection> connection =
5836 std::make_shared<Connection>(std::move(serverChannel), /*monitor=*/false,
5837 mIdGenerator);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005838
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005839 if (mConnectionsByToken.find(token) != mConnectionsByToken.end()) {
5840 ALOGE("Created a new connection, but the token %p is already known", token.get());
5841 }
5842 mConnectionsByToken.emplace(token, connection);
5843
5844 std::function<int(int events)> callback = std::bind(&InputDispatcher::handleReceiveCallback,
5845 this, std::placeholders::_1, token);
5846
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005847 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, sp<LooperEventCallback>::make(callback),
5848 nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005849 } // release lock
5850
5851 // Wake the looper because some connections have changed.
5852 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07005853 return clientChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005854}
5855
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005856Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputMonitor(int32_t displayId,
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005857 const std::string& name,
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005858 gui::Pid pid) {
Garfield Tan15601662020-09-22 15:32:38 -07005859 std::shared_ptr<InputChannel> serverChannel;
5860 std::unique_ptr<InputChannel> clientChannel;
5861 status_t result = openInputChannelPair(name, serverChannel, clientChannel);
5862 if (result) {
5863 return base::Error(result) << "Failed to open input channel pair with name " << name;
5864 }
5865
Michael Wright3dd60e22019-03-27 22:06:44 +00005866 { // acquire lock
5867 std::scoped_lock _l(mLock);
5868
5869 if (displayId < 0) {
Garfield Tan15601662020-09-22 15:32:38 -07005870 return base::Error(BAD_VALUE) << "Attempted to create input monitor with name " << name
5871 << " without a specified display.";
Michael Wright3dd60e22019-03-27 22:06:44 +00005872 }
5873
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07005874 std::shared_ptr<Connection> connection =
5875 std::make_shared<Connection>(serverChannel, /*monitor=*/true, mIdGenerator);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005876 const sp<IBinder>& token = serverChannel->getConnectionToken();
Garfield Tan15601662020-09-22 15:32:38 -07005877 const int fd = serverChannel->getFd();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005878
5879 if (mConnectionsByToken.find(token) != mConnectionsByToken.end()) {
5880 ALOGE("Created a new connection, but the token %p is already known", token.get());
5881 }
5882 mConnectionsByToken.emplace(token, connection);
5883 std::function<int(int events)> callback = std::bind(&InputDispatcher::handleReceiveCallback,
5884 this, std::placeholders::_1, token);
Michael Wright3dd60e22019-03-27 22:06:44 +00005885
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005886 mGlobalMonitorsByDisplay[displayId].emplace_back(serverChannel, pid);
Michael Wright3dd60e22019-03-27 22:06:44 +00005887
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005888 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, sp<LooperEventCallback>::make(callback),
5889 nullptr);
Michael Wright3dd60e22019-03-27 22:06:44 +00005890 }
Garfield Tan15601662020-09-22 15:32:38 -07005891
Michael Wright3dd60e22019-03-27 22:06:44 +00005892 // Wake the looper because some connections have changed.
5893 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07005894 return clientChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005895}
5896
Garfield Tan15601662020-09-22 15:32:38 -07005897status_t InputDispatcher::removeInputChannel(const sp<IBinder>& connectionToken) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005898 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005899 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005900
Harry Cutts33476232023-01-30 19:57:29 +00005901 status_t status = removeInputChannelLocked(connectionToken, /*notify=*/false);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005902 if (status) {
5903 return status;
5904 }
5905 } // release lock
5906
5907 // Wake the poll loop because removing the connection may have changed the current
5908 // synchronization state.
5909 mLooper->wake();
5910 return OK;
5911}
5912
Garfield Tan15601662020-09-22 15:32:38 -07005913status_t InputDispatcher::removeInputChannelLocked(const sp<IBinder>& connectionToken,
5914 bool notify) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07005915 std::shared_ptr<Connection> connection = getConnectionLocked(connectionToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005916 if (connection == nullptr) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005917 // Connection can be removed via socket hang up or an explicit call to 'removeInputChannel'
Michael Wrightd02c5b62014-02-10 15:10:22 -08005918 return BAD_VALUE;
5919 }
5920
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005921 removeConnectionLocked(connection);
Robert Carr5c8a0262018-10-03 16:30:44 -07005922
Michael Wrightd02c5b62014-02-10 15:10:22 -08005923 if (connection->monitor) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005924 removeMonitorChannelLocked(connectionToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005925 }
5926
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005927 mLooper->removeFd(connection->inputChannel->getFd());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005928
5929 nsecs_t currentTime = now();
5930 abortBrokenDispatchCycleLocked(currentTime, connection, notify);
5931
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08005932 connection->status = Connection::Status::ZOMBIE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005933 return OK;
5934}
5935
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005936void InputDispatcher::removeMonitorChannelLocked(const sp<IBinder>& connectionToken) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005937 for (auto it = mGlobalMonitorsByDisplay.begin(); it != mGlobalMonitorsByDisplay.end();) {
5938 auto& [displayId, monitors] = *it;
5939 std::erase_if(monitors, [connectionToken](const Monitor& monitor) {
5940 return monitor.inputChannel->getConnectionToken() == connectionToken;
5941 });
Michael Wright3dd60e22019-03-27 22:06:44 +00005942
Michael Wright3dd60e22019-03-27 22:06:44 +00005943 if (monitors.empty()) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005944 it = mGlobalMonitorsByDisplay.erase(it);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005945 } else {
5946 ++it;
5947 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005948 }
5949}
5950
Michael Wright3dd60e22019-03-27 22:06:44 +00005951status_t InputDispatcher::pilferPointers(const sp<IBinder>& token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005952 std::scoped_lock _l(mLock);
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00005953 return pilferPointersLocked(token);
5954}
Michael Wright3dd60e22019-03-27 22:06:44 +00005955
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00005956status_t InputDispatcher::pilferPointersLocked(const sp<IBinder>& token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005957 const std::shared_ptr<InputChannel> requestingChannel = getInputChannelLocked(token);
5958 if (!requestingChannel) {
Siarhei Vishniakou8384e0d2023-09-18 18:48:27 -07005959 LOG(WARNING)
5960 << "Attempted to pilfer pointers from an un-registered channel or invalid token";
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005961 return BAD_VALUE;
Michael Wright3dd60e22019-03-27 22:06:44 +00005962 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005963
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005964 auto [statePtr, windowPtr, displayId] = findTouchStateWindowAndDisplayLocked(token);
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005965 if (statePtr == nullptr || windowPtr == nullptr) {
Siarhei Vishniakou8384e0d2023-09-18 18:48:27 -07005966 LOG(WARNING)
5967 << "Attempted to pilfer points from a channel without any on-going pointer streams."
5968 " Ignoring.";
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005969 return BAD_VALUE;
5970 }
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005971 std::set<int32_t> deviceIds = windowPtr->getTouchingDeviceIds();
5972 if (deviceIds.size() != 1) {
5973 LOG(WARNING) << "Can't pilfer. Currently touching devices: " << dumpSet(deviceIds)
5974 << " in window: " << windowPtr->dump();
5975 return BAD_VALUE;
5976 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005977
Siarhei Vishniakou8384e0d2023-09-18 18:48:27 -07005978 for (const DeviceId deviceId : deviceIds) {
5979 TouchState& state = *statePtr;
5980 TouchedWindow& window = *windowPtr;
5981 // Send cancel events to all the input channels we're stealing from.
5982 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
5983 "input channel stole pointer stream");
5984 options.deviceId = deviceId;
5985 options.displayId = displayId;
5986 std::bitset<MAX_POINTER_ID + 1> pointerIds = window.getTouchingPointers(deviceId);
5987 options.pointerIds = pointerIds;
5988 std::string canceledWindows;
5989 for (const TouchedWindow& w : state.windows) {
5990 const std::shared_ptr<InputChannel> channel =
5991 getInputChannelLocked(w.windowHandle->getToken());
5992 if (channel != nullptr && channel->getConnectionToken() != token) {
5993 synthesizeCancelationEventsForInputChannelLocked(channel, options);
5994 canceledWindows += canceledWindows.empty() ? "[" : ", ";
5995 canceledWindows += channel->getName();
5996 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005997 }
Siarhei Vishniakou8384e0d2023-09-18 18:48:27 -07005998 canceledWindows += canceledWindows.empty() ? "[]" : "]";
5999 LOG(INFO) << "Channel " << requestingChannel->getName()
6000 << " is stealing input gesture for device " << deviceId << " from "
6001 << canceledWindows;
6002
6003 // Prevent the gesture from being sent to any other windows.
6004 // This only blocks relevant pointers to be sent to other windows
6005 window.addPilferingPointers(deviceId, pointerIds);
6006
6007 state.cancelPointersForWindowsExcept(deviceId, pointerIds, token);
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006008 }
Michael Wright3dd60e22019-03-27 22:06:44 +00006009 return OK;
6010}
6011
Prabir Pradhan99987712020-11-10 18:43:05 -08006012void InputDispatcher::requestPointerCapture(const sp<IBinder>& windowToken, bool enabled) {
6013 { // acquire lock
6014 std::scoped_lock _l(mLock);
6015 if (DEBUG_FOCUS) {
chaviw98318de2021-05-19 16:45:23 -05006016 const sp<WindowInfoHandle> windowHandle = getWindowHandleLocked(windowToken);
Prabir Pradhan99987712020-11-10 18:43:05 -08006017 ALOGI("Request to %s Pointer Capture from: %s.", enabled ? "enable" : "disable",
6018 windowHandle != nullptr ? windowHandle->getName().c_str()
6019 : "token without window");
6020 }
6021
Vishnu Nairc519ff72021-01-21 08:23:08 -08006022 const sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Prabir Pradhan99987712020-11-10 18:43:05 -08006023 if (focusedToken != windowToken) {
6024 ALOGW("Ignoring request to %s Pointer Capture: window does not have focus.",
6025 enabled ? "enable" : "disable");
6026 return;
6027 }
6028
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006029 if (enabled == mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006030 ALOGW("Ignoring request to %s Pointer Capture: "
6031 "window has %s requested pointer capture.",
6032 enabled ? "enable" : "disable", enabled ? "already" : "not");
6033 return;
6034 }
6035
Christine Franksb768bb42021-11-29 12:11:31 -08006036 if (enabled) {
6037 if (std::find(mIneligibleDisplaysForPointerCapture.begin(),
6038 mIneligibleDisplaysForPointerCapture.end(),
6039 mFocusedDisplayId) != mIneligibleDisplaysForPointerCapture.end()) {
6040 ALOGW("Ignoring request to enable Pointer Capture: display is not eligible");
6041 return;
6042 }
6043 }
6044
Prabir Pradhan99987712020-11-10 18:43:05 -08006045 setPointerCaptureLocked(enabled);
6046 } // release lock
6047
6048 // Wake the thread to process command entries.
6049 mLooper->wake();
6050}
6051
Christine Franksb768bb42021-11-29 12:11:31 -08006052void InputDispatcher::setDisplayEligibilityForPointerCapture(int32_t displayId, bool isEligible) {
6053 { // acquire lock
6054 std::scoped_lock _l(mLock);
6055 std::erase(mIneligibleDisplaysForPointerCapture, displayId);
6056 if (!isEligible) {
6057 mIneligibleDisplaysForPointerCapture.push_back(displayId);
6058 }
6059 } // release lock
6060}
6061
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00006062std::optional<gui::Pid> InputDispatcher::findMonitorPidByTokenLocked(const sp<IBinder>& token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006063 for (const auto& [_, monitors] : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00006064 for (const Monitor& monitor : monitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07006065 if (monitor.inputChannel->getConnectionToken() == token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006066 return monitor.pid;
Michael Wright3dd60e22019-03-27 22:06:44 +00006067 }
6068 }
6069 }
6070 return std::nullopt;
6071}
6072
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006073std::shared_ptr<Connection> InputDispatcher::getConnectionLocked(
6074 const sp<IBinder>& inputConnectionToken) const {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07006075 if (inputConnectionToken == nullptr) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07006076 return nullptr;
Arthur Hung3b413f22018-10-26 18:05:34 +08006077 }
6078
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00006079 for (const auto& [token, connection] : mConnectionsByToken) {
6080 if (token == inputConnectionToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07006081 return connection;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006082 }
6083 }
Robert Carr4e670e52018-08-15 13:26:12 -07006084
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07006085 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006086}
6087
Siarhei Vishniakouad991402020-10-28 11:40:09 -05006088std::string InputDispatcher::getConnectionNameLocked(const sp<IBinder>& connectionToken) const {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006089 std::shared_ptr<Connection> connection = getConnectionLocked(connectionToken);
Siarhei Vishniakouad991402020-10-28 11:40:09 -05006090 if (connection == nullptr) {
6091 return "<nullptr>";
6092 }
6093 return connection->getInputChannelName();
6094}
6095
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006096void InputDispatcher::removeConnectionLocked(const std::shared_ptr<Connection>& connection) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006097 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00006098 mConnectionsByToken.erase(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07006099}
6100
Prabir Pradhancef936d2021-07-21 16:17:52 +00006101void InputDispatcher::doDispatchCycleFinishedCommand(nsecs_t finishTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006102 const std::shared_ptr<Connection>& connection,
6103 uint32_t seq, bool handled,
6104 nsecs_t consumeTime) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006105 // Handle post-event policy actions.
Prabir Pradhancef936d2021-07-21 16:17:52 +00006106 bool restartEvent;
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006107
6108 { // Start critical section
6109 auto dispatchEntryIt =
6110 std::find_if(connection->waitQueue.begin(), connection->waitQueue.end(),
6111 [seq](auto& e) { return e->seq == seq; });
6112 if (dispatchEntryIt == connection->waitQueue.end()) {
6113 return;
6114 }
6115
6116 DispatchEntry& dispatchEntry = **dispatchEntryIt;
6117
6118 const nsecs_t eventDuration = finishTime - dispatchEntry.deliveryTime;
6119 if (eventDuration > SLOW_EVENT_PROCESSING_WARNING_TIMEOUT) {
6120 ALOGI("%s spent %" PRId64 "ms processing %s", connection->getWindowName().c_str(),
6121 ns2ms(eventDuration), dispatchEntry.eventEntry->getDescription().c_str());
6122 }
6123 if (shouldReportFinishedEvent(dispatchEntry, *connection)) {
6124 mLatencyTracker.trackFinishedEvent(dispatchEntry.eventEntry->id,
6125 connection->inputChannel->getConnectionToken(),
6126 dispatchEntry.deliveryTime, consumeTime, finishTime);
6127 }
6128
6129 if (dispatchEntry.eventEntry->type == EventEntry::Type::KEY) {
6130 KeyEntry& keyEntry = static_cast<KeyEntry&>(*(dispatchEntry.eventEntry));
6131 restartEvent =
6132 afterKeyEventLockedInterruptable(connection, dispatchEntry, keyEntry, handled);
6133 } else if (dispatchEntry.eventEntry->type == EventEntry::Type::MOTION) {
6134 MotionEntry& motionEntry = static_cast<MotionEntry&>(*(dispatchEntry.eventEntry));
6135 restartEvent = afterMotionEventLockedInterruptable(connection, dispatchEntry,
6136 motionEntry, handled);
6137 } else {
6138 restartEvent = false;
6139 }
6140 } // End critical section: The -LockedInterruptable methods may have released the lock.
Prabir Pradhancef936d2021-07-21 16:17:52 +00006141
6142 // Dequeue the event and start the next cycle.
6143 // Because the lock might have been released, it is possible that the
6144 // contents of the wait queue to have been drained, so we need to double-check
6145 // a few things.
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006146 auto entryIt = std::find_if(connection->waitQueue.begin(), connection->waitQueue.end(),
6147 [seq](auto& e) { return e->seq == seq; });
6148 if (entryIt != connection->waitQueue.end()) {
6149 std::unique_ptr<DispatchEntry> dispatchEntry = std::move(*entryIt);
6150 connection->waitQueue.erase(entryIt);
6151
Prabir Pradhancef936d2021-07-21 16:17:52 +00006152 const sp<IBinder>& connectionToken = connection->inputChannel->getConnectionToken();
6153 mAnrTracker.erase(dispatchEntry->timeoutTime, connectionToken);
6154 if (!connection->responsive) {
6155 connection->responsive = isConnectionResponsive(*connection);
6156 if (connection->responsive) {
6157 // The connection was unresponsive, and now it's responsive.
6158 processConnectionResponsiveLocked(*connection);
6159 }
6160 }
6161 traceWaitQueueLength(*connection);
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08006162 if (restartEvent && connection->status == Connection::Status::NORMAL) {
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006163 connection->outboundQueue.emplace_front(std::move(dispatchEntry));
Prabir Pradhancef936d2021-07-21 16:17:52 +00006164 traceOutboundQueueLength(*connection);
6165 } else {
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006166 releaseDispatchEntry(std::move(dispatchEntry));
Prabir Pradhancef936d2021-07-21 16:17:52 +00006167 }
6168 }
6169
6170 // Start the next dispatch cycle for this connection.
6171 startDispatchCycleLocked(now(), connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006172}
6173
Prabir Pradhancef936d2021-07-21 16:17:52 +00006174void InputDispatcher::sendFocusChangedCommandLocked(const sp<IBinder>& oldToken,
6175 const sp<IBinder>& newToken) {
6176 auto command = [this, oldToken, newToken]() REQUIRES(mLock) {
6177 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00006178 mPolicy.notifyFocusChanged(oldToken, newToken);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006179 };
6180 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08006181}
6182
Prabir Pradhancef936d2021-07-21 16:17:52 +00006183void InputDispatcher::sendDropWindowCommandLocked(const sp<IBinder>& token, float x, float y) {
6184 auto command = [this, token, x, y]() REQUIRES(mLock) {
6185 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00006186 mPolicy.notifyDropWindow(token, x, y);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006187 };
6188 postCommandLocked(std::move(command));
Robert Carrf759f162018-11-13 12:57:11 -08006189}
6190
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006191void InputDispatcher::onAnrLocked(const std::shared_ptr<Connection>& connection) {
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006192 if (connection == nullptr) {
6193 LOG_ALWAYS_FATAL("Caller must check for nullness");
6194 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006195 // Since we are allowing the policy to extend the timeout, maybe the waitQueue
6196 // is already healthy again. Don't raise ANR in this situation
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006197 if (connection->waitQueue.empty()) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006198 ALOGI("Not raising ANR because the connection %s has recovered",
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006199 connection->inputChannel->getName().c_str());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006200 return;
6201 }
6202 /**
6203 * The "oldestEntry" is the entry that was first sent to the application. That entry, however,
6204 * may not be the one that caused the timeout to occur. One possibility is that window timeout
6205 * has changed. This could cause newer entries to time out before the already dispatched
6206 * entries. In that situation, the newest entries caused ANR. But in all likelihood, the app
6207 * processes the events linearly. So providing information about the oldest entry seems to be
6208 * most useful.
6209 */
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006210 DispatchEntry& oldestEntry = *connection->waitQueue.front();
6211 const nsecs_t currentWait = now() - oldestEntry.deliveryTime;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006212 std::string reason =
6213 android::base::StringPrintf("%s is not responding. Waited %" PRId64 "ms for %s",
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006214 connection->inputChannel->getName().c_str(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006215 ns2ms(currentWait),
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006216 oldestEntry.eventEntry->getDescription().c_str());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006217 sp<IBinder> connectionToken = connection->inputChannel->getConnectionToken();
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -06006218 updateLastAnrStateLocked(getWindowHandleLocked(connectionToken), reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006219
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006220 processConnectionUnresponsiveLocked(*connection, std::move(reason));
6221
6222 // Stop waking up for events on this connection, it is already unresponsive
6223 cancelEventsForAnrLocked(connection);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006224}
6225
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05006226void InputDispatcher::onAnrLocked(std::shared_ptr<InputApplicationHandle> application) {
6227 std::string reason =
6228 StringPrintf("%s does not have a focused window", application->getName().c_str());
6229 updateLastAnrStateLocked(*application, reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006230
Yabin Cui8eb9c552023-06-08 18:05:07 +00006231 auto command = [this, app = std::move(application)]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006232 scoped_unlock unlock(mLock);
Yabin Cuiced952f2023-06-09 21:12:51 +00006233 mPolicy.notifyNoFocusedWindowAnr(app);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006234 };
6235 postCommandLocked(std::move(command));
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00006236}
6237
chaviw98318de2021-05-19 16:45:23 -05006238void InputDispatcher::updateLastAnrStateLocked(const sp<WindowInfoHandle>& window,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006239 const std::string& reason) {
6240 const std::string windowLabel = getApplicationWindowLabel(nullptr, window);
6241 updateLastAnrStateLocked(windowLabel, reason);
6242}
6243
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05006244void InputDispatcher::updateLastAnrStateLocked(const InputApplicationHandle& application,
6245 const std::string& reason) {
6246 const std::string windowLabel = getApplicationWindowLabel(&application, nullptr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006247 updateLastAnrStateLocked(windowLabel, reason);
6248}
6249
6250void InputDispatcher::updateLastAnrStateLocked(const std::string& windowLabel,
6251 const std::string& reason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006252 // Capture a record of the InputDispatcher state at the time of the ANR.
Yi Kong9b14ac62018-07-17 13:48:38 -07006253 time_t t = time(nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006254 struct tm tm;
6255 localtime_r(&t, &tm);
6256 char timestr[64];
6257 strftime(timestr, sizeof(timestr), "%F %T", &tm);
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006258 mLastAnrState.clear();
6259 mLastAnrState += INDENT "ANR:\n";
6260 mLastAnrState += StringPrintf(INDENT2 "Time: %s\n", timestr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006261 mLastAnrState += StringPrintf(INDENT2 "Reason: %s\n", reason.c_str());
6262 mLastAnrState += StringPrintf(INDENT2 "Window: %s\n", windowLabel.c_str());
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006263 dumpDispatchStateLocked(mLastAnrState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006264}
6265
Prabir Pradhancef936d2021-07-21 16:17:52 +00006266void InputDispatcher::doInterceptKeyBeforeDispatchingCommand(const sp<IBinder>& focusedWindowToken,
6267 KeyEntry& entry) {
6268 const KeyEvent event = createKeyEvent(entry);
6269 nsecs_t delay = 0;
6270 { // release lock
6271 scoped_unlock unlock(mLock);
6272 android::base::Timer t;
Prabir Pradhana41d2442023-04-20 21:30:40 +00006273 delay = mPolicy.interceptKeyBeforeDispatching(focusedWindowToken, event, entry.policyFlags);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006274 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
6275 ALOGW("Excessive delay in interceptKeyBeforeDispatching; took %s ms",
6276 std::to_string(t.duration().count()).c_str());
6277 }
6278 } // acquire lock
Michael Wrightd02c5b62014-02-10 15:10:22 -08006279
6280 if (delay < 0) {
Michael Wright5caf55a2022-11-24 22:31:42 +00006281 entry.interceptKeyResult = KeyEntry::InterceptKeyResult::SKIP;
Prabir Pradhancef936d2021-07-21 16:17:52 +00006282 } else if (delay == 0) {
Michael Wright5caf55a2022-11-24 22:31:42 +00006283 entry.interceptKeyResult = KeyEntry::InterceptKeyResult::CONTINUE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006284 } else {
Michael Wright5caf55a2022-11-24 22:31:42 +00006285 entry.interceptKeyResult = KeyEntry::InterceptKeyResult::TRY_AGAIN_LATER;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006286 entry.interceptKeyWakeupTime = now() + delay;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006287 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006288}
6289
Prabir Pradhancef936d2021-07-21 16:17:52 +00006290void InputDispatcher::sendWindowUnresponsiveCommandLocked(const sp<IBinder>& token,
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00006291 std::optional<gui::Pid> pid,
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006292 std::string reason) {
Yabin Cui8eb9c552023-06-08 18:05:07 +00006293 auto command = [this, token, pid, r = std::move(reason)]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006294 scoped_unlock unlock(mLock);
Yabin Cuiced952f2023-06-09 21:12:51 +00006295 mPolicy.notifyWindowUnresponsive(token, pid, r);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006296 };
6297 postCommandLocked(std::move(command));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006298}
6299
Prabir Pradhanedd96402022-02-15 01:46:16 -08006300void InputDispatcher::sendWindowResponsiveCommandLocked(const sp<IBinder>& token,
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00006301 std::optional<gui::Pid> pid) {
Prabir Pradhanedd96402022-02-15 01:46:16 -08006302 auto command = [this, token, pid]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006303 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00006304 mPolicy.notifyWindowResponsive(token, pid);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006305 };
6306 postCommandLocked(std::move(command));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006307}
6308
6309/**
6310 * Tell the policy that a connection has become unresponsive so that it can start ANR.
6311 * Check whether the connection of interest is a monitor or a window, and add the corresponding
6312 * command entry to the command queue.
6313 */
6314void InputDispatcher::processConnectionUnresponsiveLocked(const Connection& connection,
6315 std::string reason) {
6316 const sp<IBinder>& connectionToken = connection.inputChannel->getConnectionToken();
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00006317 std::optional<gui::Pid> pid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006318 if (connection.monitor) {
6319 ALOGW("Monitor %s is unresponsive: %s", connection.inputChannel->getName().c_str(),
6320 reason.c_str());
Prabir Pradhanedd96402022-02-15 01:46:16 -08006321 pid = findMonitorPidByTokenLocked(connectionToken);
6322 } else {
6323 // The connection is a window
6324 ALOGW("Window %s is unresponsive: %s", connection.inputChannel->getName().c_str(),
6325 reason.c_str());
6326 const sp<WindowInfoHandle> handle = getWindowHandleLocked(connectionToken);
6327 if (handle != nullptr) {
6328 pid = handle->getInfo()->ownerPid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006329 }
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006330 }
Prabir Pradhanedd96402022-02-15 01:46:16 -08006331 sendWindowUnresponsiveCommandLocked(connectionToken, pid, std::move(reason));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006332}
6333
6334/**
6335 * Tell the policy that a connection has become responsive so that it can stop ANR.
6336 */
6337void InputDispatcher::processConnectionResponsiveLocked(const Connection& connection) {
6338 const sp<IBinder>& connectionToken = connection.inputChannel->getConnectionToken();
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00006339 std::optional<gui::Pid> pid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006340 if (connection.monitor) {
Prabir Pradhanedd96402022-02-15 01:46:16 -08006341 pid = findMonitorPidByTokenLocked(connectionToken);
6342 } else {
6343 // The connection is a window
6344 const sp<WindowInfoHandle> handle = getWindowHandleLocked(connectionToken);
6345 if (handle != nullptr) {
6346 pid = handle->getInfo()->ownerPid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006347 }
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006348 }
Prabir Pradhanedd96402022-02-15 01:46:16 -08006349 sendWindowResponsiveCommandLocked(connectionToken, pid);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006350}
6351
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006352bool InputDispatcher::afterKeyEventLockedInterruptable(
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006353 const std::shared_ptr<Connection>& connection, DispatchEntry& dispatchEntry,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006354 KeyEntry& keyEntry, bool handled) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006355 if (keyEntry.flags & AKEY_EVENT_FLAG_FALLBACK) {
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006356 if (!handled) {
6357 // Report the key as unhandled, since the fallback was not handled.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006358 mReporter->reportUnhandledKey(keyEntry.id);
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006359 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006360 return false;
6361 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006362
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006363 // Get the fallback key state.
6364 // Clear it out after dispatching the UP.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006365 int32_t originalKeyCode = keyEntry.keyCode;
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006366 std::optional<int32_t> fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006367 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006368 connection->inputState.removeFallbackKey(originalKeyCode);
6369 }
6370
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006371 if (handled || !dispatchEntry.hasForegroundTarget()) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006372 // If the application handles the original key for which we previously
6373 // generated a fallback or if the window is not a foreground window,
6374 // then cancel the associated fallback key, if any.
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006375 if (fallbackKeyCode) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006376 // Dispatch the unhandled key to the policy with the cancel flag.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006377 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6378 ALOGD("Unhandled key event: Asking policy to cancel fallback action. "
6379 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6380 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount,
6381 keyEntry.policyFlags);
6382 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006383 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006384 event.setFlags(event.getFlags() | AKEY_EVENT_FLAG_CANCELED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006385
6386 mLock.unlock();
6387
Prabir Pradhana41d2442023-04-20 21:30:40 +00006388 if (const auto unhandledKeyFallback =
6389 mPolicy.dispatchUnhandledKey(connection->inputChannel->getConnectionToken(),
6390 event, keyEntry.policyFlags);
6391 unhandledKeyFallback) {
6392 event = *unhandledKeyFallback;
6393 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006394
6395 mLock.lock();
6396
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006397 // Cancel the fallback key.
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006398 if (*fallbackKeyCode != AKEYCODE_UNKNOWN) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00006399 CancelationOptions options(CancelationOptions::Mode::CANCEL_FALLBACK_EVENTS,
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006400 "application handled the original non-fallback key "
6401 "or is no longer a foreground target, "
6402 "canceling previously dispatched fallback key");
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006403 options.keyCode = *fallbackKeyCode;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006404 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006405 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006406 connection->inputState.removeFallbackKey(originalKeyCode);
6407 }
6408 } else {
6409 // If the application did not handle a non-fallback key, first check
6410 // that we are in a good state to perform unhandled key event processing
6411 // Then ask the policy what to do with it.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006412 bool initialDown = keyEntry.action == AKEY_EVENT_ACTION_DOWN && keyEntry.repeatCount == 0;
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006413 if (!fallbackKeyCode && !initialDown) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006414 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6415 ALOGD("Unhandled key event: Skipping unhandled key event processing "
6416 "since this is not an initial down. "
6417 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6418 originalKeyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
6419 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006420 return false;
6421 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006422
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006423 // Dispatch the unhandled key to the policy.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006424 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6425 ALOGD("Unhandled key event: Asking policy to perform fallback action. "
6426 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6427 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
6428 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006429 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006430
6431 mLock.unlock();
6432
Prabir Pradhana41d2442023-04-20 21:30:40 +00006433 bool fallback = false;
6434 if (auto fb = mPolicy.dispatchUnhandledKey(connection->inputChannel->getConnectionToken(),
6435 event, keyEntry.policyFlags);
6436 fb) {
6437 fallback = true;
6438 event = *fb;
6439 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006440
6441 mLock.lock();
6442
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08006443 if (connection->status != Connection::Status::NORMAL) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006444 connection->inputState.removeFallbackKey(originalKeyCode);
6445 return false;
6446 }
6447
6448 // Latch the fallback keycode for this key on an initial down.
6449 // The fallback keycode cannot change at any other point in the lifecycle.
6450 if (initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006451 if (fallback) {
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006452 *fallbackKeyCode = event.getKeyCode();
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006453 } else {
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006454 *fallbackKeyCode = AKEYCODE_UNKNOWN;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006455 }
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006456 connection->inputState.setFallbackKey(originalKeyCode, *fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006457 }
6458
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006459 ALOG_ASSERT(fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006460
6461 // Cancel the fallback key if the policy decides not to send it anymore.
6462 // We will continue to dispatch the key to the policy but we will no
6463 // longer dispatch a fallback key to the application.
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006464 if (*fallbackKeyCode != AKEYCODE_UNKNOWN &&
6465 (!fallback || *fallbackKeyCode != event.getKeyCode())) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006466 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6467 if (fallback) {
6468 ALOGD("Unhandled key event: Policy requested to send key %d"
6469 "as a fallback for %d, but on the DOWN it had requested "
6470 "to send %d instead. Fallback canceled.",
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006471 event.getKeyCode(), originalKeyCode, *fallbackKeyCode);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006472 } else {
6473 ALOGD("Unhandled key event: Policy did not request fallback for %d, "
6474 "but on the DOWN it had requested to send %d. "
6475 "Fallback canceled.",
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006476 originalKeyCode, *fallbackKeyCode);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006477 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006478 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006479
Michael Wrightfb04fd52022-11-24 22:31:11 +00006480 CancelationOptions options(CancelationOptions::Mode::CANCEL_FALLBACK_EVENTS,
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006481 "canceling fallback, policy no longer desires it");
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006482 options.keyCode = *fallbackKeyCode;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006483 synthesizeCancelationEventsForConnectionLocked(connection, options);
6484
6485 fallback = false;
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006486 *fallbackKeyCode = AKEYCODE_UNKNOWN;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006487 if (keyEntry.action != AKEY_EVENT_ACTION_UP) {
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006488 connection->inputState.setFallbackKey(originalKeyCode, *fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006489 }
6490 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006491
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006492 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6493 {
6494 std::string msg;
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006495 const std::map<int32_t, int32_t>& fallbackKeys =
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006496 connection->inputState.getFallbackKeys();
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006497 for (const auto& [key, value] : fallbackKeys) {
6498 msg += StringPrintf(", %d->%d", key, value);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006499 }
6500 ALOGD("Unhandled key event: %zu currently tracked fallback keys%s.",
6501 fallbackKeys.size(), msg.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006502 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006503 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006504
6505 if (fallback) {
6506 // Restart the dispatch cycle using the fallback key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006507 keyEntry.eventTime = event.getEventTime();
6508 keyEntry.deviceId = event.getDeviceId();
6509 keyEntry.source = event.getSource();
6510 keyEntry.displayId = event.getDisplayId();
6511 keyEntry.flags = event.getFlags() | AKEY_EVENT_FLAG_FALLBACK;
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006512 keyEntry.keyCode = *fallbackKeyCode;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006513 keyEntry.scanCode = event.getScanCode();
6514 keyEntry.metaState = event.getMetaState();
6515 keyEntry.repeatCount = event.getRepeatCount();
6516 keyEntry.downTime = event.getDownTime();
6517 keyEntry.syntheticRepeat = false;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006518
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006519 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6520 ALOGD("Unhandled key event: Dispatching fallback key. "
6521 "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006522 originalKeyCode, *fallbackKeyCode, keyEntry.metaState);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006523 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006524 return true; // restart the event
6525 } else {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006526 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6527 ALOGD("Unhandled key event: No fallback key.");
6528 }
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006529
6530 // Report the key as unhandled, since there is no fallback key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006531 mReporter->reportUnhandledKey(keyEntry.id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006532 }
6533 }
6534 return false;
6535}
6536
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006537bool InputDispatcher::afterMotionEventLockedInterruptable(
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006538 const std::shared_ptr<Connection>& connection, DispatchEntry& dispatchEntry,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006539 MotionEntry& motionEntry, bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006540 return false;
6541}
6542
Michael Wrightd02c5b62014-02-10 15:10:22 -08006543void InputDispatcher::traceInboundQueueLengthLocked() {
6544 if (ATRACE_ENABLED()) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07006545 ATRACE_INT("iq", mInboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006546 }
6547}
6548
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006549void InputDispatcher::traceOutboundQueueLength(const Connection& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006550 if (ATRACE_ENABLED()) {
6551 char counterName[40];
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006552 snprintf(counterName, sizeof(counterName), "oq:%s", connection.getWindowName().c_str());
6553 ATRACE_INT(counterName, connection.outboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006554 }
6555}
6556
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006557void InputDispatcher::traceWaitQueueLength(const Connection& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006558 if (ATRACE_ENABLED()) {
6559 char counterName[40];
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006560 snprintf(counterName, sizeof(counterName), "wq:%s", connection.getWindowName().c_str());
6561 ATRACE_INT(counterName, connection.waitQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006562 }
6563}
6564
Siarhei Vishniakou5e20f272023-06-08 17:24:44 -07006565void InputDispatcher::dump(std::string& dump) const {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006566 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006567
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006568 dump += "Input Dispatcher State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08006569 dumpDispatchStateLocked(dump);
6570
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006571 if (!mLastAnrState.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006572 dump += "\nInput Dispatcher State at time of last ANR:\n";
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006573 dump += mLastAnrState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006574 }
6575}
6576
6577void InputDispatcher::monitor() {
6578 // Acquire and release the lock to ensure that the dispatcher has not deadlocked.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006579 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006580 mLooper->wake();
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006581 mDispatcherIsAlive.wait(_l);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006582}
6583
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08006584/**
6585 * Wake up the dispatcher and wait until it processes all events and commands.
6586 * The notification of mDispatcherEnteredIdle is guaranteed to happen after wake(), so
6587 * this method can be safely called from any thread, as long as you've ensured that
6588 * the work you are interested in completing has already been queued.
6589 */
Siarhei Vishniakoua66d65e2023-06-16 10:32:51 -07006590bool InputDispatcher::waitForIdle() const {
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08006591 /**
6592 * Timeout should represent the longest possible time that a device might spend processing
6593 * events and commands.
6594 */
6595 constexpr std::chrono::duration TIMEOUT = 100ms;
6596 std::unique_lock lock(mLock);
6597 mLooper->wake();
6598 std::cv_status result = mDispatcherEnteredIdle.wait_for(lock, TIMEOUT);
6599 return result == std::cv_status::no_timeout;
6600}
6601
Vishnu Naire798b472020-07-23 13:52:21 -07006602/**
6603 * Sets focus to the window identified by the token. This must be called
6604 * after updating any input window handles.
6605 *
6606 * Params:
6607 * request.token - input channel token used to identify the window that should gain focus.
6608 * request.focusedToken - the token that the caller expects currently to be focused. If the
6609 * specified token does not match the currently focused window, this request will be dropped.
6610 * If the specified focused token matches the currently focused window, the call will succeed.
6611 * Set this to "null" if this call should succeed no matter what the currently focused token is.
6612 * request.timestamp - SYSTEM_TIME_MONOTONIC timestamp in nanos set by the client (wm)
6613 * when requesting the focus change. This determines which request gets
6614 * precedence if there is a focus change request from another source such as pointer down.
6615 */
Vishnu Nair958da932020-08-21 17:12:37 -07006616void InputDispatcher::setFocusedWindow(const FocusRequest& request) {
6617 { // acquire lock
6618 std::scoped_lock _l(mLock);
Vishnu Nairc519ff72021-01-21 08:23:08 -08006619 std::optional<FocusResolver::FocusChanges> changes =
6620 mFocusResolver.setFocusedWindow(request, getWindowHandlesLocked(request.displayId));
6621 if (changes) {
6622 onFocusChangedLocked(*changes);
Vishnu Nair958da932020-08-21 17:12:37 -07006623 }
6624 } // release lock
6625 // Wake up poll loop since it may need to make new input dispatching choices.
6626 mLooper->wake();
6627}
6628
Vishnu Nairc519ff72021-01-21 08:23:08 -08006629void InputDispatcher::onFocusChangedLocked(const FocusResolver::FocusChanges& changes) {
6630 if (changes.oldFocus) {
6631 std::shared_ptr<InputChannel> focusedInputChannel = getInputChannelLocked(changes.oldFocus);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006632 if (focusedInputChannel) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00006633 CancelationOptions options(CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS,
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006634 "focus left window");
6635 synthesizeCancelationEventsForInputChannelLocked(focusedInputChannel, options);
Harry Cutts33476232023-01-30 19:57:29 +00006636 enqueueFocusEventLocked(changes.oldFocus, /*hasFocus=*/false, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006637 }
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006638 }
Vishnu Nairc519ff72021-01-21 08:23:08 -08006639 if (changes.newFocus) {
Siarhei Vishniakouc033dfb2023-10-03 10:45:16 -07006640 resetNoFocusedWindowTimeoutLocked();
Harry Cutts33476232023-01-30 19:57:29 +00006641 enqueueFocusEventLocked(changes.newFocus, /*hasFocus=*/true, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006642 }
6643
Prabir Pradhan99987712020-11-10 18:43:05 -08006644 // If a window has pointer capture, then it must have focus. We need to ensure that this
6645 // contract is upheld when pointer capture is being disabled due to a loss of window focus.
6646 // If the window loses focus before it loses pointer capture, then the window can be in a state
6647 // where it has pointer capture but not focus, violating the contract. Therefore we must
6648 // dispatch the pointer capture event before the focus event. Since focus events are added to
6649 // the front of the queue (above), we add the pointer capture event to the front of the queue
6650 // after the focus events are added. This ensures the pointer capture event ends up at the
6651 // front.
6652 disablePointerCaptureForcedLocked();
6653
Vishnu Nairc519ff72021-01-21 08:23:08 -08006654 if (mFocusedDisplayId == changes.displayId) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006655 sendFocusChangedCommandLocked(changes.oldFocus, changes.newFocus);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006656 }
6657}
Vishnu Nair958da932020-08-21 17:12:37 -07006658
Prabir Pradhan99987712020-11-10 18:43:05 -08006659void InputDispatcher::disablePointerCaptureForcedLocked() {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006660 if (!mCurrentPointerCaptureRequest.enable && !mWindowTokenWithPointerCapture) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006661 return;
6662 }
6663
6664 ALOGD_IF(DEBUG_FOCUS, "Disabling Pointer Capture because the window lost focus.");
6665
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006666 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006667 setPointerCaptureLocked(false);
6668 }
6669
6670 if (!mWindowTokenWithPointerCapture) {
6671 // No need to send capture changes because no window has capture.
6672 return;
6673 }
6674
6675 if (mPendingEvent != nullptr) {
6676 // Move the pending event to the front of the queue. This will give the chance
6677 // for the pending event to be dropped if it is a captured event.
6678 mInboundQueue.push_front(mPendingEvent);
6679 mPendingEvent = nullptr;
6680 }
6681
6682 auto entry = std::make_unique<PointerCaptureChangedEntry>(mIdGenerator.nextId(), now(),
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006683 mCurrentPointerCaptureRequest);
Prabir Pradhan99987712020-11-10 18:43:05 -08006684 mInboundQueue.push_front(std::move(entry));
6685}
6686
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006687void InputDispatcher::setPointerCaptureLocked(bool enable) {
6688 mCurrentPointerCaptureRequest.enable = enable;
6689 mCurrentPointerCaptureRequest.seq++;
6690 auto command = [this, request = mCurrentPointerCaptureRequest]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006691 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00006692 mPolicy.setPointerCapture(request);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006693 };
6694 postCommandLocked(std::move(command));
Prabir Pradhan99987712020-11-10 18:43:05 -08006695}
6696
Vishnu Nair599f1412021-06-21 10:39:58 -07006697void InputDispatcher::displayRemoved(int32_t displayId) {
6698 { // acquire lock
6699 std::scoped_lock _l(mLock);
6700 // Set an empty list to remove all handles from the specific display.
Harry Cutts101ee9b2023-07-06 18:04:14 +00006701 setInputWindowsLocked(/*windowInfoHandles=*/{}, displayId);
Vishnu Nair599f1412021-06-21 10:39:58 -07006702 setFocusedApplicationLocked(displayId, nullptr);
6703 // Call focus resolver to clean up stale requests. This must be called after input windows
6704 // have been removed for the removed display.
6705 mFocusResolver.displayRemoved(displayId);
Christine Franksb768bb42021-11-29 12:11:31 -08006706 // Reset pointer capture eligibility, regardless of previous state.
6707 std::erase(mIneligibleDisplaysForPointerCapture, displayId);
Antonio Kantek15beb512022-06-13 22:35:41 +00006708 // Remove the associated touch mode state.
6709 mTouchModePerDisplay.erase(displayId);
Siarhei Vishniakou5c02a712023-05-15 15:45:02 -07006710 mVerifiersByDisplay.erase(displayId);
Vishnu Nair599f1412021-06-21 10:39:58 -07006711 } // release lock
6712
6713 // Wake up poll loop since it may need to make new input dispatching choices.
6714 mLooper->wake();
6715}
6716
Patrick Williamsd828f302023-04-28 17:52:08 -05006717void InputDispatcher::onWindowInfosChanged(const gui::WindowInfosUpdate& update) {
chaviw15fab6f2021-06-07 14:15:52 -05006718 // The listener sends the windows as a flattened array. Separate the windows by display for
6719 // more convenient parsing.
6720 std::unordered_map<int32_t, std::vector<sp<WindowInfoHandle>>> handlesPerDisplay;
Patrick Williamsd828f302023-04-28 17:52:08 -05006721 for (const auto& info : update.windowInfos) {
chaviw15fab6f2021-06-07 14:15:52 -05006722 handlesPerDisplay.emplace(info.displayId, std::vector<sp<WindowInfoHandle>>());
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07006723 handlesPerDisplay[info.displayId].push_back(sp<WindowInfoHandle>::make(info));
chaviw15fab6f2021-06-07 14:15:52 -05006724 }
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006725
6726 { // acquire lock
6727 std::scoped_lock _l(mLock);
Prabir Pradhan814fe082022-07-22 20:22:18 +00006728
6729 // Ensure that we have an entry created for all existing displays so that if a displayId has
6730 // no windows, we can tell that the windows were removed from the display.
6731 for (const auto& [displayId, _] : mWindowHandlesByDisplay) {
6732 handlesPerDisplay[displayId];
6733 }
6734
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006735 mDisplayInfos.clear();
Patrick Williamsd828f302023-04-28 17:52:08 -05006736 for (const auto& displayInfo : update.displayInfos) {
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006737 mDisplayInfos.emplace(displayInfo.displayId, displayInfo);
6738 }
6739
6740 for (const auto& [displayId, handles] : handlesPerDisplay) {
6741 setInputWindowsLocked(handles, displayId);
6742 }
Patrick Williams9464b2c2023-05-23 11:22:04 -05006743
6744 if (update.vsyncId < mWindowInfosVsyncId) {
6745 ALOGE("Received out of order window infos update. Last update vsync id: %" PRId64
6746 ", current update vsync id: %" PRId64,
6747 mWindowInfosVsyncId, update.vsyncId);
6748 }
6749 mWindowInfosVsyncId = update.vsyncId;
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006750 }
6751 // Wake up poll loop since it may need to make new input dispatching choices.
6752 mLooper->wake();
chaviw15fab6f2021-06-07 14:15:52 -05006753}
6754
Vishnu Nair062a8672021-09-03 16:07:44 -07006755bool InputDispatcher::shouldDropInput(
6756 const EventEntry& entry, const sp<android::gui::WindowInfoHandle>& windowHandle) const {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006757 if (windowHandle->getInfo()->inputConfig.test(WindowInfo::InputConfig::DROP_INPUT) ||
6758 (windowHandle->getInfo()->inputConfig.test(
6759 WindowInfo::InputConfig::DROP_INPUT_IF_OBSCURED) &&
Vishnu Nair062a8672021-09-03 16:07:44 -07006760 isWindowObscuredLocked(windowHandle))) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006761 ALOGW("Dropping %s event targeting %s as requested by the input configuration {%s} on "
6762 "display %" PRId32 ".",
Vishnu Nair062a8672021-09-03 16:07:44 -07006763 ftl::enum_string(entry.type).c_str(), windowHandle->getName().c_str(),
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006764 windowHandle->getInfo()->inputConfig.string().c_str(),
Vishnu Nair062a8672021-09-03 16:07:44 -07006765 windowHandle->getInfo()->displayId);
6766 return true;
6767 }
6768 return false;
6769}
6770
Siarhei Vishniakou18050092021-09-01 13:32:49 -07006771void InputDispatcher::DispatcherWindowListener::onWindowInfosChanged(
Patrick Williamsd828f302023-04-28 17:52:08 -05006772 const gui::WindowInfosUpdate& update) {
6773 mDispatcher.onWindowInfosChanged(update);
Siarhei Vishniakou18050092021-09-01 13:32:49 -07006774}
6775
Arthur Hungdfd528e2021-12-08 13:23:04 +00006776void InputDispatcher::cancelCurrentTouch() {
6777 {
6778 std::scoped_lock _l(mLock);
6779 ALOGD("Canceling all ongoing pointer gestures on all displays.");
Michael Wrightfb04fd52022-11-24 22:31:11 +00006780 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
Arthur Hungdfd528e2021-12-08 13:23:04 +00006781 "cancel current touch");
6782 synthesizeCancelationEventsForAllConnectionsLocked(options);
6783
6784 mTouchStatesByDisplay.clear();
Arthur Hungdfd528e2021-12-08 13:23:04 +00006785 }
6786 // Wake up poll loop since there might be work to do.
6787 mLooper->wake();
6788}
6789
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006790void InputDispatcher::setMonitorDispatchingTimeoutForTest(std::chrono::nanoseconds timeout) {
6791 std::scoped_lock _l(mLock);
6792 mMonitorDispatchingTimeout = timeout;
6793}
6794
Arthur Hungc539dbb2022-12-08 07:45:36 +00006795void InputDispatcher::slipWallpaperTouch(ftl::Flags<InputTarget::Flags> targetFlags,
6796 const sp<WindowInfoHandle>& oldWindowHandle,
6797 const sp<WindowInfoHandle>& newWindowHandle,
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07006798 TouchState& state, int32_t deviceId, int32_t pointerId,
Siarhei Vishniakoubf880522023-05-01 11:03:22 -07006799 std::vector<InputTarget>& targets) const {
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08006800 std::bitset<MAX_POINTER_ID + 1> pointerIds;
6801 pointerIds.set(pointerId);
Arthur Hungc539dbb2022-12-08 07:45:36 +00006802 const bool oldHasWallpaper = oldWindowHandle->getInfo()->inputConfig.test(
6803 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
6804 const bool newHasWallpaper = targetFlags.test(InputTarget::Flags::FOREGROUND) &&
6805 newWindowHandle->getInfo()->inputConfig.test(
6806 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
6807 const sp<WindowInfoHandle> oldWallpaper =
6808 oldHasWallpaper ? state.getWallpaperWindow() : nullptr;
6809 const sp<WindowInfoHandle> newWallpaper =
6810 newHasWallpaper ? findWallpaperWindowBelow(newWindowHandle) : nullptr;
6811 if (oldWallpaper == newWallpaper) {
6812 return;
6813 }
6814
6815 if (oldWallpaper != nullptr) {
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08006816 const TouchedWindow& oldTouchedWindow = state.getTouchedWindow(oldWallpaper);
6817 addWindowTargetLocked(oldWallpaper,
6818 oldTouchedWindow.targetFlags |
6819 InputTarget::Flags::DISPATCH_AS_SLIPPERY_EXIT,
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07006820 pointerIds, oldTouchedWindow.getDownTimeInTarget(deviceId), targets);
6821 state.removeTouchingPointerFromWindow(deviceId, pointerId, oldWallpaper);
Arthur Hungc539dbb2022-12-08 07:45:36 +00006822 }
6823
6824 if (newWallpaper != nullptr) {
6825 state.addOrUpdateWindow(newWallpaper,
6826 InputTarget::Flags::DISPATCH_AS_SLIPPERY_ENTER |
6827 InputTarget::Flags::WINDOW_IS_OBSCURED |
6828 InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED,
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07006829 deviceId, pointerIds);
Arthur Hungc539dbb2022-12-08 07:45:36 +00006830 }
6831}
6832
6833void InputDispatcher::transferWallpaperTouch(ftl::Flags<InputTarget::Flags> oldTargetFlags,
6834 ftl::Flags<InputTarget::Flags> newTargetFlags,
6835 const sp<WindowInfoHandle> fromWindowHandle,
6836 const sp<WindowInfoHandle> toWindowHandle,
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07006837 TouchState& state, int32_t deviceId,
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08006838 std::bitset<MAX_POINTER_ID + 1> pointerIds) {
Arthur Hungc539dbb2022-12-08 07:45:36 +00006839 const bool oldHasWallpaper = oldTargetFlags.test(InputTarget::Flags::FOREGROUND) &&
6840 fromWindowHandle->getInfo()->inputConfig.test(
6841 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
6842 const bool newHasWallpaper = newTargetFlags.test(InputTarget::Flags::FOREGROUND) &&
6843 toWindowHandle->getInfo()->inputConfig.test(
6844 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
6845
6846 const sp<WindowInfoHandle> oldWallpaper =
6847 oldHasWallpaper ? state.getWallpaperWindow() : nullptr;
6848 const sp<WindowInfoHandle> newWallpaper =
6849 newHasWallpaper ? findWallpaperWindowBelow(toWindowHandle) : nullptr;
6850 if (oldWallpaper == newWallpaper) {
6851 return;
6852 }
6853
6854 if (oldWallpaper != nullptr) {
6855 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
6856 "transferring touch focus to another window");
6857 state.removeWindowByToken(oldWallpaper->getToken());
6858 synthesizeCancelationEventsForWindowLocked(oldWallpaper, options);
6859 }
6860
6861 if (newWallpaper != nullptr) {
6862 nsecs_t downTimeInTarget = now();
6863 ftl::Flags<InputTarget::Flags> wallpaperFlags =
6864 oldTargetFlags & (InputTarget::Flags::SPLIT | InputTarget::Flags::DISPATCH_AS_IS);
6865 wallpaperFlags |= InputTarget::Flags::WINDOW_IS_OBSCURED |
6866 InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED;
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07006867 state.addOrUpdateWindow(newWallpaper, wallpaperFlags, deviceId, pointerIds,
6868 downTimeInTarget);
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006869 std::shared_ptr<Connection> wallpaperConnection =
6870 getConnectionLocked(newWallpaper->getToken());
Arthur Hungc539dbb2022-12-08 07:45:36 +00006871 if (wallpaperConnection != nullptr) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006872 std::shared_ptr<Connection> toConnection =
6873 getConnectionLocked(toWindowHandle->getToken());
Arthur Hungc539dbb2022-12-08 07:45:36 +00006874 toConnection->inputState.mergePointerStateTo(wallpaperConnection->inputState);
6875 synthesizePointerDownEventsForConnectionLocked(downTimeInTarget, wallpaperConnection,
6876 wallpaperFlags);
6877 }
6878 }
6879}
6880
6881sp<WindowInfoHandle> InputDispatcher::findWallpaperWindowBelow(
6882 const sp<WindowInfoHandle>& windowHandle) const {
6883 const std::vector<sp<WindowInfoHandle>>& windowHandles =
6884 getWindowHandlesLocked(windowHandle->getInfo()->displayId);
6885 bool foundWindow = false;
6886 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
6887 if (!foundWindow && otherHandle != windowHandle) {
6888 continue;
6889 }
6890 if (windowHandle == otherHandle) {
6891 foundWindow = true;
6892 continue;
6893 }
6894
6895 if (otherHandle->getInfo()->inputConfig.test(WindowInfo::InputConfig::IS_WALLPAPER)) {
6896 return otherHandle;
6897 }
6898 }
6899 return nullptr;
6900}
6901
Nergi Rahardi730cf3c2023-04-13 12:41:17 +09006902void InputDispatcher::setKeyRepeatConfiguration(nsecs_t timeout, nsecs_t delay) {
6903 std::scoped_lock _l(mLock);
6904
6905 mConfig.keyRepeatTimeout = timeout;
6906 mConfig.keyRepeatDelay = delay;
6907}
6908
Garfield Tane84e6f92019-08-29 17:28:41 -07006909} // namespace android::inputdispatcher