blob: be579329ad5e59806c9e3f4064af59e0b844a69e [file] [log] [blame]
Michael Wrightd02c5b62014-02-10 15:10:22 -08001/*
2 * Copyright (C) 2010 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#define LOG_TAG "InputDispatcher"
18#define ATRACE_TAG ATRACE_TAG_INPUT
19
John Recke0710582019-09-26 13:46:12 -070020#define LOG_NDEBUG 1
Michael Wrightd02c5b62014-02-10 15:10:22 -080021
Michael Wright2b3c3302018-03-02 17:19:13 +000022#include <android-base/chrono_utils.h>
Siarhei Vishniakoud010b012023-01-18 15:00:53 -080023#include <android-base/logging.h>
Peter Collingbourneb04b9b82021-02-08 12:09:47 -080024#include <android-base/properties.h>
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080025#include <android-base/stringprintf.h>
Siarhei Vishniakou70622952020-07-30 11:17:23 -050026#include <android/os/IInputConstants.h>
Robert Carr4e670e52018-08-15 13:26:12 -070027#include <binder/Binder.h>
Dominik Laskowski75788452021-02-09 18:51:25 -080028#include <ftl/enum.h>
Siarhei Vishniakou5c02a712023-05-15 15:45:02 -070029#include <log/log_event_list.h>
Siarhei Vishniakou31977182022-09-30 08:51:23 -070030#if defined(__ANDROID__)
chaviw15fab6f2021-06-07 14:15:52 -050031#include <gui/SurfaceComposerClient.h>
Siarhei Vishniakou31977182022-09-30 08:51:23 -070032#endif
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -080033#include <input/InputDevice.h>
Siarhei Vishniakou6e1e9872022-11-08 17:51:35 -080034#include <input/PrintTools.h>
Prabir Pradhana37bad12023-08-18 15:55:32 +000035#include <input/TraceTools.h>
tyiu1573a672023-02-21 22:38:32 +000036#include <openssl/mem.h>
Garfield Tan0fc2fa72019-08-29 17:22:15 -070037#include <powermanager/PowerManager.h>
Michael Wright44753b12020-07-08 13:48:11 +010038#include <unistd.h>
Garfield Tan0fc2fa72019-08-29 17:22:15 -070039#include <utils/Trace.h>
Michael Wrightd02c5b62014-02-10 15:10:22 -080040
Michael Wright44753b12020-07-08 13:48:11 +010041#include <cerrno>
42#include <cinttypes>
43#include <climits>
44#include <cstddef>
45#include <ctime>
46#include <queue>
47#include <sstream>
48
49#include "Connection.h"
Arthur Hung1a1007b2022-05-11 07:15:01 +000050#include "DebugConfig.h"
Chris Yef59a2f42020-10-16 12:55:26 -070051#include "InputDispatcher.h"
Michael Wright44753b12020-07-08 13:48:11 +010052
Michael Wrightd02c5b62014-02-10 15:10:22 -080053#define INDENT " "
54#define INDENT2 " "
55#define INDENT3 " "
56#define INDENT4 " "
57
Siarhei Vishniakou253f4642022-11-09 13:42:06 -080058using namespace android::ftl::flag_operators;
Siarhei Vishniakou23740b92023-04-21 11:30:20 -070059using android::base::Error;
Peter Collingbourneb04b9b82021-02-08 12:09:47 -080060using android::base::HwTimeoutMultiplier;
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +000061using android::base::Result;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080062using android::base::StringPrintf;
Prabir Pradhan48f8cb92021-08-26 14:05:36 -070063using android::gui::DisplayInfo;
chaviw98318de2021-05-19 16:45:23 -050064using android::gui::FocusRequest;
65using android::gui::TouchOcclusionMode;
66using android::gui::WindowInfo;
67using android::gui::WindowInfoHandle;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -080068using android::os::InputEventInjectionResult;
69using android::os::InputEventInjectionSync;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080070
Garfield Tane84e6f92019-08-29 17:28:41 -070071namespace android::inputdispatcher {
Michael Wrightd02c5b62014-02-10 15:10:22 -080072
Prabir Pradhancef936d2021-07-21 16:17:52 +000073namespace {
Prabir Pradhancef936d2021-07-21 16:17:52 +000074// Temporarily releases a held mutex for the lifetime of the instance.
75// Named to match std::scoped_lock
76class scoped_unlock {
77public:
78 explicit scoped_unlock(std::mutex& mutex) : mMutex(mutex) { mMutex.unlock(); }
79 ~scoped_unlock() { mMutex.lock(); }
80
81private:
82 std::mutex& mMutex;
83};
84
Michael Wrightd02c5b62014-02-10 15:10:22 -080085// Default input dispatching timeout if there is no focused application or paused window
86// from which to determine an appropriate dispatching timeout.
Peter Collingbourneb04b9b82021-02-08 12:09:47 -080087const std::chrono::duration DEFAULT_INPUT_DISPATCHING_TIMEOUT = std::chrono::milliseconds(
88 android::os::IInputConstants::UNMULTIPLIED_DEFAULT_DISPATCHING_TIMEOUT_MILLIS *
89 HwTimeoutMultiplier());
Michael Wrightd02c5b62014-02-10 15:10:22 -080090
91// Amount of time to allow for all pending events to be processed when an app switch
92// key is on the way. This is used to preempt input dispatch and drop input events
93// when an application takes too long to respond and the user has pressed an app switch key.
Michael Wright2b3c3302018-03-02 17:19:13 +000094constexpr nsecs_t APP_SWITCH_TIMEOUT = 500 * 1000000LL; // 0.5sec
Michael Wrightd02c5b62014-02-10 15:10:22 -080095
Siarhei Vishniakou289e9242022-02-15 14:50:16 -080096const std::chrono::duration STALE_EVENT_TIMEOUT = std::chrono::seconds(10) * HwTimeoutMultiplier();
Michael Wrightd02c5b62014-02-10 15:10:22 -080097
Michael Wrightd02c5b62014-02-10 15:10:22 -080098// Log a warning when an event takes longer than this to process, even if an ANR does not occur.
Michael Wright2b3c3302018-03-02 17:19:13 +000099constexpr nsecs_t SLOW_EVENT_PROCESSING_WARNING_TIMEOUT = 2000 * 1000000LL; // 2sec
100
101// Log a warning when an interception call takes longer than this to process.
102constexpr std::chrono::milliseconds SLOW_INTERCEPTION_THRESHOLD = 50ms;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800103
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700104// Additional key latency in case a connection is still processing some motion events.
105// This will help with the case when a user touched a button that opens a new window,
106// and gives us the chance to dispatch the key to this new window.
107constexpr std::chrono::nanoseconds KEY_WAITING_FOR_EVENTS_TIMEOUT = 500ms;
108
Michael Wrightd02c5b62014-02-10 15:10:22 -0800109// Number of recent events to keep for debugging purposes.
Michael Wright2b3c3302018-03-02 17:19:13 +0000110constexpr size_t RECENT_QUEUE_MAX_SIZE = 10;
111
Antonio Kantekea47acb2021-12-23 12:41:25 -0800112// Event log tags. See EventLogTags.logtags for reference.
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +0000113constexpr int LOGTAG_INPUT_INTERACTION = 62000;
114constexpr int LOGTAG_INPUT_FOCUS = 62001;
Arthur Hungb3307ee2021-10-14 10:57:37 +0000115constexpr int LOGTAG_INPUT_CANCEL = 62003;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +0000116
Prabir Pradhan33e3baa2022-12-06 20:30:22 +0000117const ui::Transform kIdentityTransform;
118
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000119inline nsecs_t now() {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800120 return systemTime(SYSTEM_TIME_MONOTONIC);
121}
122
Siarhei Vishniakoud38a1e02023-07-18 11:55:17 -0700123bool isEmpty(const std::stringstream& ss) {
124 return ss.rdbuf()->in_avail() == 0;
125}
126
Siarhei Vishniakou63b63612023-04-12 11:00:23 -0700127inline const std::string binderToString(const sp<IBinder>& binder) {
Bernardo Rufino49d99e42021-01-18 15:16:59 +0000128 if (binder == nullptr) {
129 return "<null>";
130 }
131 return StringPrintf("%p", binder.get());
132}
133
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +0000134static std::string uidString(const gui::Uid& uid) {
135 return uid.toString();
136}
137
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700138Result<void> checkKeyAction(int32_t action) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800139 switch (action) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700140 case AKEY_EVENT_ACTION_DOWN:
141 case AKEY_EVENT_ACTION_UP:
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700142 return {};
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700143 default:
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700144 return Error() << "Key event has invalid action code " << action;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800145 }
146}
147
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700148Result<void> validateKeyEvent(int32_t action) {
149 return checkKeyAction(action);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800150}
151
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700152Result<void> checkMotionAction(int32_t action, int32_t actionButton, int32_t pointerCount) {
Siarhei Vishniakou2f61bdc2022-12-02 08:55:51 -0800153 switch (MotionEvent::getActionMasked(action)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700154 case AMOTION_EVENT_ACTION_DOWN:
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700155 case AMOTION_EVENT_ACTION_UP: {
156 if (pointerCount != 1) {
157 return Error() << "invalid pointer count " << pointerCount;
158 }
159 return {};
160 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700161 case AMOTION_EVENT_ACTION_MOVE:
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700162 case AMOTION_EVENT_ACTION_HOVER_ENTER:
163 case AMOTION_EVENT_ACTION_HOVER_MOVE:
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700164 case AMOTION_EVENT_ACTION_HOVER_EXIT: {
165 if (pointerCount < 1) {
166 return Error() << "invalid pointer count " << pointerCount;
167 }
168 return {};
169 }
Siarhei Vishniakou2f61bdc2022-12-02 08:55:51 -0800170 case AMOTION_EVENT_ACTION_CANCEL:
171 case AMOTION_EVENT_ACTION_OUTSIDE:
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700172 case AMOTION_EVENT_ACTION_SCROLL:
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700173 return {};
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700174 case AMOTION_EVENT_ACTION_POINTER_DOWN:
175 case AMOTION_EVENT_ACTION_POINTER_UP: {
Siarhei Vishniakou2f61bdc2022-12-02 08:55:51 -0800176 const int32_t index = MotionEvent::getActionIndex(action);
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700177 if (index < 0) {
178 return Error() << "invalid index " << index << " for "
179 << MotionEvent::actionToString(action);
180 }
181 if (index >= pointerCount) {
182 return Error() << "invalid index " << index << " for pointerCount " << pointerCount;
183 }
184 if (pointerCount <= 1) {
185 return Error() << "invalid pointer count " << pointerCount << " for "
186 << MotionEvent::actionToString(action);
187 }
188 return {};
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700189 }
190 case AMOTION_EVENT_ACTION_BUTTON_PRESS:
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700191 case AMOTION_EVENT_ACTION_BUTTON_RELEASE: {
192 if (actionButton == 0) {
193 return Error() << "action button should be nonzero for "
194 << MotionEvent::actionToString(action);
195 }
196 return {};
197 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700198 default:
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700199 return Error() << "invalid action " << action;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800200 }
201}
202
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000203int64_t millis(std::chrono::nanoseconds t) {
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -0500204 return std::chrono::duration_cast<std::chrono::milliseconds>(t).count();
205}
206
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700207Result<void> validateMotionEvent(int32_t action, int32_t actionButton, size_t pointerCount,
208 const PointerProperties* pointerProperties) {
209 Result<void> actionCheck = checkMotionAction(action, actionButton, pointerCount);
210 if (!actionCheck.ok()) {
211 return actionCheck;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800212 }
213 if (pointerCount < 1 || pointerCount > MAX_POINTERS) {
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700214 return Error() << "Motion event has invalid pointer count " << pointerCount
215 << "; value must be between 1 and " << MAX_POINTERS << ".";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800216 }
Siarhei Vishniakou8a878352023-01-30 14:05:01 -0800217 std::bitset<MAX_POINTER_ID + 1> pointerIdBits;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800218 for (size_t i = 0; i < pointerCount; i++) {
219 int32_t id = pointerProperties[i].id;
220 if (id < 0 || id > MAX_POINTER_ID) {
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700221 return Error() << "Motion event has invalid pointer id " << id
222 << "; value must be between 0 and " << MAX_POINTER_ID;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800223 }
Siarhei Vishniakou8a878352023-01-30 14:05:01 -0800224 if (pointerIdBits.test(id)) {
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700225 return Error() << "Motion event has duplicate pointer id " << id;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800226 }
Siarhei Vishniakou8a878352023-01-30 14:05:01 -0800227 pointerIdBits.set(id);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800228 }
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700229 return {};
230}
231
232Result<void> validateInputEvent(const InputEvent& event) {
233 switch (event.getType()) {
234 case InputEventType::KEY: {
235 const KeyEvent& key = static_cast<const KeyEvent&>(event);
236 const int32_t action = key.getAction();
237 return validateKeyEvent(action);
238 }
239 case InputEventType::MOTION: {
240 const MotionEvent& motion = static_cast<const MotionEvent&>(event);
241 const int32_t action = motion.getAction();
242 const size_t pointerCount = motion.getPointerCount();
243 const PointerProperties* pointerProperties = motion.getPointerProperties();
244 const int32_t actionButton = motion.getActionButton();
245 return validateMotionEvent(action, actionButton, pointerCount, pointerProperties);
246 }
247 default: {
248 return {};
249 }
250 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800251}
252
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000253std::string dumpRegion(const Region& region) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800254 if (region.isEmpty()) {
Bernardo Rufino53fc31e2020-11-03 11:01:07 +0000255 return "<empty>";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800256 }
257
Bernardo Rufino53fc31e2020-11-03 11:01:07 +0000258 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800259 bool first = true;
260 Region::const_iterator cur = region.begin();
261 Region::const_iterator const tail = region.end();
262 while (cur != tail) {
263 if (first) {
264 first = false;
265 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800266 dump += "|";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800267 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800268 dump += StringPrintf("[%d,%d][%d,%d]", cur->left, cur->top, cur->right, cur->bottom);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800269 cur++;
270 }
Bernardo Rufino53fc31e2020-11-03 11:01:07 +0000271 return dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800272}
273
Prabir Pradhan8c90d782023-09-15 21:16:44 +0000274std::string dumpQueue(const std::deque<std::unique_ptr<DispatchEntry>>& queue,
275 nsecs_t currentTime) {
Siarhei Vishniakou14411c92020-09-18 21:15:05 -0500276 constexpr size_t maxEntries = 50; // max events to print
277 constexpr size_t skipBegin = maxEntries / 2;
278 const size_t skipEnd = queue.size() - maxEntries / 2;
279 // skip from maxEntries / 2 ... size() - maxEntries/2
280 // only print from 0 .. skipBegin and then from skipEnd .. size()
281
282 std::string dump;
283 for (size_t i = 0; i < queue.size(); i++) {
284 const DispatchEntry& entry = *queue[i];
285 if (i >= skipBegin && i < skipEnd) {
286 dump += StringPrintf(INDENT4 "<skipped %zu entries>\n", skipEnd - skipBegin);
287 i = skipEnd - 1; // it will be incremented to "skipEnd" by 'continue'
288 continue;
289 }
290 dump.append(INDENT4);
291 dump += entry.eventEntry->getDescription();
Siarhei Vishniakou253f4642022-11-09 13:42:06 -0800292 dump += StringPrintf(", seq=%" PRIu32 ", targetFlags=%s, resolvedAction=%d, age=%" PRId64
293 "ms",
294 entry.seq, entry.targetFlags.string().c_str(), entry.resolvedAction,
Siarhei Vishniakou14411c92020-09-18 21:15:05 -0500295 ns2ms(currentTime - entry.eventEntry->eventTime));
296 if (entry.deliveryTime != 0) {
297 // This entry was delivered, so add information on how long we've been waiting
298 dump += StringPrintf(", wait=%" PRId64 "ms", ns2ms(currentTime - entry.deliveryTime));
299 }
300 dump.append("\n");
301 }
302 return dump;
303}
304
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -0700305/**
306 * Find the entry in std::unordered_map by key, and return it.
307 * If the entry is not found, return a default constructed entry.
308 *
309 * Useful when the entries are vectors, since an empty vector will be returned
310 * if the entry is not found.
311 * Also useful when the entries are sp<>. If an entry is not found, nullptr is returned.
312 */
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700313template <typename K, typename V>
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000314V getValueByKey(const std::unordered_map<K, V>& map, K key) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -0700315 auto it = map.find(key);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700316 return it != map.end() ? it->second : V{};
Tiger Huang721e26f2018-07-24 22:26:19 +0800317}
318
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000319bool haveSameToken(const sp<WindowInfoHandle>& first, const sp<WindowInfoHandle>& second) {
chaviwaf87b3e2019-10-01 16:59:28 -0700320 if (first == second) {
321 return true;
322 }
323
324 if (first == nullptr || second == nullptr) {
325 return false;
326 }
327
328 return first->getToken() == second->getToken();
329}
330
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000331bool haveSameApplicationToken(const WindowInfo* first, const WindowInfo* second) {
Bernardo Rufino1ff9d592021-01-18 16:58:57 +0000332 if (first == nullptr || second == nullptr) {
333 return false;
334 }
335 return first->applicationInfo.token != nullptr &&
336 first->applicationInfo.token == second->applicationInfo.token;
337}
338
Siarhei Vishniakou8a878352023-01-30 14:05:01 -0800339template <typename T>
340size_t firstMarkedBit(T set) {
341 // TODO: replace with std::countr_zero from <bit> when that's available
342 LOG_ALWAYS_FATAL_IF(set.none());
343 size_t i = 0;
344 while (!set.test(i)) {
345 i++;
346 }
347 return i;
348}
349
Siarhei Vishniakou253f4642022-11-09 13:42:06 -0800350std::unique_ptr<DispatchEntry> createDispatchEntry(
351 const InputTarget& inputTarget, std::shared_ptr<EventEntry> eventEntry,
352 ftl::Flags<InputTarget::Flags> inputTargetFlags) {
chaviw1ff3d1e2020-07-01 15:53:47 -0700353 if (inputTarget.useDefaultPointerTransform()) {
354 const ui::Transform& transform = inputTarget.getDefaultPointerTransform();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700355 return std::make_unique<DispatchEntry>(eventEntry, inputTargetFlags, transform,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700356 inputTarget.displayTransform,
357 inputTarget.globalScaleFactor);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000358 }
359
360 ALOG_ASSERT(eventEntry->type == EventEntry::Type::MOTION);
361 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(*eventEntry);
362
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700363 std::vector<PointerCoords> pointerCoords;
364 pointerCoords.resize(motionEntry.pointerCount);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000365
366 // Use the first pointer information to normalize all other pointers. This could be any pointer
367 // as long as all other pointers are normalized to the same value and the final DispatchEntry
chaviw1ff3d1e2020-07-01 15:53:47 -0700368 // uses the transform for the normalized pointer.
369 const ui::Transform& firstPointerTransform =
Siarhei Vishniakou8a878352023-01-30 14:05:01 -0800370 inputTarget.pointerTransforms[firstMarkedBit(inputTarget.pointerIds)];
chaviw1ff3d1e2020-07-01 15:53:47 -0700371 ui::Transform inverseFirstTransform = firstPointerTransform.inverse();
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000372
373 // Iterate through all pointers in the event to normalize against the first.
374 for (uint32_t pointerIndex = 0; pointerIndex < motionEntry.pointerCount; pointerIndex++) {
375 const PointerProperties& pointerProperties = motionEntry.pointerProperties[pointerIndex];
376 uint32_t pointerId = uint32_t(pointerProperties.id);
chaviw1ff3d1e2020-07-01 15:53:47 -0700377 const ui::Transform& currTransform = inputTarget.pointerTransforms[pointerId];
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000378
379 pointerCoords[pointerIndex].copyFrom(motionEntry.pointerCoords[pointerIndex]);
chaviw1ff3d1e2020-07-01 15:53:47 -0700380 // First, apply the current pointer's transform to update the coordinates into
381 // window space.
382 pointerCoords[pointerIndex].transform(currTransform);
383 // Next, apply the inverse transform of the normalized coordinates so the
384 // current coordinates are transformed into the normalized coordinate space.
385 pointerCoords[pointerIndex].transform(inverseFirstTransform);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000386 }
387
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700388 std::unique_ptr<MotionEntry> combinedMotionEntry =
389 std::make_unique<MotionEntry>(motionEntry.id, motionEntry.eventTime,
390 motionEntry.deviceId, motionEntry.source,
391 motionEntry.displayId, motionEntry.policyFlags,
392 motionEntry.action, motionEntry.actionButton,
393 motionEntry.flags, motionEntry.metaState,
394 motionEntry.buttonState, motionEntry.classification,
395 motionEntry.edgeFlags, motionEntry.xPrecision,
396 motionEntry.yPrecision, motionEntry.xCursorPosition,
397 motionEntry.yCursorPosition, motionEntry.downTime,
398 motionEntry.pointerCount, motionEntry.pointerProperties,
Prabir Pradhan5beda762021-12-10 09:30:08 +0000399 pointerCoords.data());
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000400
401 if (motionEntry.injectionState) {
402 combinedMotionEntry->injectionState = motionEntry.injectionState;
403 combinedMotionEntry->injectionState->refCount += 1;
404 }
405
406 std::unique_ptr<DispatchEntry> dispatchEntry =
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700407 std::make_unique<DispatchEntry>(std::move(combinedMotionEntry), inputTargetFlags,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700408 firstPointerTransform, inputTarget.displayTransform,
409 inputTarget.globalScaleFactor);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000410 return dispatchEntry;
411}
412
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000413status_t openInputChannelPair(const std::string& name, std::shared_ptr<InputChannel>& serverChannel,
414 std::unique_ptr<InputChannel>& clientChannel) {
Garfield Tan15601662020-09-22 15:32:38 -0700415 std::unique_ptr<InputChannel> uniqueServerChannel;
416 status_t result = InputChannel::openInputChannelPair(name, uniqueServerChannel, clientChannel);
417
418 serverChannel = std::move(uniqueServerChannel);
419 return result;
420}
421
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -0500422template <typename T>
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000423bool sharedPointersEqual(const std::shared_ptr<T>& lhs, const std::shared_ptr<T>& rhs) {
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -0500424 if (lhs == nullptr && rhs == nullptr) {
425 return true;
426 }
427 if (lhs == nullptr || rhs == nullptr) {
428 return false;
429 }
430 return *lhs == *rhs;
431}
432
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000433KeyEvent createKeyEvent(const KeyEntry& entry) {
Siarhei Vishniakou2e2ea992020-12-15 02:57:19 +0000434 KeyEvent event;
435 event.initialize(entry.id, entry.deviceId, entry.source, entry.displayId, INVALID_HMAC,
436 entry.action, entry.flags, entry.keyCode, entry.scanCode, entry.metaState,
437 entry.repeatCount, entry.downTime, entry.eventTime);
438 return event;
439}
440
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000441bool shouldReportMetricsForConnection(const Connection& connection) {
Siarhei Vishniakouf2652122021-03-05 21:39:46 +0000442 // Do not keep track of gesture monitors. They receive every event and would disproportionately
443 // affect the statistics.
444 if (connection.monitor) {
445 return false;
446 }
447 // If the connection is experiencing ANR, let's skip it. We have separate ANR metrics
448 if (!connection.responsive) {
449 return false;
450 }
451 return true;
452}
453
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000454bool shouldReportFinishedEvent(const DispatchEntry& dispatchEntry, const Connection& connection) {
Siarhei Vishniakouf2652122021-03-05 21:39:46 +0000455 const EventEntry& eventEntry = *dispatchEntry.eventEntry;
456 const int32_t& inputEventId = eventEntry.id;
457 if (inputEventId != dispatchEntry.resolvedEventId) {
458 // Event was transmuted
459 return false;
460 }
461 if (inputEventId == android::os::IInputConstants::INVALID_INPUT_EVENT_ID) {
462 return false;
463 }
464 // Only track latency for events that originated from hardware
465 if (eventEntry.isSynthesized()) {
466 return false;
467 }
468 const EventEntry::Type& inputEventEntryType = eventEntry.type;
469 if (inputEventEntryType == EventEntry::Type::KEY) {
470 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
471 if (keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) {
472 return false;
473 }
474 } else if (inputEventEntryType == EventEntry::Type::MOTION) {
475 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
476 if (motionEntry.action == AMOTION_EVENT_ACTION_CANCEL ||
477 motionEntry.action == AMOTION_EVENT_ACTION_HOVER_EXIT) {
478 return false;
479 }
480 } else {
481 // Not a key or a motion
482 return false;
483 }
484 if (!shouldReportMetricsForConnection(connection)) {
485 return false;
486 }
487 return true;
488}
489
Prabir Pradhancef936d2021-07-21 16:17:52 +0000490/**
491 * Connection is responsive if it has no events in the waitQueue that are older than the
492 * current time.
493 */
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000494bool isConnectionResponsive(const Connection& connection) {
Prabir Pradhancef936d2021-07-21 16:17:52 +0000495 const nsecs_t currentTime = now();
Prabir Pradhan8c90d782023-09-15 21:16:44 +0000496 for (const auto& dispatchEntry : connection.waitQueue) {
497 if (dispatchEntry->timeoutTime < currentTime) {
Prabir Pradhancef936d2021-07-21 16:17:52 +0000498 return false;
499 }
500 }
501 return true;
502}
503
Antonio Kantekf16f2832021-09-28 04:39:20 +0000504// Returns true if the event type passed as argument represents a user activity.
505bool isUserActivityEvent(const EventEntry& eventEntry) {
506 switch (eventEntry.type) {
Josep del Riob3981622023-04-18 15:49:45 +0000507 case EventEntry::Type::CONFIGURATION_CHANGED:
508 case EventEntry::Type::DEVICE_RESET:
509 case EventEntry::Type::DRAG:
Antonio Kantekf16f2832021-09-28 04:39:20 +0000510 case EventEntry::Type::FOCUS:
511 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
Antonio Kantekf16f2832021-09-28 04:39:20 +0000512 case EventEntry::Type::SENSOR:
Josep del Riob3981622023-04-18 15:49:45 +0000513 case EventEntry::Type::TOUCH_MODE_CHANGED:
Antonio Kantekf16f2832021-09-28 04:39:20 +0000514 return false;
Antonio Kantekf16f2832021-09-28 04:39:20 +0000515 case EventEntry::Type::KEY:
516 case EventEntry::Type::MOTION:
517 return true;
518 }
519}
520
Prabir Pradhan3f90d312021-11-19 03:57:24 -0800521// Returns true if the given window can accept pointer events at the given display location.
Prabir Pradhan82e081e2022-12-06 09:50:09 +0000522bool windowAcceptsTouchAt(const WindowInfo& windowInfo, int32_t displayId, float x, float y,
Prabir Pradhan33e3baa2022-12-06 20:30:22 +0000523 bool isStylus, const ui::Transform& displayTransform) {
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -0800524 const auto inputConfig = windowInfo.inputConfig;
525 if (windowInfo.displayId != displayId ||
526 inputConfig.test(WindowInfo::InputConfig::NOT_VISIBLE)) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -0800527 return false;
528 }
Prabir Pradhand65552b2021-10-07 11:23:50 -0700529 const bool windowCanInterceptTouch = isStylus && windowInfo.interceptsStylus();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -0800530 if (inputConfig.test(WindowInfo::InputConfig::NOT_TOUCHABLE) && !windowCanInterceptTouch) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -0800531 return false;
532 }
Prabir Pradhan33e3baa2022-12-06 20:30:22 +0000533
534 // Window Manager works in the logical display coordinate space. When it specifies bounds for a
535 // window as (l, t, r, b), the range of x in [l, r) and y in [t, b) are considered to be inside
536 // the window. Points on the right and bottom edges should not be inside the window, so we need
537 // to be careful about performing a hit test when the display is rotated, since the "right" and
538 // "bottom" of the window will be different in the display (un-rotated) space compared to in the
539 // logical display in which WM determined the bounds. Perform the hit test in the logical
540 // display space to ensure these edges are considered correctly in all orientations.
541 const auto touchableRegion = displayTransform.transform(windowInfo.touchableRegion);
542 const auto p = displayTransform.transform(x, y);
543 if (!touchableRegion.contains(std::floor(p.x), std::floor(p.y))) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -0800544 return false;
545 }
546 return true;
547}
548
Prabir Pradhand65552b2021-10-07 11:23:50 -0700549bool isPointerFromStylus(const MotionEntry& entry, int32_t pointerIndex) {
550 return isFromSource(entry.source, AINPUT_SOURCE_STYLUS) &&
Prabir Pradhane5626962022-10-27 20:30:53 +0000551 isStylusToolType(entry.pointerProperties[pointerIndex].toolType);
Prabir Pradhand65552b2021-10-07 11:23:50 -0700552}
553
Siarhei Vishniakou253f4642022-11-09 13:42:06 -0800554// Determines if the given window can be targeted as InputTarget::Flags::FOREGROUND.
Prabir Pradhan6dfbf262022-03-14 15:24:30 +0000555// Foreground events are only sent to "foreground targetable" windows, but not all gestures sent to
556// such window are necessarily targeted with the flag. For example, an event with ACTION_OUTSIDE can
557// be sent to such a window, but it is not a foreground event and doesn't use
Siarhei Vishniakou253f4642022-11-09 13:42:06 -0800558// InputTarget::Flags::FOREGROUND.
Prabir Pradhan6dfbf262022-03-14 15:24:30 +0000559bool canReceiveForegroundTouches(const WindowInfo& info) {
560 // A non-touchable window can still receive touch events (e.g. in the case of
561 // STYLUS_INTERCEPTOR), so prevent such windows from receiving foreground events for touches.
562 return !info.inputConfig.test(gui::WindowInfo::InputConfig::NOT_TOUCHABLE) && !info.isSpy();
563}
564
Prabir Pradhanaeebeb42023-06-13 19:53:03 +0000565bool isWindowOwnedBy(const sp<WindowInfoHandle>& windowHandle, gui::Pid pid, gui::Uid uid) {
Antonio Kantek48710e42022-03-24 14:19:30 -0700566 if (windowHandle == nullptr) {
567 return false;
568 }
569 const WindowInfo* windowInfo = windowHandle->getInfo();
570 if (pid == windowInfo->ownerPid && uid == windowInfo->ownerUid) {
571 return true;
572 }
573 return false;
574}
575
Prabir Pradhan5735a322022-04-11 17:23:34 +0000576// Checks targeted injection using the window's owner's uid.
577// Returns an empty string if an entry can be sent to the given window, or an error message if the
578// entry is a targeted injection whose uid target doesn't match the window owner.
579std::optional<std::string> verifyTargetedInjection(const sp<WindowInfoHandle>& window,
580 const EventEntry& entry) {
581 if (entry.injectionState == nullptr || !entry.injectionState->targetUid) {
582 // The event was not injected, or the injected event does not target a window.
583 return {};
584 }
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +0000585 const auto uid = *entry.injectionState->targetUid;
Prabir Pradhan5735a322022-04-11 17:23:34 +0000586 if (window == nullptr) {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +0000587 return StringPrintf("No valid window target for injection into uid %s.",
588 uid.toString().c_str());
Prabir Pradhan5735a322022-04-11 17:23:34 +0000589 }
590 if (entry.injectionState->targetUid != window->getInfo()->ownerUid) {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +0000591 return StringPrintf("Injected event targeted at uid %s would be dispatched to window '%s' "
592 "owned by uid %s.",
593 uid.toString().c_str(), window->getName().c_str(),
594 window->getInfo()->ownerUid.toString().c_str());
Prabir Pradhan5735a322022-04-11 17:23:34 +0000595 }
596 return {};
597}
598
Prabir Pradhan82e081e2022-12-06 09:50:09 +0000599std::pair<float, float> resolveTouchedPosition(const MotionEntry& entry) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -0700600 const bool isFromMouse = isFromSource(entry.source, AINPUT_SOURCE_MOUSE);
601 // Always dispatch mouse events to cursor position.
602 if (isFromMouse) {
Prabir Pradhan82e081e2022-12-06 09:50:09 +0000603 return {entry.xCursorPosition, entry.yCursorPosition};
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -0700604 }
605
Siarhei Vishniakou5b9766d2023-07-18 14:06:29 -0700606 const int32_t pointerIndex = MotionEvent::getActionIndex(entry.action);
Prabir Pradhan82e081e2022-12-06 09:50:09 +0000607 return {entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_X),
608 entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_Y)};
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -0700609}
610
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -0700611std::optional<nsecs_t> getDownTime(const EventEntry& eventEntry) {
612 if (eventEntry.type == EventEntry::Type::KEY) {
613 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
614 return keyEntry.downTime;
615 } else if (eventEntry.type == EventEntry::Type::MOTION) {
616 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
617 return motionEntry.downTime;
618 }
619 return std::nullopt;
620}
621
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000622/**
623 * Compare the old touch state to the new touch state, and generate the corresponding touched
624 * windows (== input targets).
625 * If a window had the hovering pointer, but now it doesn't, produce HOVER_EXIT for that window.
626 * If the pointer just entered the new window, produce HOVER_ENTER.
627 * For pointers remaining in the window, produce HOVER_MOVE.
628 */
629std::vector<TouchedWindow> getHoveringWindowsLocked(const TouchState* oldState,
630 const TouchState& newTouchState,
631 const MotionEntry& entry) {
632 std::vector<TouchedWindow> out;
633 const int32_t maskedAction = MotionEvent::getActionMasked(entry.action);
634 if (maskedAction != AMOTION_EVENT_ACTION_HOVER_ENTER &&
635 maskedAction != AMOTION_EVENT_ACTION_HOVER_MOVE &&
636 maskedAction != AMOTION_EVENT_ACTION_HOVER_EXIT) {
637 // Not a hover event - don't need to do anything
638 return out;
639 }
640
641 // We should consider all hovering pointers here. But for now, just use the first one
642 const int32_t pointerId = entry.pointerProperties[0].id;
643
644 std::set<sp<WindowInfoHandle>> oldWindows;
645 if (oldState != nullptr) {
646 oldWindows = oldState->getWindowsWithHoveringPointer(entry.deviceId, pointerId);
647 }
648
649 std::set<sp<WindowInfoHandle>> newWindows =
650 newTouchState.getWindowsWithHoveringPointer(entry.deviceId, pointerId);
651
652 // If the pointer is no longer in the new window set, send HOVER_EXIT.
653 for (const sp<WindowInfoHandle>& oldWindow : oldWindows) {
654 if (newWindows.find(oldWindow) == newWindows.end()) {
655 TouchedWindow touchedWindow;
656 touchedWindow.windowHandle = oldWindow;
657 touchedWindow.targetFlags = InputTarget::Flags::DISPATCH_AS_HOVER_EXIT;
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000658 out.push_back(touchedWindow);
659 }
660 }
661
662 for (const sp<WindowInfoHandle>& newWindow : newWindows) {
663 TouchedWindow touchedWindow;
664 touchedWindow.windowHandle = newWindow;
665 if (oldWindows.find(newWindow) == oldWindows.end()) {
666 // Any windows that have this pointer now, and didn't have it before, should get
667 // HOVER_ENTER
668 touchedWindow.targetFlags = InputTarget::Flags::DISPATCH_AS_HOVER_ENTER;
669 } else {
670 // This pointer was already sent to the window. Use ACTION_HOVER_MOVE.
Siarhei Vishniakouc2eb8502023-04-11 18:33:36 -0700671 if (CC_UNLIKELY(maskedAction != AMOTION_EVENT_ACTION_HOVER_MOVE)) {
Daniel Norman7487dfa2023-08-02 16:39:45 -0700672 android::base::LogSeverity severity = android::base::LogSeverity::FATAL;
673 if (entry.flags & AMOTION_EVENT_FLAG_IS_ACCESSIBILITY_EVENT) {
674 // The Accessibility injected touch exploration event stream
675 // has known inconsistencies, so log ERROR instead of
676 // crashing the device with FATAL.
677 // TODO(b/299977100): Move a11y severity back to FATAL.
678 severity = android::base::LogSeverity::ERROR;
679 }
680 LOG(severity) << "Expected ACTION_HOVER_MOVE instead of " << entry.getDescription();
Siarhei Vishniakouc2eb8502023-04-11 18:33:36 -0700681 }
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000682 touchedWindow.targetFlags = InputTarget::Flags::DISPATCH_AS_IS;
683 }
Siarhei Vishniakou0836a302023-05-03 13:54:30 -0700684 touchedWindow.addHoveringPointer(entry.deviceId, pointerId);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000685 if (canReceiveForegroundTouches(*newWindow->getInfo())) {
686 touchedWindow.targetFlags |= InputTarget::Flags::FOREGROUND;
687 }
688 out.push_back(touchedWindow);
689 }
690 return out;
691}
692
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -0800693template <typename T>
694std::vector<T>& operator+=(std::vector<T>& left, const std::vector<T>& right) {
695 left.insert(left.end(), right.begin(), right.end());
696 return left;
697}
698
Harry Cuttsb166c002023-05-09 13:06:05 +0000699// Filter windows in a TouchState and targets in a vector to remove untrusted windows/targets from
700// both.
701void filterUntrustedTargets(TouchState& touchState, std::vector<InputTarget>& targets) {
702 std::erase_if(touchState.windows, [&](const TouchedWindow& window) {
703 if (!window.windowHandle->getInfo()->inputConfig.test(
704 WindowInfo::InputConfig::TRUSTED_OVERLAY)) {
705 // In addition to TouchState, erase this window from the input targets! We don't have a
706 // good way to do this today except by adding a nested loop.
707 // TODO(b/282025641): simplify this code once InputTargets are being identified
708 // separately from TouchedWindows.
709 std::erase_if(targets, [&](const InputTarget& target) {
710 return target.inputChannel->getConnectionToken() == window.windowHandle->getToken();
711 });
712 return true;
713 }
714 return false;
715 });
716}
717
Siarhei Vishniakouce1fd472023-09-18 18:38:07 -0700718/**
719 * In general, touch should be always split between windows. Some exceptions:
720 * 1. Don't split touch if all of the below is true:
721 * (a) we have an active pointer down *and*
722 * (b) a new pointer is going down that's from the same device *and*
723 * (c) the window that's receiving the current pointer does not support split touch.
724 * 2. Don't split mouse events
725 */
726bool shouldSplitTouch(const TouchState& touchState, const MotionEntry& entry) {
727 if (isFromSource(entry.source, AINPUT_SOURCE_MOUSE)) {
728 // We should never split mouse events
729 return false;
730 }
731 for (const TouchedWindow& touchedWindow : touchState.windows) {
732 if (touchedWindow.windowHandle->getInfo()->isSpy()) {
733 // Spy windows should not affect whether or not touch is split.
734 continue;
735 }
736 if (touchedWindow.windowHandle->getInfo()->supportsSplitTouch()) {
737 continue;
738 }
739 if (touchedWindow.windowHandle->getInfo()->inputConfig.test(
740 gui::WindowInfo::InputConfig::IS_WALLPAPER)) {
741 // Wallpaper window should not affect whether or not touch is split
742 continue;
743 }
744
745 if (touchedWindow.hasTouchingPointers(entry.deviceId)) {
746 return false;
747 }
748 }
749 return true;
750}
751
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000752} // namespace
753
Michael Wrightd02c5b62014-02-10 15:10:22 -0800754// --- InputDispatcher ---
755
Prabir Pradhana41d2442023-04-20 21:30:40 +0000756InputDispatcher::InputDispatcher(InputDispatcherPolicyInterface& policy)
Siarhei Vishniakou289e9242022-02-15 14:50:16 -0800757 : InputDispatcher(policy, STALE_EVENT_TIMEOUT) {}
758
Prabir Pradhana41d2442023-04-20 21:30:40 +0000759InputDispatcher::InputDispatcher(InputDispatcherPolicyInterface& policy,
Siarhei Vishniakou289e9242022-02-15 14:50:16 -0800760 std::chrono::nanoseconds staleEventTimeout)
Garfield Tan00f511d2019-06-12 16:55:40 -0700761 : mPolicy(policy),
762 mPendingEvent(nullptr),
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700763 mLastDropReason(DropReason::NOT_DROPPED),
Garfield Tanff1f1bb2020-01-28 13:24:04 -0800764 mIdGenerator(IdGenerator::Source::INPUT_DISPATCHER),
Garfield Tan00f511d2019-06-12 16:55:40 -0700765 mAppSwitchSawKeyDown(false),
Colin Cross5b799302022-10-18 21:52:41 -0700766 mAppSwitchDueTime(LLONG_MAX),
Garfield Tan00f511d2019-06-12 16:55:40 -0700767 mNextUnblockedEvent(nullptr),
Prabir Pradhan1376fcd2022-01-21 09:56:35 -0800768 mMonitorDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT),
Garfield Tan00f511d2019-06-12 16:55:40 -0700769 mDispatchEnabled(false),
770 mDispatchFrozen(false),
771 mInputFilterEnabled(false),
Bernardo Rufinoea97d182020-08-19 14:43:14 +0100772 mMaximumObscuringOpacityForTouch(1.0f),
Siarhei Vishniakou2508b872020-12-03 16:33:53 -1000773 mFocusedDisplayId(ADISPLAY_ID_DEFAULT),
Prabir Pradhan99987712020-11-10 18:43:05 -0800774 mWindowTokenWithPointerCapture(nullptr),
Siarhei Vishniakou289e9242022-02-15 14:50:16 -0800775 mStaleEventTimeout(staleEventTimeout),
Siarhei Vishniakoua04181f2021-03-26 05:56:49 +0000776 mLatencyAggregator(),
Antonio Kantek15beb512022-06-13 22:35:41 +0000777 mLatencyTracker(&mLatencyAggregator) {
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -0700778 mLooper = sp<Looper>::make(false);
Prabir Pradhanf93562f2018-11-29 12:13:37 -0800779 mReporter = createInputReporter();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800780
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -0700781 mWindowInfoListener = sp<DispatcherWindowListener>::make(*this);
Siarhei Vishniakou31977182022-09-30 08:51:23 -0700782#if defined(__ANDROID__)
Siarhei Vishniakou18050092021-09-01 13:32:49 -0700783 SurfaceComposerClient::getDefault()->addWindowInfosListener(mWindowInfoListener);
Siarhei Vishniakou31977182022-09-30 08:51:23 -0700784#endif
Yi Kong9b14ac62018-07-17 13:48:38 -0700785 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800786}
787
788InputDispatcher::~InputDispatcher() {
Prabir Pradhancef936d2021-07-21 16:17:52 +0000789 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800790
Prabir Pradhancef936d2021-07-21 16:17:52 +0000791 resetKeyRepeatLocked();
792 releasePendingEventLocked();
793 drainInboundQueueLocked();
794 mCommandQueue.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800795
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +0000796 while (!mConnectionsByToken.empty()) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -0700797 std::shared_ptr<Connection> connection = mConnectionsByToken.begin()->second;
Harry Cutts33476232023-01-30 19:57:29 +0000798 removeInputChannelLocked(connection->inputChannel->getConnectionToken(), /*notify=*/false);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800799 }
800}
801
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700802status_t InputDispatcher::start() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700803 if (mThread) {
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700804 return ALREADY_EXISTS;
805 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700806 mThread = std::make_unique<InputThread>(
807 "InputDispatcher", [this]() { dispatchOnce(); }, [this]() { mLooper->wake(); });
808 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700809}
810
811status_t InputDispatcher::stop() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700812 if (mThread && mThread->isCallingThread()) {
813 ALOGE("InputDispatcher cannot be stopped from its own thread!");
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700814 return INVALID_OPERATION;
815 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700816 mThread.reset();
817 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700818}
819
Michael Wrightd02c5b62014-02-10 15:10:22 -0800820void InputDispatcher::dispatchOnce() {
Colin Cross5b799302022-10-18 21:52:41 -0700821 nsecs_t nextWakeupTime = LLONG_MAX;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800822 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -0800823 std::scoped_lock _l(mLock);
824 mDispatcherIsAlive.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800825
826 // Run a dispatch loop if there are no pending commands.
827 // The dispatch loop might enqueue commands to run afterwards.
828 if (!haveCommandsLocked()) {
829 dispatchOnceInnerLocked(&nextWakeupTime);
830 }
831
832 // Run all pending commands if there are any.
833 // If any commands were run then force the next poll to wake up immediately.
Prabir Pradhancef936d2021-07-21 16:17:52 +0000834 if (runCommandsLockedInterruptable()) {
Colin Cross5b799302022-10-18 21:52:41 -0700835 nextWakeupTime = LLONG_MIN;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800836 }
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800837
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700838 // If we are still waiting for ack on some events,
839 // we might have to wake up earlier to check if an app is anr'ing.
840 const nsecs_t nextAnrCheck = processAnrsLocked();
841 nextWakeupTime = std::min(nextWakeupTime, nextAnrCheck);
842
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800843 // We are about to enter an infinitely long sleep, because we have no commands or
844 // pending or queued events
Colin Cross5b799302022-10-18 21:52:41 -0700845 if (nextWakeupTime == LLONG_MAX) {
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800846 mDispatcherEnteredIdle.notify_all();
847 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800848 } // release lock
849
850 // Wait for callback or timeout or wake. (make sure we round up, not down)
851 nsecs_t currentTime = now();
852 int timeoutMillis = toMillisecondTimeoutDelay(currentTime, nextWakeupTime);
853 mLooper->pollOnce(timeoutMillis);
854}
855
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700856/**
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500857 * Raise ANR if there is no focused window.
858 * Before the ANR is raised, do a final state check:
859 * 1. The currently focused application must be the same one we are waiting for.
860 * 2. Ensure we still don't have a focused window.
861 */
862void InputDispatcher::processNoFocusedWindowAnrLocked() {
863 // Check if the application that we are waiting for is still focused.
864 std::shared_ptr<InputApplicationHandle> focusedApplication =
865 getValueByKey(mFocusedApplicationHandlesByDisplay, mAwaitedApplicationDisplayId);
866 if (focusedApplication == nullptr ||
867 focusedApplication->getApplicationToken() !=
868 mAwaitedFocusedApplication->getApplicationToken()) {
869 // Unexpected because we should have reset the ANR timer when focused application changed
870 ALOGE("Waited for a focused window, but focused application has already changed to %s",
871 focusedApplication->getName().c_str());
872 return; // The focused application has changed.
873 }
874
chaviw98318de2021-05-19 16:45:23 -0500875 const sp<WindowInfoHandle>& focusedWindowHandle =
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500876 getFocusedWindowHandleLocked(mAwaitedApplicationDisplayId);
877 if (focusedWindowHandle != nullptr) {
878 return; // We now have a focused window. No need for ANR.
879 }
880 onAnrLocked(mAwaitedFocusedApplication);
881}
882
883/**
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700884 * Check if any of the connections' wait queues have events that are too old.
885 * If we waited for events to be ack'ed for more than the window timeout, raise an ANR.
886 * Return the time at which we should wake up next.
887 */
888nsecs_t InputDispatcher::processAnrsLocked() {
889 const nsecs_t currentTime = now();
Colin Cross5b799302022-10-18 21:52:41 -0700890 nsecs_t nextAnrCheck = LLONG_MAX;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700891 // Check if we are waiting for a focused window to appear. Raise ANR if waited too long
892 if (mNoFocusedWindowTimeoutTime.has_value() && mAwaitedFocusedApplication != nullptr) {
893 if (currentTime >= *mNoFocusedWindowTimeoutTime) {
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500894 processNoFocusedWindowAnrLocked();
Chris Yea209fde2020-07-22 13:54:51 -0700895 mAwaitedFocusedApplication.reset();
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500896 mNoFocusedWindowTimeoutTime = std::nullopt;
Colin Cross5b799302022-10-18 21:52:41 -0700897 return LLONG_MIN;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700898 } else {
Siarhei Vishniakou38a6d272020-10-20 20:29:33 -0500899 // Keep waiting. We will drop the event when mNoFocusedWindowTimeoutTime comes.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700900 nextAnrCheck = *mNoFocusedWindowTimeoutTime;
901 }
902 }
903
904 // Check if any connection ANRs are due
905 nextAnrCheck = std::min(nextAnrCheck, mAnrTracker.firstTimeout());
906 if (currentTime < nextAnrCheck) { // most likely scenario
907 return nextAnrCheck; // everything is normal. Let's check again at nextAnrCheck
908 }
909
910 // If we reached here, we have an unresponsive connection.
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -0700911 std::shared_ptr<Connection> connection = getConnectionLocked(mAnrTracker.firstToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700912 if (connection == nullptr) {
913 ALOGE("Could not find connection for entry %" PRId64, mAnrTracker.firstTimeout());
914 return nextAnrCheck;
915 }
916 connection->responsive = false;
917 // Stop waking up for this unresponsive connection
918 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000919 onAnrLocked(connection);
Colin Cross5b799302022-10-18 21:52:41 -0700920 return LLONG_MIN;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700921}
922
Prabir Pradhan1376fcd2022-01-21 09:56:35 -0800923std::chrono::nanoseconds InputDispatcher::getDispatchingTimeoutLocked(
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -0700924 const std::shared_ptr<Connection>& connection) {
Prabir Pradhan1376fcd2022-01-21 09:56:35 -0800925 if (connection->monitor) {
926 return mMonitorDispatchingTimeout;
927 }
928 const sp<WindowInfoHandle> window =
929 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700930 if (window != nullptr) {
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500931 return window->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700932 }
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500933 return DEFAULT_INPUT_DISPATCHING_TIMEOUT;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700934}
935
Michael Wrightd02c5b62014-02-10 15:10:22 -0800936void InputDispatcher::dispatchOnceInnerLocked(nsecs_t* nextWakeupTime) {
937 nsecs_t currentTime = now();
938
Jeff Browndc5992e2014-04-11 01:27:26 -0700939 // Reset the key repeat timer whenever normal dispatch is suspended while the
940 // device is in a non-interactive state. This is to ensure that we abort a key
941 // repeat if the device is just coming out of sleep.
942 if (!mDispatchEnabled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800943 resetKeyRepeatLocked();
944 }
945
946 // If dispatching is frozen, do not process timeouts or try to deliver any new events.
947 if (mDispatchFrozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +0100948 if (DEBUG_FOCUS) {
949 ALOGD("Dispatch frozen. Waiting some more.");
950 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800951 return;
952 }
953
954 // Optimize latency of app switches.
955 // Essentially we start a short timeout when an app switch key (HOME / ENDCALL) has
956 // been pressed. When it expires, we preempt dispatch and drop all other pending events.
957 bool isAppSwitchDue = mAppSwitchDueTime <= currentTime;
958 if (mAppSwitchDueTime < *nextWakeupTime) {
959 *nextWakeupTime = mAppSwitchDueTime;
960 }
961
962 // Ready to start a new event.
963 // If we don't already have a pending event, go grab one.
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700964 if (!mPendingEvent) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700965 if (mInboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800966 if (isAppSwitchDue) {
967 // The inbound queue is empty so the app switch key we were waiting
968 // for will never arrive. Stop waiting for it.
969 resetPendingAppSwitchLocked(false);
970 isAppSwitchDue = false;
971 }
972
973 // Synthesize a key repeat if appropriate.
974 if (mKeyRepeatState.lastKeyEntry) {
975 if (currentTime >= mKeyRepeatState.nextRepeatTime) {
976 mPendingEvent = synthesizeKeyRepeatLocked(currentTime);
977 } else {
978 if (mKeyRepeatState.nextRepeatTime < *nextWakeupTime) {
979 *nextWakeupTime = mKeyRepeatState.nextRepeatTime;
980 }
981 }
982 }
983
984 // Nothing to do if there is no pending event.
985 if (!mPendingEvent) {
986 return;
987 }
988 } else {
989 // Inbound queue has at least one entry.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700990 mPendingEvent = mInboundQueue.front();
991 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800992 traceInboundQueueLengthLocked();
993 }
994
995 // Poke user activity for this event.
996 if (mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700997 pokeUserActivityLocked(*mPendingEvent);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800998 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800999 }
1000
1001 // Now we have an event to dispatch.
1002 // All events are eventually dequeued and processed this way, even if we intend to drop them.
Yi Kong9b14ac62018-07-17 13:48:38 -07001003 ALOG_ASSERT(mPendingEvent != nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001004 bool done = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001005 DropReason dropReason = DropReason::NOT_DROPPED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001006 if (!(mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001007 dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001008 } else if (!mDispatchEnabled) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001009 dropReason = DropReason::DISABLED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001010 }
1011
1012 if (mNextUnblockedEvent == mPendingEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001013 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001014 }
1015
1016 switch (mPendingEvent->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001017 case EventEntry::Type::CONFIGURATION_CHANGED: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001018 const ConfigurationChangedEntry& typedEntry =
1019 static_cast<const ConfigurationChangedEntry&>(*mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001020 done = dispatchConfigurationChangedLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001021 dropReason = DropReason::NOT_DROPPED; // configuration changes are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001022 break;
1023 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001024
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001025 case EventEntry::Type::DEVICE_RESET: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001026 const DeviceResetEntry& typedEntry =
1027 static_cast<const DeviceResetEntry&>(*mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001028 done = dispatchDeviceResetLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001029 dropReason = DropReason::NOT_DROPPED; // device resets are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001030 break;
1031 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001032
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001033 case EventEntry::Type::FOCUS: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001034 std::shared_ptr<FocusEntry> typedEntry =
1035 std::static_pointer_cast<FocusEntry>(mPendingEvent);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001036 dispatchFocusLocked(currentTime, typedEntry);
1037 done = true;
1038 dropReason = DropReason::NOT_DROPPED; // focus events are never dropped
1039 break;
1040 }
1041
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001042 case EventEntry::Type::TOUCH_MODE_CHANGED: {
1043 const auto typedEntry = std::static_pointer_cast<TouchModeEntry>(mPendingEvent);
1044 dispatchTouchModeChangeLocked(currentTime, typedEntry);
1045 done = true;
1046 dropReason = DropReason::NOT_DROPPED; // touch mode events are never dropped
1047 break;
1048 }
1049
Prabir Pradhan99987712020-11-10 18:43:05 -08001050 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
1051 const auto typedEntry =
1052 std::static_pointer_cast<PointerCaptureChangedEntry>(mPendingEvent);
1053 dispatchPointerCaptureChangedLocked(currentTime, typedEntry, dropReason);
1054 done = true;
1055 break;
1056 }
1057
arthurhungb89ccb02020-12-30 16:19:01 +08001058 case EventEntry::Type::DRAG: {
1059 std::shared_ptr<DragEntry> typedEntry =
1060 std::static_pointer_cast<DragEntry>(mPendingEvent);
1061 dispatchDragLocked(currentTime, typedEntry);
1062 done = true;
1063 break;
1064 }
1065
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001066 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001067 std::shared_ptr<KeyEntry> keyEntry = std::static_pointer_cast<KeyEntry>(mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001068 if (isAppSwitchDue) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001069 if (isAppSwitchKeyEvent(*keyEntry)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001070 resetPendingAppSwitchLocked(true);
1071 isAppSwitchDue = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001072 } else if (dropReason == DropReason::NOT_DROPPED) {
1073 dropReason = DropReason::APP_SWITCH;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001074 }
1075 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001076 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *keyEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001077 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001078 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001079 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
1080 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001081 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001082 done = dispatchKeyLocked(currentTime, keyEntry, &dropReason, nextWakeupTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001083 break;
1084 }
1085
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001086 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001087 std::shared_ptr<MotionEntry> motionEntry =
1088 std::static_pointer_cast<MotionEntry>(mPendingEvent);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001089 if (dropReason == DropReason::NOT_DROPPED && isAppSwitchDue) {
1090 dropReason = DropReason::APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001091 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001092 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *motionEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001093 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001094 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001095 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
1096 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001097 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001098 done = dispatchMotionLocked(currentTime, motionEntry, &dropReason, nextWakeupTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001099 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001100 }
Chris Yef59a2f42020-10-16 12:55:26 -07001101
1102 case EventEntry::Type::SENSOR: {
1103 std::shared_ptr<SensorEntry> sensorEntry =
1104 std::static_pointer_cast<SensorEntry>(mPendingEvent);
1105 if (dropReason == DropReason::NOT_DROPPED && isAppSwitchDue) {
1106 dropReason = DropReason::APP_SWITCH;
1107 }
1108 // Sensor timestamps use SYSTEM_TIME_BOOTTIME time base, so we can't use
1109 // 'currentTime' here, get SYSTEM_TIME_BOOTTIME instead.
1110 nsecs_t bootTime = systemTime(SYSTEM_TIME_BOOTTIME);
1111 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(bootTime, *sensorEntry)) {
1112 dropReason = DropReason::STALE;
1113 }
1114 dispatchSensorLocked(currentTime, sensorEntry, &dropReason, nextWakeupTime);
1115 done = true;
1116 break;
1117 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001118 }
1119
1120 if (done) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001121 if (dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001122 dropInboundEventLocked(*mPendingEvent, dropReason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001123 }
Michael Wright3a981722015-06-10 15:26:13 +01001124 mLastDropReason = dropReason;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001125
1126 releasePendingEventLocked();
Colin Cross5b799302022-10-18 21:52:41 -07001127 *nextWakeupTime = LLONG_MIN; // force next poll to wake up immediately
Michael Wrightd02c5b62014-02-10 15:10:22 -08001128 }
1129}
1130
Siarhei Vishniakou289e9242022-02-15 14:50:16 -08001131bool InputDispatcher::isStaleEvent(nsecs_t currentTime, const EventEntry& entry) {
1132 return std::chrono::nanoseconds(currentTime - entry.eventTime) >= mStaleEventTimeout;
1133}
1134
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001135/**
1136 * Return true if the events preceding this incoming motion event should be dropped
1137 * Return false otherwise (the default behaviour)
1138 */
1139bool InputDispatcher::shouldPruneInboundQueueLocked(const MotionEntry& motionEntry) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001140 const bool isPointerDownEvent = motionEntry.action == AMOTION_EVENT_ACTION_DOWN &&
Prabir Pradhanaa561d12021-09-24 06:57:33 -07001141 isFromSource(motionEntry.source, AINPUT_SOURCE_CLASS_POINTER);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001142
1143 // Optimize case where the current application is unresponsive and the user
1144 // decides to touch a window in a different application.
1145 // If the application takes too long to catch up then we drop all events preceding
1146 // the touch into the other window.
1147 if (isPointerDownEvent && mAwaitedFocusedApplication != nullptr) {
Siarhei Vishniakou9306c382022-09-30 15:30:31 -07001148 const int32_t displayId = motionEntry.displayId;
1149 const auto [x, y] = resolveTouchedPosition(motionEntry);
Harry Cutts33476232023-01-30 19:57:29 +00001150 const bool isStylus = isPointerFromStylus(motionEntry, /*pointerIndex=*/0);
Siarhei Vishniakou9306c382022-09-30 15:30:31 -07001151
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07001152 sp<WindowInfoHandle> touchedWindowHandle =
1153 findTouchedWindowAtLocked(displayId, x, y, isStylus);
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001154 if (touchedWindowHandle != nullptr &&
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001155 touchedWindowHandle->getApplicationToken() !=
1156 mAwaitedFocusedApplication->getApplicationToken()) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001157 // User touched a different application than the one we are waiting on.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001158 ALOGI("Pruning input queue because user touched a different application while waiting "
1159 "for %s",
1160 mAwaitedFocusedApplication->getName().c_str());
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001161 return true;
1162 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001163
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08001164 // Alternatively, maybe there's a spy window that could handle this event.
1165 const std::vector<sp<WindowInfoHandle>> touchedSpies =
1166 findTouchedSpyWindowsAtLocked(displayId, x, y, isStylus);
1167 for (const auto& windowHandle : touchedSpies) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07001168 const std::shared_ptr<Connection> connection =
1169 getConnectionLocked(windowHandle->getToken());
Siarhei Vishniakou34ed4d42020-06-18 00:43:02 +00001170 if (connection != nullptr && connection->responsive) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08001171 // This spy window could take more input. Drop all events preceding this
1172 // event, so that the spy window can get a chance to receive the stream.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001173 ALOGW("Pruning the input queue because %s is unresponsive, but we have a "
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08001174 "responsive spy window that may handle the event.",
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001175 mAwaitedFocusedApplication->getName().c_str());
1176 return true;
1177 }
1178 }
1179 }
1180
1181 // Prevent getting stuck: if we have a pending key event, and some motion events that have not
1182 // yet been processed by some connections, the dispatcher will wait for these motion
1183 // events to be processed before dispatching the key event. This is because these motion events
1184 // may cause a new window to be launched, which the user might expect to receive focus.
1185 // To prevent waiting forever for such events, just send the key to the currently focused window
1186 if (isPointerDownEvent && mKeyIsWaitingForEventsTimeout) {
1187 ALOGD("Received a new pointer down event, stop waiting for events to process and "
1188 "just send the pending key event to the focused window.");
1189 mKeyIsWaitingForEventsTimeout = now();
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001190 }
1191 return false;
1192}
1193
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001194bool InputDispatcher::enqueueInboundEventLocked(std::unique_ptr<EventEntry> newEntry) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001195 bool needWake = mInboundQueue.empty();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001196 mInboundQueue.push_back(std::move(newEntry));
1197 EventEntry& entry = *(mInboundQueue.back());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001198 traceInboundQueueLengthLocked();
1199
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001200 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001201 case EventEntry::Type::KEY: {
Prabir Pradhan5735a322022-04-11 17:23:34 +00001202 LOG_ALWAYS_FATAL_IF((entry.policyFlags & POLICY_FLAG_TRUSTED) == 0,
1203 "Unexpected untrusted event.");
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001204 // Optimize app switch latency.
1205 // If the application takes too long to catch up then we drop all events preceding
1206 // the app switch key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001207 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001208 if (isAppSwitchKeyEvent(keyEntry)) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001209 if (keyEntry.action == AKEY_EVENT_ACTION_DOWN) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001210 mAppSwitchSawKeyDown = true;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001211 } else if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001212 if (mAppSwitchSawKeyDown) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001213 if (DEBUG_APP_SWITCH) {
1214 ALOGD("App switch is pending!");
1215 }
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001216 mAppSwitchDueTime = keyEntry.eventTime + APP_SWITCH_TIMEOUT;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001217 mAppSwitchSawKeyDown = false;
1218 needWake = true;
1219 }
1220 }
1221 }
Arthur Hung2ee6d0b2022-03-03 20:19:38 +08001222
1223 // If a new up event comes in, and the pending event with same key code has been asked
1224 // to try again later because of the policy. We have to reset the intercept key wake up
1225 // time for it may have been handled in the policy and could be dropped.
1226 if (keyEntry.action == AKEY_EVENT_ACTION_UP && mPendingEvent &&
1227 mPendingEvent->type == EventEntry::Type::KEY) {
1228 KeyEntry& pendingKey = static_cast<KeyEntry&>(*mPendingEvent);
1229 if (pendingKey.keyCode == keyEntry.keyCode &&
1230 pendingKey.interceptKeyResult ==
Michael Wright5caf55a2022-11-24 22:31:42 +00001231 KeyEntry::InterceptKeyResult::TRY_AGAIN_LATER) {
1232 pendingKey.interceptKeyResult = KeyEntry::InterceptKeyResult::UNKNOWN;
Arthur Hung2ee6d0b2022-03-03 20:19:38 +08001233 pendingKey.interceptKeyWakeupTime = 0;
1234 needWake = true;
1235 }
1236 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001237 break;
1238 }
1239
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001240 case EventEntry::Type::MOTION: {
Prabir Pradhan5735a322022-04-11 17:23:34 +00001241 LOG_ALWAYS_FATAL_IF((entry.policyFlags & POLICY_FLAG_TRUSTED) == 0,
1242 "Unexpected untrusted event.");
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001243 if (shouldPruneInboundQueueLocked(static_cast<MotionEntry&>(entry))) {
1244 mNextUnblockedEvent = mInboundQueue.back();
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001245 needWake = true;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001246 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001247 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001248 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001249 case EventEntry::Type::FOCUS: {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001250 LOG_ALWAYS_FATAL("Focus events should be inserted using enqueueFocusEventLocked");
1251 break;
1252 }
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001253 case EventEntry::Type::TOUCH_MODE_CHANGED:
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001254 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08001255 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07001256 case EventEntry::Type::SENSOR:
arthurhungb89ccb02020-12-30 16:19:01 +08001257 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
1258 case EventEntry::Type::DRAG: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001259 // nothing to do
1260 break;
1261 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001262 }
1263
1264 return needWake;
1265}
1266
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001267void InputDispatcher::addRecentEventLocked(std::shared_ptr<EventEntry> entry) {
Chris Yef59a2f42020-10-16 12:55:26 -07001268 // Do not store sensor event in recent queue to avoid flooding the queue.
1269 if (entry->type != EventEntry::Type::SENSOR) {
1270 mRecentQueue.push_back(entry);
1271 }
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001272 if (mRecentQueue.size() > RECENT_QUEUE_MAX_SIZE) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001273 mRecentQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001274 }
1275}
1276
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07001277sp<WindowInfoHandle> InputDispatcher::findTouchedWindowAtLocked(int32_t displayId, float x, float y,
1278 bool isStylus,
1279 bool ignoreDragWindow) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001280 // Traverse windows from front to back to find touched window.
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001281 const auto& windowHandles = getWindowHandlesLocked(displayId);
chaviw98318de2021-05-19 16:45:23 -05001282 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
arthurhung6d4bed92021-03-17 11:59:33 +08001283 if (ignoreDragWindow && haveSameToken(windowHandle, mDragState->dragWindow)) {
arthurhungb89ccb02020-12-30 16:19:01 +08001284 continue;
1285 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001286
Prabir Pradhan3f90d312021-11-19 03:57:24 -08001287 const WindowInfo& info = *windowHandle->getInfo();
Prabir Pradhan33e3baa2022-12-06 20:30:22 +00001288 if (!info.isSpy() &&
1289 windowAcceptsTouchAt(info, displayId, x, y, isStylus, getTransformLocked(displayId))) {
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07001290 return windowHandle;
1291 }
1292 }
1293 return nullptr;
1294}
1295
1296std::vector<InputTarget> InputDispatcher::findOutsideTargetsLocked(
Siarhei Vishniakou70f3d8c2023-09-19 15:36:52 -07001297 int32_t displayId, const sp<WindowInfoHandle>& touchedWindow, int32_t pointerId) const {
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07001298 if (touchedWindow == nullptr) {
1299 return {};
1300 }
1301 // Traverse windows from front to back until we encounter the touched window.
1302 std::vector<InputTarget> outsideTargets;
1303 const auto& windowHandles = getWindowHandlesLocked(displayId);
1304 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
1305 if (windowHandle == touchedWindow) {
1306 // Stop iterating once we found a touched window. Any WATCH_OUTSIDE_TOUCH window
1307 // below the touched window will not get ACTION_OUTSIDE event.
1308 return outsideTargets;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08001309 }
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001310
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07001311 const WindowInfo& info = *windowHandle->getInfo();
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08001312 if (info.inputConfig.test(WindowInfo::InputConfig::WATCH_OUTSIDE_TOUCH)) {
Siarhei Vishniakou70f3d8c2023-09-19 15:36:52 -07001313 std::bitset<MAX_POINTER_ID + 1> pointerIds;
1314 pointerIds.set(pointerId);
1315 addWindowTargetLocked(windowHandle, InputTarget::Flags::DISPATCH_AS_OUTSIDE, pointerIds,
1316 /*firstDownTimeInTarget=*/std::nullopt, outsideTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001317 }
1318 }
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07001319 return outsideTargets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001320}
1321
Prabir Pradhand65552b2021-10-07 11:23:50 -07001322std::vector<sp<WindowInfoHandle>> InputDispatcher::findTouchedSpyWindowsAtLocked(
Prabir Pradhan82e081e2022-12-06 09:50:09 +00001323 int32_t displayId, float x, float y, bool isStylus) const {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001324 // Traverse windows from front to back and gather the touched spy windows.
1325 std::vector<sp<WindowInfoHandle>> spyWindows;
1326 const auto& windowHandles = getWindowHandlesLocked(displayId);
1327 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
1328 const WindowInfo& info = *windowHandle->getInfo();
1329
Prabir Pradhan33e3baa2022-12-06 20:30:22 +00001330 if (!windowAcceptsTouchAt(info, displayId, x, y, isStylus, getTransformLocked(displayId))) {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001331 continue;
1332 }
1333 if (!info.isSpy()) {
1334 // The first touched non-spy window was found, so return the spy windows touched so far.
1335 return spyWindows;
1336 }
1337 spyWindows.push_back(windowHandle);
1338 }
1339 return spyWindows;
1340}
1341
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001342void InputDispatcher::dropInboundEventLocked(const EventEntry& entry, DropReason dropReason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001343 const char* reason;
1344 switch (dropReason) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001345 case DropReason::POLICY:
Prabir Pradhan65613802023-02-22 23:36:58 +00001346 if (debugInboundEventDetails()) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001347 ALOGD("Dropped event because policy consumed it.");
1348 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001349 reason = "inbound event was dropped because the policy consumed it";
1350 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001351 case DropReason::DISABLED:
1352 if (mLastDropReason != DropReason::DISABLED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001353 ALOGI("Dropped event because input dispatch is disabled.");
1354 }
1355 reason = "inbound event was dropped because input dispatch is disabled";
1356 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001357 case DropReason::APP_SWITCH:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001358 ALOGI("Dropped event because of pending overdue app switch.");
1359 reason = "inbound event was dropped because of pending overdue app switch";
1360 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001361 case DropReason::BLOCKED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001362 ALOGI("Dropped event because the current application is not responding and the user "
1363 "has started interacting with a different application.");
1364 reason = "inbound event was dropped because the current application is not responding "
1365 "and the user has started interacting with a different application";
1366 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001367 case DropReason::STALE:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001368 ALOGI("Dropped event because it is stale.");
1369 reason = "inbound event was dropped because it is stale";
1370 break;
Prabir Pradhan99987712020-11-10 18:43:05 -08001371 case DropReason::NO_POINTER_CAPTURE:
1372 ALOGI("Dropped event because there is no window with Pointer Capture.");
1373 reason = "inbound event was dropped because there is no window with Pointer Capture";
1374 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001375 case DropReason::NOT_DROPPED: {
1376 LOG_ALWAYS_FATAL("Should not be dropping a NOT_DROPPED event");
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001377 return;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001378 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001379 }
1380
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001381 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001382 case EventEntry::Type::KEY: {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001383 CancelationOptions options(CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS, reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001384 synthesizeCancelationEventsForAllConnectionsLocked(options);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001385 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001386 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001387 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001388 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
1389 if (motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001390 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS, reason);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001391 synthesizeCancelationEventsForAllConnectionsLocked(options);
1392 } else {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001393 CancelationOptions options(CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS,
1394 reason);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001395 synthesizeCancelationEventsForAllConnectionsLocked(options);
1396 }
1397 break;
1398 }
Chris Yef59a2f42020-10-16 12:55:26 -07001399 case EventEntry::Type::SENSOR: {
1400 break;
1401 }
arthurhungb89ccb02020-12-30 16:19:01 +08001402 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
1403 case EventEntry::Type::DRAG: {
Prabir Pradhan99987712020-11-10 18:43:05 -08001404 break;
1405 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001406 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001407 case EventEntry::Type::TOUCH_MODE_CHANGED:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001408 case EventEntry::Type::CONFIGURATION_CHANGED:
1409 case EventEntry::Type::DEVICE_RESET: {
Dominik Laskowski75788452021-02-09 18:51:25 -08001410 LOG_ALWAYS_FATAL("Should not drop %s events", ftl::enum_string(entry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001411 break;
1412 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001413 }
1414}
1415
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08001416static bool isAppSwitchKeyCode(int32_t keyCode) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001417 return keyCode == AKEYCODE_HOME || keyCode == AKEYCODE_ENDCALL ||
1418 keyCode == AKEYCODE_APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001419}
1420
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001421bool InputDispatcher::isAppSwitchKeyEvent(const KeyEntry& keyEntry) {
1422 return !(keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) && isAppSwitchKeyCode(keyEntry.keyCode) &&
1423 (keyEntry.policyFlags & POLICY_FLAG_TRUSTED) &&
1424 (keyEntry.policyFlags & POLICY_FLAG_PASS_TO_USER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001425}
1426
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07001427bool InputDispatcher::isAppSwitchPendingLocked() const {
Colin Cross5b799302022-10-18 21:52:41 -07001428 return mAppSwitchDueTime != LLONG_MAX;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001429}
1430
1431void InputDispatcher::resetPendingAppSwitchLocked(bool handled) {
Colin Cross5b799302022-10-18 21:52:41 -07001432 mAppSwitchDueTime = LLONG_MAX;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001433
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001434 if (DEBUG_APP_SWITCH) {
1435 if (handled) {
1436 ALOGD("App switch has arrived.");
1437 } else {
1438 ALOGD("App switch was abandoned.");
1439 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001440 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001441}
1442
Michael Wrightd02c5b62014-02-10 15:10:22 -08001443bool InputDispatcher::haveCommandsLocked() const {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001444 return !mCommandQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001445}
1446
Prabir Pradhancef936d2021-07-21 16:17:52 +00001447bool InputDispatcher::runCommandsLockedInterruptable() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001448 if (mCommandQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001449 return false;
1450 }
1451
1452 do {
Prabir Pradhancef936d2021-07-21 16:17:52 +00001453 auto command = std::move(mCommandQueue.front());
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001454 mCommandQueue.pop_front();
Prabir Pradhancef936d2021-07-21 16:17:52 +00001455 // Commands are run with the lock held, but may release and re-acquire the lock from within.
1456 command();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001457 } while (!mCommandQueue.empty());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001458 return true;
1459}
1460
Prabir Pradhancef936d2021-07-21 16:17:52 +00001461void InputDispatcher::postCommandLocked(Command&& command) {
1462 mCommandQueue.push_back(command);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001463}
1464
1465void InputDispatcher::drainInboundQueueLocked() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001466 while (!mInboundQueue.empty()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001467 std::shared_ptr<EventEntry> entry = mInboundQueue.front();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001468 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001469 releaseInboundEventLocked(entry);
1470 }
1471 traceInboundQueueLengthLocked();
1472}
1473
1474void InputDispatcher::releasePendingEventLocked() {
1475 if (mPendingEvent) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001476 releaseInboundEventLocked(mPendingEvent);
Yi Kong9b14ac62018-07-17 13:48:38 -07001477 mPendingEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001478 }
1479}
1480
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001481void InputDispatcher::releaseInboundEventLocked(std::shared_ptr<EventEntry> entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001482 InjectionState* injectionState = entry->injectionState;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001483 if (injectionState && injectionState->injectionResult == InputEventInjectionResult::PENDING) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001484 if (DEBUG_DISPATCH_CYCLE) {
1485 ALOGD("Injected inbound event was dropped.");
1486 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001487 setInjectionResult(*entry, InputEventInjectionResult::FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001488 }
1489 if (entry == mNextUnblockedEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001490 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001491 }
1492 addRecentEventLocked(entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001493}
1494
1495void InputDispatcher::resetKeyRepeatLocked() {
1496 if (mKeyRepeatState.lastKeyEntry) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001497 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001498 }
1499}
1500
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001501std::shared_ptr<KeyEntry> InputDispatcher::synthesizeKeyRepeatLocked(nsecs_t currentTime) {
1502 std::shared_ptr<KeyEntry> entry = mKeyRepeatState.lastKeyEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001503
Michael Wright2e732952014-09-24 13:26:59 -07001504 uint32_t policyFlags = entry->policyFlags &
1505 (POLICY_FLAG_RAW_MASK | POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_TRUSTED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001506
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001507 std::shared_ptr<KeyEntry> newEntry =
1508 std::make_unique<KeyEntry>(mIdGenerator.nextId(), currentTime, entry->deviceId,
1509 entry->source, entry->displayId, policyFlags, entry->action,
1510 entry->flags, entry->keyCode, entry->scanCode,
1511 entry->metaState, entry->repeatCount + 1, entry->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001512
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001513 newEntry->syntheticRepeat = true;
1514 mKeyRepeatState.lastKeyEntry = newEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001515 mKeyRepeatState.nextRepeatTime = currentTime + mConfig.keyRepeatDelay;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001516 return newEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001517}
1518
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001519bool InputDispatcher::dispatchConfigurationChangedLocked(nsecs_t currentTime,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001520 const ConfigurationChangedEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001521 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1522 ALOGD("dispatchConfigurationChanged - eventTime=%" PRId64, entry.eventTime);
1523 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001524
1525 // Reset key repeating in case a keyboard device was added or removed or something.
1526 resetKeyRepeatLocked();
1527
1528 // Enqueue a command to run outside the lock to tell the policy that the configuration changed.
Prabir Pradhancef936d2021-07-21 16:17:52 +00001529 auto command = [this, eventTime = entry.eventTime]() REQUIRES(mLock) {
1530 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00001531 mPolicy.notifyConfigurationChanged(eventTime);
Prabir Pradhancef936d2021-07-21 16:17:52 +00001532 };
1533 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001534 return true;
1535}
1536
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001537bool InputDispatcher::dispatchDeviceResetLocked(nsecs_t currentTime,
1538 const DeviceResetEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001539 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1540 ALOGD("dispatchDeviceReset - eventTime=%" PRId64 ", deviceId=%d", entry.eventTime,
1541 entry.deviceId);
1542 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001543
liushenxiang42232912021-05-21 20:24:09 +08001544 // Reset key repeating in case a keyboard device was disabled or enabled.
1545 if (mKeyRepeatState.lastKeyEntry && mKeyRepeatState.lastKeyEntry->deviceId == entry.deviceId) {
1546 resetKeyRepeatLocked();
1547 }
1548
Michael Wrightfb04fd52022-11-24 22:31:11 +00001549 CancelationOptions options(CancelationOptions::Mode::CANCEL_ALL_EVENTS, "device was reset");
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001550 options.deviceId = entry.deviceId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001551 synthesizeCancelationEventsForAllConnectionsLocked(options);
Siarhei Vishniakou0686f0c2023-05-02 11:56:15 -07001552
1553 // Remove all active pointers from this device
1554 for (auto& [_, touchState] : mTouchStatesByDisplay) {
1555 touchState.removeAllPointersForDevice(entry.deviceId);
1556 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001557 return true;
1558}
1559
Vishnu Nairad321cd2020-08-20 16:40:21 -07001560void InputDispatcher::enqueueFocusEventLocked(const sp<IBinder>& windowToken, bool hasFocus,
Vishnu Nairc519ff72021-01-21 08:23:08 -08001561 const std::string& reason) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001562 if (mPendingEvent != nullptr) {
1563 // Move the pending event to the front of the queue. This will give the chance
1564 // for the pending event to get dispatched to the newly focused window
1565 mInboundQueue.push_front(mPendingEvent);
1566 mPendingEvent = nullptr;
1567 }
1568
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001569 std::unique_ptr<FocusEntry> focusEntry =
1570 std::make_unique<FocusEntry>(mIdGenerator.nextId(), now(), windowToken, hasFocus,
1571 reason);
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001572
1573 // This event should go to the front of the queue, but behind all other focus events
1574 // Find the last focus event, and insert right after it
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001575 std::deque<std::shared_ptr<EventEntry>>::reverse_iterator it =
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001576 std::find_if(mInboundQueue.rbegin(), mInboundQueue.rend(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001577 [](const std::shared_ptr<EventEntry>& event) {
1578 return event->type == EventEntry::Type::FOCUS;
1579 });
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001580
1581 // Maintain the order of focus events. Insert the entry after all other focus events.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001582 mInboundQueue.insert(it.base(), std::move(focusEntry));
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001583}
1584
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001585void InputDispatcher::dispatchFocusLocked(nsecs_t currentTime, std::shared_ptr<FocusEntry> entry) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05001586 std::shared_ptr<InputChannel> channel = getInputChannelLocked(entry->connectionToken);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001587 if (channel == nullptr) {
1588 return; // Window has gone away
1589 }
1590 InputTarget target;
1591 target.inputChannel = channel;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08001592 target.flags = InputTarget::Flags::DISPATCH_AS_IS;
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001593 entry->dispatchInProgress = true;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00001594 std::string message = std::string("Focus ") + (entry->hasFocus ? "entering " : "leaving ") +
1595 channel->getName();
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07001596 std::string reason = std::string("reason=").append(entry->reason);
1597 android_log_event_list(LOGTAG_INPUT_FOCUS) << message << reason << LOG_ID_EVENTS;
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001598 dispatchEventLocked(currentTime, entry, {target});
1599}
1600
Prabir Pradhan99987712020-11-10 18:43:05 -08001601void InputDispatcher::dispatchPointerCaptureChangedLocked(
1602 nsecs_t currentTime, const std::shared_ptr<PointerCaptureChangedEntry>& entry,
1603 DropReason& dropReason) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001604 dropReason = DropReason::NOT_DROPPED;
1605
Prabir Pradhan99987712020-11-10 18:43:05 -08001606 const bool haveWindowWithPointerCapture = mWindowTokenWithPointerCapture != nullptr;
Prabir Pradhan99987712020-11-10 18:43:05 -08001607 sp<IBinder> token;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001608
1609 if (entry->pointerCaptureRequest.enable) {
1610 // Enable Pointer Capture.
1611 if (haveWindowWithPointerCapture &&
1612 (entry->pointerCaptureRequest == mCurrentPointerCaptureRequest)) {
Prabir Pradhan7092e262022-05-03 16:51:09 +00001613 // This can happen if pointer capture is disabled and re-enabled before we notify the
1614 // app of the state change, so there is no need to notify the app.
1615 ALOGI("Skipping dispatch of Pointer Capture being enabled: no state change.");
1616 return;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001617 }
1618 if (!mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08001619 // This can happen if a window requests capture and immediately releases capture.
1620 ALOGW("No window requested Pointer Capture.");
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001621 dropReason = DropReason::NO_POINTER_CAPTURE;
Prabir Pradhan99987712020-11-10 18:43:05 -08001622 return;
1623 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001624 if (entry->pointerCaptureRequest.seq != mCurrentPointerCaptureRequest.seq) {
1625 ALOGI("Skipping dispatch of Pointer Capture being enabled: sequence number mismatch.");
1626 return;
1627 }
1628
Vishnu Nairc519ff72021-01-21 08:23:08 -08001629 token = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Prabir Pradhan99987712020-11-10 18:43:05 -08001630 LOG_ALWAYS_FATAL_IF(!token, "Cannot find focused window for Pointer Capture.");
1631 mWindowTokenWithPointerCapture = token;
1632 } else {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001633 // Disable Pointer Capture.
1634 // We do not check if the sequence number matches for requests to disable Pointer Capture
1635 // for two reasons:
1636 // 1. Pointer Capture can be disabled by a focus change, which means we can get two entries
1637 // to disable capture with the same sequence number: one generated by
1638 // disablePointerCaptureForcedLocked() and another as an acknowledgement of Pointer
1639 // Capture being disabled in InputReader.
1640 // 2. We respect any request to disable Pointer Capture generated by InputReader, since the
1641 // actual Pointer Capture state that affects events being generated by input devices is
1642 // in InputReader.
1643 if (!haveWindowWithPointerCapture) {
1644 // Pointer capture was already forcefully disabled because of focus change.
1645 dropReason = DropReason::NOT_DROPPED;
1646 return;
1647 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001648 token = mWindowTokenWithPointerCapture;
1649 mWindowTokenWithPointerCapture = nullptr;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001650 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan7d030382020-12-21 07:58:35 -08001651 setPointerCaptureLocked(false);
1652 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001653 }
1654
1655 auto channel = getInputChannelLocked(token);
1656 if (channel == nullptr) {
1657 // Window has gone away, clean up Pointer Capture state.
1658 mWindowTokenWithPointerCapture = nullptr;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001659 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan7d030382020-12-21 07:58:35 -08001660 setPointerCaptureLocked(false);
1661 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001662 return;
1663 }
1664 InputTarget target;
1665 target.inputChannel = channel;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08001666 target.flags = InputTarget::Flags::DISPATCH_AS_IS;
Prabir Pradhan99987712020-11-10 18:43:05 -08001667 entry->dispatchInProgress = true;
1668 dispatchEventLocked(currentTime, entry, {target});
1669
1670 dropReason = DropReason::NOT_DROPPED;
1671}
1672
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001673void InputDispatcher::dispatchTouchModeChangeLocked(nsecs_t currentTime,
1674 const std::shared_ptr<TouchModeEntry>& entry) {
1675 const std::vector<sp<WindowInfoHandle>>& windowHandles =
Antonio Kantek15beb512022-06-13 22:35:41 +00001676 getWindowHandlesLocked(entry->displayId);
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001677 if (windowHandles.empty()) {
1678 return;
1679 }
1680 const std::vector<InputTarget> inputTargets =
1681 getInputTargetsFromWindowHandlesLocked(windowHandles);
1682 if (inputTargets.empty()) {
1683 return;
1684 }
1685 entry->dispatchInProgress = true;
1686 dispatchEventLocked(currentTime, entry, inputTargets);
1687}
1688
1689std::vector<InputTarget> InputDispatcher::getInputTargetsFromWindowHandlesLocked(
1690 const std::vector<sp<WindowInfoHandle>>& windowHandles) const {
1691 std::vector<InputTarget> inputTargets;
1692 for (const sp<WindowInfoHandle>& handle : windowHandles) {
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001693 const sp<IBinder>& token = handle->getToken();
1694 if (token == nullptr) {
1695 continue;
1696 }
1697 std::shared_ptr<InputChannel> channel = getInputChannelLocked(token);
1698 if (channel == nullptr) {
1699 continue; // Window has gone away
1700 }
1701 InputTarget target;
1702 target.inputChannel = channel;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08001703 target.flags = InputTarget::Flags::DISPATCH_AS_IS;
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001704 inputTargets.push_back(target);
1705 }
1706 return inputTargets;
1707}
1708
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001709bool InputDispatcher::dispatchKeyLocked(nsecs_t currentTime, std::shared_ptr<KeyEntry> entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001710 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001711 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001712 if (!entry->dispatchInProgress) {
1713 if (entry->repeatCount == 0 && entry->action == AKEY_EVENT_ACTION_DOWN &&
1714 (entry->policyFlags & POLICY_FLAG_TRUSTED) &&
1715 (!(entry->policyFlags & POLICY_FLAG_DISABLE_KEY_REPEAT))) {
1716 if (mKeyRepeatState.lastKeyEntry &&
Chris Ye2ad95392020-09-01 13:44:44 -07001717 mKeyRepeatState.lastKeyEntry->keyCode == entry->keyCode &&
Michael Wrightd02c5b62014-02-10 15:10:22 -08001718 // We have seen two identical key downs in a row which indicates that the device
1719 // driver is automatically generating key repeats itself. We take note of the
1720 // repeat here, but we disable our own next key repeat timer since it is clear that
1721 // we will not need to synthesize key repeats ourselves.
Chris Ye2ad95392020-09-01 13:44:44 -07001722 mKeyRepeatState.lastKeyEntry->deviceId == entry->deviceId) {
1723 // Make sure we don't get key down from a different device. If a different
1724 // device Id has same key pressed down, the new device Id will replace the
1725 // current one to hold the key repeat with repeat count reset.
1726 // In the future when got a KEY_UP on the device id, drop it and do not
1727 // stop the key repeat on current device.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001728 entry->repeatCount = mKeyRepeatState.lastKeyEntry->repeatCount + 1;
1729 resetKeyRepeatLocked();
Colin Cross5b799302022-10-18 21:52:41 -07001730 mKeyRepeatState.nextRepeatTime = LLONG_MAX; // don't generate repeats ourselves
Michael Wrightd02c5b62014-02-10 15:10:22 -08001731 } else {
1732 // Not a repeat. Save key down state in case we do see a repeat later.
1733 resetKeyRepeatLocked();
1734 mKeyRepeatState.nextRepeatTime = entry->eventTime + mConfig.keyRepeatTimeout;
1735 }
1736 mKeyRepeatState.lastKeyEntry = entry;
Chris Ye2ad95392020-09-01 13:44:44 -07001737 } else if (entry->action == AKEY_EVENT_ACTION_UP && mKeyRepeatState.lastKeyEntry &&
1738 mKeyRepeatState.lastKeyEntry->deviceId != entry->deviceId) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001739 // The key on device 'deviceId' is still down, do not stop key repeat
Prabir Pradhan65613802023-02-22 23:36:58 +00001740 if (debugInboundEventDetails()) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001741 ALOGD("deviceId=%d got KEY_UP as stale", entry->deviceId);
1742 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001743 } else if (!entry->syntheticRepeat) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001744 resetKeyRepeatLocked();
1745 }
1746
1747 if (entry->repeatCount == 1) {
1748 entry->flags |= AKEY_EVENT_FLAG_LONG_PRESS;
1749 } else {
1750 entry->flags &= ~AKEY_EVENT_FLAG_LONG_PRESS;
1751 }
1752
1753 entry->dispatchInProgress = true;
1754
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001755 logOutboundKeyDetails("dispatchKey - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001756 }
1757
1758 // Handle case where the policy asked us to try again later last time.
Michael Wright5caf55a2022-11-24 22:31:42 +00001759 if (entry->interceptKeyResult == KeyEntry::InterceptKeyResult::TRY_AGAIN_LATER) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001760 if (currentTime < entry->interceptKeyWakeupTime) {
1761 if (entry->interceptKeyWakeupTime < *nextWakeupTime) {
1762 *nextWakeupTime = entry->interceptKeyWakeupTime;
1763 }
1764 return false; // wait until next wakeup
1765 }
Michael Wright5caf55a2022-11-24 22:31:42 +00001766 entry->interceptKeyResult = KeyEntry::InterceptKeyResult::UNKNOWN;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001767 entry->interceptKeyWakeupTime = 0;
1768 }
1769
1770 // Give the policy a chance to intercept the key.
Michael Wright5caf55a2022-11-24 22:31:42 +00001771 if (entry->interceptKeyResult == KeyEntry::InterceptKeyResult::UNKNOWN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001772 if (entry->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07001773 sp<IBinder> focusedWindowToken =
Vishnu Nairc519ff72021-01-21 08:23:08 -08001774 mFocusResolver.getFocusedWindowToken(getTargetDisplayId(*entry));
Prabir Pradhancef936d2021-07-21 16:17:52 +00001775
1776 auto command = [this, focusedWindowToken, entry]() REQUIRES(mLock) {
1777 doInterceptKeyBeforeDispatchingCommand(focusedWindowToken, *entry);
1778 };
1779 postCommandLocked(std::move(command));
Josep del Riob3981622023-04-18 15:49:45 +00001780 // Poke user activity for keys not passed to user
1781 pokeUserActivityLocked(*entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001782 return false; // wait for the command to run
1783 } else {
Michael Wright5caf55a2022-11-24 22:31:42 +00001784 entry->interceptKeyResult = KeyEntry::InterceptKeyResult::CONTINUE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001785 }
Michael Wright5caf55a2022-11-24 22:31:42 +00001786 } else if (entry->interceptKeyResult == KeyEntry::InterceptKeyResult::SKIP) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001787 if (*dropReason == DropReason::NOT_DROPPED) {
1788 *dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001789 }
1790 }
1791
1792 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001793 if (*dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001794 setInjectionResult(*entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001795 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
1796 : InputEventInjectionResult::FAILED);
Garfield Tan6a5a14e2020-01-28 13:24:04 -08001797 mReporter->reportDroppedKey(entry->id);
Josep del Riob3981622023-04-18 15:49:45 +00001798 // Poke user activity for undispatched keys
1799 pokeUserActivityLocked(*entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001800 return true;
1801 }
1802
1803 // Identify targets.
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001804 InputEventInjectionResult injectionResult;
1805 sp<WindowInfoHandle> focusedWindow =
1806 findFocusedWindowTargetLocked(currentTime, *entry, nextWakeupTime,
1807 /*byref*/ injectionResult);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001808 if (injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001809 return false;
1810 }
1811
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001812 setInjectionResult(*entry, injectionResult);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001813 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001814 return true;
1815 }
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001816 LOG_ALWAYS_FATAL_IF(focusedWindow == nullptr);
1817
1818 std::vector<InputTarget> inputTargets;
1819 addWindowTargetLocked(focusedWindow,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08001820 InputTarget::Flags::FOREGROUND | InputTarget::Flags::DISPATCH_AS_IS,
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08001821 /*pointerIds=*/{}, getDownTime(*entry), inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001822
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001823 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001824 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001825
1826 // Dispatch the key.
1827 dispatchEventLocked(currentTime, entry, inputTargets);
1828 return true;
1829}
1830
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001831void InputDispatcher::logOutboundKeyDetails(const char* prefix, const KeyEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001832 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1833 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32 ", "
1834 "policyFlags=0x%x, action=0x%x, flags=0x%x, keyCode=0x%x, scanCode=0x%x, "
1835 "metaState=0x%x, repeatCount=%d, downTime=%" PRId64,
1836 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId,
1837 entry.policyFlags, entry.action, entry.flags, entry.keyCode, entry.scanCode,
1838 entry.metaState, entry.repeatCount, entry.downTime);
1839 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001840}
1841
Prabir Pradhancef936d2021-07-21 16:17:52 +00001842void InputDispatcher::dispatchSensorLocked(nsecs_t currentTime,
1843 const std::shared_ptr<SensorEntry>& entry,
Chris Yef59a2f42020-10-16 12:55:26 -07001844 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001845 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1846 ALOGD("notifySensorEvent eventTime=%" PRId64 ", hwTimestamp=%" PRId64 ", deviceId=%d, "
1847 "source=0x%x, sensorType=%s",
1848 entry->eventTime, entry->hwTimestamp, entry->deviceId, entry->source,
Dominik Laskowski75788452021-02-09 18:51:25 -08001849 ftl::enum_string(entry->sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001850 }
Prabir Pradhancef936d2021-07-21 16:17:52 +00001851 auto command = [this, entry]() REQUIRES(mLock) {
1852 scoped_unlock unlock(mLock);
1853
1854 if (entry->accuracyChanged) {
Prabir Pradhana41d2442023-04-20 21:30:40 +00001855 mPolicy.notifySensorAccuracy(entry->deviceId, entry->sensorType, entry->accuracy);
Prabir Pradhancef936d2021-07-21 16:17:52 +00001856 }
Prabir Pradhana41d2442023-04-20 21:30:40 +00001857 mPolicy.notifySensorEvent(entry->deviceId, entry->sensorType, entry->accuracy,
1858 entry->hwTimestamp, entry->values);
Prabir Pradhancef936d2021-07-21 16:17:52 +00001859 };
1860 postCommandLocked(std::move(command));
Chris Yef59a2f42020-10-16 12:55:26 -07001861}
1862
1863bool InputDispatcher::flushSensor(int deviceId, InputDeviceSensorType sensorType) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001864 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1865 ALOGD("flushSensor deviceId=%d, sensorType=%s", deviceId,
Dominik Laskowski75788452021-02-09 18:51:25 -08001866 ftl::enum_string(sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001867 }
Chris Yef59a2f42020-10-16 12:55:26 -07001868 { // acquire lock
1869 std::scoped_lock _l(mLock);
1870
1871 for (auto it = mInboundQueue.begin(); it != mInboundQueue.end(); it++) {
1872 std::shared_ptr<EventEntry> entry = *it;
1873 if (entry->type == EventEntry::Type::SENSOR) {
1874 it = mInboundQueue.erase(it);
1875 releaseInboundEventLocked(entry);
1876 }
1877 }
1878 }
1879 return true;
1880}
1881
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001882bool InputDispatcher::dispatchMotionLocked(nsecs_t currentTime, std::shared_ptr<MotionEntry> entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001883 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001884 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001885 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001886 if (!entry->dispatchInProgress) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001887 entry->dispatchInProgress = true;
1888
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001889 logOutboundMotionDetails("dispatchMotion - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001890 }
1891
1892 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001893 if (*dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001894 setInjectionResult(*entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001895 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
1896 : InputEventInjectionResult::FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001897 return true;
1898 }
1899
Prabir Pradhanaa561d12021-09-24 06:57:33 -07001900 const bool isPointerEvent = isFromSource(entry->source, AINPUT_SOURCE_CLASS_POINTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001901
1902 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001903 std::vector<InputTarget> inputTargets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001904
1905 bool conflictingPointerActions = false;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001906 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001907 if (isPointerEvent) {
1908 // Pointer event. (eg. touchscreen)
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00001909
1910 if (mDragState &&
1911 (entry->action & AMOTION_EVENT_ACTION_MASK) == AMOTION_EVENT_ACTION_POINTER_DOWN) {
1912 // If drag and drop ongoing and pointer down occur: pilfer drag window pointers
1913 pilferPointersLocked(mDragState->dragWindow->getToken());
1914 }
1915
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08001916 inputTargets =
Siarhei Vishniakou4fe57392022-10-25 13:44:30 -07001917 findTouchedWindowTargetsLocked(currentTime, *entry, &conflictingPointerActions,
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001918 /*byref*/ injectionResult);
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08001919 LOG_ALWAYS_FATAL_IF(injectionResult != InputEventInjectionResult::SUCCEEDED &&
1920 !inputTargets.empty());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001921 } else {
1922 // Non touch event. (eg. trackball)
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001923 sp<WindowInfoHandle> focusedWindow =
1924 findFocusedWindowTargetLocked(currentTime, *entry, nextWakeupTime, injectionResult);
1925 if (injectionResult == InputEventInjectionResult::SUCCEEDED) {
1926 LOG_ALWAYS_FATAL_IF(focusedWindow == nullptr);
1927 addWindowTargetLocked(focusedWindow,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08001928 InputTarget::Flags::FOREGROUND |
1929 InputTarget::Flags::DISPATCH_AS_IS,
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08001930 /*pointerIds=*/{}, getDownTime(*entry), inputTargets);
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001931 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001932 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001933 if (injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001934 return false;
1935 }
1936
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001937 setInjectionResult(*entry, injectionResult);
Prabir Pradhan5735a322022-04-11 17:23:34 +00001938 if (injectionResult == InputEventInjectionResult::TARGET_MISMATCH) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001939 return true;
1940 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001941 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001942 CancelationOptions::Mode mode(
1943 isPointerEvent ? CancelationOptions::Mode::CANCEL_POINTER_EVENTS
1944 : CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS);
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001945 CancelationOptions options(mode, "input event injection failed");
1946 synthesizeCancelationEventsForMonitorsLocked(options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001947 return true;
1948 }
1949
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001950 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001951 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001952
1953 // Dispatch the motion.
1954 if (conflictingPointerActions) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001955 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001956 "conflicting pointer actions");
Michael Wrightd02c5b62014-02-10 15:10:22 -08001957 synthesizeCancelationEventsForAllConnectionsLocked(options);
1958 }
1959 dispatchEventLocked(currentTime, entry, inputTargets);
1960 return true;
1961}
1962
chaviw98318de2021-05-19 16:45:23 -05001963void InputDispatcher::enqueueDragEventLocked(const sp<WindowInfoHandle>& windowHandle,
Arthur Hung54745652022-04-20 07:17:41 +00001964 bool isExiting, const int32_t rawX,
1965 const int32_t rawY) {
1966 const vec2 xy = windowHandle->getInfo()->transform.transform(vec2(rawX, rawY));
arthurhungb89ccb02020-12-30 16:19:01 +08001967 std::unique_ptr<DragEntry> dragEntry =
Arthur Hung54745652022-04-20 07:17:41 +00001968 std::make_unique<DragEntry>(mIdGenerator.nextId(), now(), windowHandle->getToken(),
1969 isExiting, xy.x, xy.y);
arthurhungb89ccb02020-12-30 16:19:01 +08001970
1971 enqueueInboundEventLocked(std::move(dragEntry));
1972}
1973
1974void InputDispatcher::dispatchDragLocked(nsecs_t currentTime, std::shared_ptr<DragEntry> entry) {
1975 std::shared_ptr<InputChannel> channel = getInputChannelLocked(entry->connectionToken);
1976 if (channel == nullptr) {
1977 return; // Window has gone away
1978 }
1979 InputTarget target;
1980 target.inputChannel = channel;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08001981 target.flags = InputTarget::Flags::DISPATCH_AS_IS;
arthurhungb89ccb02020-12-30 16:19:01 +08001982 entry->dispatchInProgress = true;
1983 dispatchEventLocked(currentTime, entry, {target});
1984}
1985
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001986void InputDispatcher::logOutboundMotionDetails(const char* prefix, const MotionEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001987 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -08001988 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=%s, displayId=%" PRId32
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001989 ", policyFlags=0x%x, "
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001990 "action=%s, actionButton=0x%x, flags=0x%x, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001991 "metaState=0x%x, buttonState=0x%x,"
1992 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%" PRId64,
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -08001993 prefix, entry.eventTime, entry.deviceId,
1994 inputEventSourceToString(entry.source).c_str(), entry.displayId, entry.policyFlags,
1995 MotionEvent::actionToString(entry.action).c_str(), entry.actionButton, entry.flags,
1996 entry.metaState, entry.buttonState, entry.edgeFlags, entry.xPrecision,
1997 entry.yPrecision, entry.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001998
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001999 for (uint32_t i = 0; i < entry.pointerCount; i++) {
Siarhei Vishniakou09a8fe42022-07-21 17:27:03 -07002000 ALOGD(" Pointer %d: id=%d, toolType=%s, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002001 "x=%f, y=%f, pressure=%f, size=%f, "
2002 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
2003 "orientation=%f",
Siarhei Vishniakou09a8fe42022-07-21 17:27:03 -07002004 i, entry.pointerProperties[i].id,
2005 ftl::enum_string(entry.pointerProperties[i].toolType).c_str(),
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002006 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
2007 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
2008 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
2009 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
2010 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
2011 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
2012 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
2013 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
2014 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
2015 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002016 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002017}
2018
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002019void InputDispatcher::dispatchEventLocked(nsecs_t currentTime,
2020 std::shared_ptr<EventEntry> eventEntry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002021 const std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002022 ATRACE_CALL();
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002023 if (DEBUG_DISPATCH_CYCLE) {
2024 ALOGD("dispatchEventToCurrentInputTargets");
2025 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002026
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00002027 processInteractionsLocked(*eventEntry, inputTargets);
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00002028
Michael Wrightd02c5b62014-02-10 15:10:22 -08002029 ALOG_ASSERT(eventEntry->dispatchInProgress); // should already have been set to true
2030
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002031 pokeUserActivityLocked(*eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002032
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002033 for (const InputTarget& inputTarget : inputTargets) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07002034 std::shared_ptr<Connection> connection =
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07002035 getConnectionLocked(inputTarget.inputChannel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07002036 if (connection != nullptr) {
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002037 prepareDispatchCycleLocked(currentTime, connection, eventEntry, inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002038 } else {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002039 if (DEBUG_FOCUS) {
2040 ALOGD("Dropping event delivery to target with channel '%s' because it "
2041 "is no longer registered with the input dispatcher.",
2042 inputTarget.inputChannel->getName().c_str());
2043 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002044 }
2045 }
2046}
2047
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07002048void InputDispatcher::cancelEventsForAnrLocked(const std::shared_ptr<Connection>& connection) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002049 // We will not be breaking any connections here, even if the policy wants us to abort dispatch.
2050 // If the policy decides to close the app, we will get a channel removal event via
2051 // unregisterInputChannel, and will clean up the connection that way. We are already not
2052 // sending new pointers to the connection when it blocked, but focused events will continue to
2053 // pile up.
2054 ALOGW("Canceling events for %s because it is unresponsive",
2055 connection->inputChannel->getName().c_str());
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08002056 if (connection->status == Connection::Status::NORMAL) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00002057 CancelationOptions options(CancelationOptions::Mode::CANCEL_ALL_EVENTS,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002058 "application not responding");
2059 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002060 }
2061}
2062
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002063void InputDispatcher::resetNoFocusedWindowTimeoutLocked() {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002064 if (DEBUG_FOCUS) {
2065 ALOGD("Resetting ANR timeouts.");
2066 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002067
2068 // Reset input target wait timeout.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002069 mNoFocusedWindowTimeoutTime = std::nullopt;
Chris Yea209fde2020-07-22 13:54:51 -07002070 mAwaitedFocusedApplication.reset();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002071}
2072
Tiger Huang721e26f2018-07-24 22:26:19 +08002073/**
2074 * Get the display id that the given event should go to. If this event specifies a valid display id,
2075 * then it should be dispatched to that display. Otherwise, the event goes to the focused display.
2076 * Focused display is the display that the user most recently interacted with.
2077 */
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002078int32_t InputDispatcher::getTargetDisplayId(const EventEntry& entry) {
Tiger Huang721e26f2018-07-24 22:26:19 +08002079 int32_t displayId;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002080 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002081 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002082 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
2083 displayId = keyEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002084 break;
2085 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002086 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002087 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
2088 displayId = motionEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002089 break;
2090 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00002091 case EventEntry::Type::TOUCH_MODE_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08002092 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002093 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002094 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07002095 case EventEntry::Type::DEVICE_RESET:
arthurhungb89ccb02020-12-30 16:19:01 +08002096 case EventEntry::Type::SENSOR:
2097 case EventEntry::Type::DRAG: {
Dominik Laskowski75788452021-02-09 18:51:25 -08002098 ALOGE("%s events do not have a target display", ftl::enum_string(entry.type).c_str());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002099 return ADISPLAY_ID_NONE;
2100 }
Tiger Huang721e26f2018-07-24 22:26:19 +08002101 }
2102 return displayId == ADISPLAY_ID_NONE ? mFocusedDisplayId : displayId;
2103}
2104
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002105bool InputDispatcher::shouldWaitToSendKeyLocked(nsecs_t currentTime,
2106 const char* focusedWindowName) {
2107 if (mAnrTracker.empty()) {
2108 // already processed all events that we waited for
2109 mKeyIsWaitingForEventsTimeout = std::nullopt;
2110 return false;
2111 }
2112
2113 if (!mKeyIsWaitingForEventsTimeout.has_value()) {
2114 // Start the timer
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00002115 // Wait to send key because there are unprocessed events that may cause focus to change
Siarhei Vishniakou70622952020-07-30 11:17:23 -05002116 mKeyIsWaitingForEventsTimeout = currentTime +
2117 std::chrono::duration_cast<std::chrono::nanoseconds>(KEY_WAITING_FOR_EVENTS_TIMEOUT)
2118 .count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002119 return true;
2120 }
2121
2122 // We still have pending events, and already started the timer
2123 if (currentTime < *mKeyIsWaitingForEventsTimeout) {
2124 return true; // Still waiting
2125 }
2126
2127 // Waited too long, and some connection still hasn't processed all motions
2128 // Just send the key to the focused window
2129 ALOGW("Dispatching key to %s even though there are other unprocessed events",
2130 focusedWindowName);
2131 mKeyIsWaitingForEventsTimeout = std::nullopt;
2132 return false;
2133}
2134
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002135sp<WindowInfoHandle> InputDispatcher::findFocusedWindowTargetLocked(
2136 nsecs_t currentTime, const EventEntry& entry, nsecs_t* nextWakeupTime,
2137 InputEventInjectionResult& outInjectionResult) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002138 std::string reason;
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002139 outInjectionResult = InputEventInjectionResult::FAILED; // Default result
Michael Wrightd02c5b62014-02-10 15:10:22 -08002140
Tiger Huang721e26f2018-07-24 22:26:19 +08002141 int32_t displayId = getTargetDisplayId(entry);
chaviw98318de2021-05-19 16:45:23 -05002142 sp<WindowInfoHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Chris Yea209fde2020-07-22 13:54:51 -07002143 std::shared_ptr<InputApplicationHandle> focusedApplicationHandle =
Tiger Huang721e26f2018-07-24 22:26:19 +08002144 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
2145
Michael Wrightd02c5b62014-02-10 15:10:22 -08002146 // If there is no currently focused window and no focused application
2147 // then drop the event.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002148 if (focusedWindowHandle == nullptr && focusedApplicationHandle == nullptr) {
2149 ALOGI("Dropping %s event because there is no focused window or focused application in "
2150 "display %" PRId32 ".",
Dominik Laskowski75788452021-02-09 18:51:25 -08002151 ftl::enum_string(entry.type).c_str(), displayId);
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002152 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002153 }
2154
Vishnu Nair062a8672021-09-03 16:07:44 -07002155 // Drop key events if requested by input feature
2156 if (focusedWindowHandle != nullptr && shouldDropInput(entry, focusedWindowHandle)) {
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002157 return nullptr;
Vishnu Nair062a8672021-09-03 16:07:44 -07002158 }
2159
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002160 // Compatibility behavior: raise ANR if there is a focused application, but no focused window.
2161 // Only start counting when we have a focused event to dispatch. The ANR is canceled if we
2162 // start interacting with another application via touch (app switch). This code can be removed
2163 // if the "no focused window ANR" is moved to the policy. Input doesn't know whether
2164 // an app is expected to have a focused window.
2165 if (focusedWindowHandle == nullptr && focusedApplicationHandle != nullptr) {
2166 if (!mNoFocusedWindowTimeoutTime.has_value()) {
2167 // We just discovered that there's no focused window. Start the ANR timer
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05002168 std::chrono::nanoseconds timeout = focusedApplicationHandle->getDispatchingTimeout(
2169 DEFAULT_INPUT_DISPATCHING_TIMEOUT);
2170 mNoFocusedWindowTimeoutTime = currentTime + timeout.count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002171 mAwaitedFocusedApplication = focusedApplicationHandle;
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05002172 mAwaitedApplicationDisplayId = displayId;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002173 ALOGW("Waiting because no window has focus but %s may eventually add a "
2174 "window when it finishes starting up. Will wait for %" PRId64 "ms",
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05002175 mAwaitedFocusedApplication->getName().c_str(), millis(timeout));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002176 *nextWakeupTime = *mNoFocusedWindowTimeoutTime;
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002177 outInjectionResult = InputEventInjectionResult::PENDING;
2178 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002179 } else if (currentTime > *mNoFocusedWindowTimeoutTime) {
2180 // Already raised ANR. Drop the event
2181 ALOGE("Dropping %s event because there is no focused window",
Dominik Laskowski75788452021-02-09 18:51:25 -08002182 ftl::enum_string(entry.type).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002183 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002184 } else {
2185 // Still waiting for the focused window
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002186 outInjectionResult = InputEventInjectionResult::PENDING;
2187 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002188 }
2189 }
2190
2191 // we have a valid, non-null focused window
2192 resetNoFocusedWindowTimeoutLocked();
2193
Prabir Pradhan5735a322022-04-11 17:23:34 +00002194 // Verify targeted injection.
2195 if (const auto err = verifyTargetedInjection(focusedWindowHandle, entry); err) {
2196 ALOGW("Dropping injected event: %s", (*err).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002197 outInjectionResult = InputEventInjectionResult::TARGET_MISMATCH;
2198 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002199 }
2200
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002201 if (focusedWindowHandle->getInfo()->inputConfig.test(
2202 WindowInfo::InputConfig::PAUSE_DISPATCHING)) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002203 ALOGI("Waiting because %s is paused", focusedWindowHandle->getName().c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002204 outInjectionResult = InputEventInjectionResult::PENDING;
2205 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002206 }
2207
2208 // If the event is a key event, then we must wait for all previous events to
2209 // complete before delivering it because previous events may have the
2210 // side-effect of transferring focus to a different window and we want to
2211 // ensure that the following keys are sent to the new window.
2212 //
2213 // Suppose the user touches a button in a window then immediately presses "A".
2214 // If the button causes a pop-up window to appear then we want to ensure that
2215 // the "A" key is delivered to the new pop-up window. This is because users
2216 // often anticipate pending UI changes when typing on a keyboard.
2217 // To obtain this behavior, we must serialize key events with respect to all
2218 // prior input events.
2219 if (entry.type == EventEntry::Type::KEY) {
2220 if (shouldWaitToSendKeyLocked(currentTime, focusedWindowHandle->getName().c_str())) {
2221 *nextWakeupTime = *mKeyIsWaitingForEventsTimeout;
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002222 outInjectionResult = InputEventInjectionResult::PENDING;
2223 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002224 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002225 }
2226
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002227 outInjectionResult = InputEventInjectionResult::SUCCEEDED;
2228 return focusedWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002229}
2230
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002231/**
2232 * Given a list of monitors, remove the ones we cannot find a connection for, and the ones
2233 * that are currently unresponsive.
2234 */
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002235std::vector<Monitor> InputDispatcher::selectResponsiveMonitorsLocked(
2236 const std::vector<Monitor>& monitors) const {
2237 std::vector<Monitor> responsiveMonitors;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002238 std::copy_if(monitors.begin(), monitors.end(), std::back_inserter(responsiveMonitors),
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002239 [this](const Monitor& monitor) REQUIRES(mLock) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07002240 std::shared_ptr<Connection> connection =
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002241 getConnectionLocked(monitor.inputChannel->getConnectionToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002242 if (connection == nullptr) {
2243 ALOGE("Could not find connection for monitor %s",
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002244 monitor.inputChannel->getName().c_str());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002245 return false;
2246 }
2247 if (!connection->responsive) {
2248 ALOGW("Unresponsive monitor %s will not get the new gesture",
2249 connection->inputChannel->getName().c_str());
2250 return false;
2251 }
2252 return true;
2253 });
2254 return responsiveMonitors;
2255}
2256
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002257std::vector<InputTarget> InputDispatcher::findTouchedWindowTargetsLocked(
Siarhei Vishniakou4fe57392022-10-25 13:44:30 -07002258 nsecs_t currentTime, const MotionEntry& entry, bool* outConflictingPointerActions,
2259 InputEventInjectionResult& outInjectionResult) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002260 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002261
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002262 std::vector<InputTarget> targets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002263 // For security reasons, we defer updating the touch state until we are sure that
2264 // event injection will be allowed.
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002265 const int32_t displayId = entry.displayId;
2266 const int32_t action = entry.action;
Siarhei Vishniakoubf880522023-05-01 11:03:22 -07002267 const int32_t maskedAction = MotionEvent::getActionMasked(action);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002268
2269 // Update the touch state as needed based on the properties of the touch event.
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002270 outInjectionResult = InputEventInjectionResult::PENDING;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002271
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002272 // Copy current touch state into tempTouchState.
2273 // This state will be used to update mTouchStatesByDisplay at the end of this function.
2274 // If no state for the specified display exists, then our initial state will be empty.
Yi Kong9b14ac62018-07-17 13:48:38 -07002275 const TouchState* oldState = nullptr;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002276 TouchState tempTouchState;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002277 if (const auto it = mTouchStatesByDisplay.find(displayId); it != mTouchStatesByDisplay.end()) {
2278 oldState = &(it->second);
Prabir Pradhane680f9b2022-02-04 04:24:00 -08002279 tempTouchState = *oldState;
Jeff Brownf086ddb2014-02-11 14:28:48 -08002280 }
2281
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07002282 bool isSplit = shouldSplitTouch(tempTouchState, entry);
Siarhei Vishniakou45504fe2023-05-05 16:05:10 -07002283 bool switchedDevice = false;
2284 if (oldState != nullptr) {
2285 std::set<int32_t> oldActiveDevices = oldState->getActiveDeviceIds();
2286 const bool anotherDeviceIsActive =
2287 oldActiveDevices.count(entry.deviceId) == 0 && !oldActiveDevices.empty();
2288 switchedDevice |= anotherDeviceIsActive;
Siarhei Vishniakou45504fe2023-05-05 16:05:10 -07002289 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002290
2291 const bool isHoverAction = (maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE ||
2292 maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2293 maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT);
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002294 // A DOWN could be generated from POINTER_DOWN if the initial pointers did not land into any
2295 // touchable windows.
2296 const bool wasDown = oldState != nullptr && oldState->isDown();
2297 const bool isDown = (maskedAction == AMOTION_EVENT_ACTION_DOWN) ||
2298 (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN && !wasDown);
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07002299 const bool newGesture = isDown || maskedAction == AMOTION_EVENT_ACTION_SCROLL ||
2300 maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2301 maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE;
Prabir Pradhanaa561d12021-09-24 06:57:33 -07002302 const bool isFromMouse = isFromSource(entry.source, AINPUT_SOURCE_MOUSE);
Siarhei Vishniakou5cee1e32022-11-29 12:35:39 -08002303
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002304 // If pointers are already down, let's finish the current gesture and ignore the new events
2305 // from another device. However, if the new event is a down event, let's cancel the current
2306 // touch and let the new one take over.
2307 if (switchedDevice && wasDown && !isDown) {
Siarhei Vishniakou45504fe2023-05-05 16:05:10 -07002308 LOG(INFO) << "Dropping event because a pointer for another device "
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002309 << " is already down in display " << displayId << ": " << entry.getDescription();
2310 // TODO(b/211379801): test multiple simultaneous input streams.
2311 outInjectionResult = InputEventInjectionResult::FAILED;
2312 return {}; // wrong device
2313 }
2314
Michael Wrightd02c5b62014-02-10 15:10:22 -08002315 if (newGesture) {
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002316 // If a new gesture is starting, clear the touch state completely.
2317 tempTouchState.reset();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002318 isSplit = false;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04002319 } else if (switchedDevice && maskedAction == AMOTION_EVENT_ACTION_MOVE) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07002320 ALOGI("Dropping move event because a pointer for a different device is already active "
2321 "in display %" PRId32,
2322 displayId);
Siarhei Vishniakou16e4fa02023-02-16 17:48:56 -08002323 // TODO(b/211379801): test multiple simultaneous input streams.
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002324 outInjectionResult = InputEventInjectionResult::FAILED;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002325 return {}; // wrong device
Michael Wrightd02c5b62014-02-10 15:10:22 -08002326 }
2327
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002328 if (isHoverAction) {
2329 // For hover actions, we will treat 'tempTouchState' as a new state, so let's erase
2330 // all of the existing hovering pointers and recompute.
2331 tempTouchState.clearHoveringPointers();
2332 }
2333
Michael Wrightd02c5b62014-02-10 15:10:22 -08002334 if (newGesture || (isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN)) {
2335 /* Case 1: New splittable pointer going down, or need target for hover or scroll. */
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07002336 const auto [x, y] = resolveTouchedPosition(entry);
Siarhei Vishniakou5b9766d2023-07-18 14:06:29 -07002337 const int32_t pointerIndex = MotionEvent::getActionIndex(action);
Siarhei Vishniakou70f3d8c2023-09-19 15:36:52 -07002338 const int32_t pointerId = entry.pointerProperties[pointerIndex].id;
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002339 // Outside targets should be added upon first dispatched DOWN event. That means, this should
2340 // be a pointer that would generate ACTION_DOWN, *and* touch should not already be down.
Prabir Pradhand65552b2021-10-07 11:23:50 -07002341 const bool isStylus = isPointerFromStylus(entry, pointerIndex);
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07002342 sp<WindowInfoHandle> newTouchedWindowHandle =
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002343 findTouchedWindowAtLocked(displayId, x, y, isStylus);
Michael Wright3dd60e22019-03-27 22:06:44 +00002344
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002345 if (isDown) {
Siarhei Vishniakou70f3d8c2023-09-19 15:36:52 -07002346 targets += findOutsideTargetsLocked(displayId, newTouchedWindowHandle, pointerId);
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002347 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002348 // Handle the case where we did not find a window.
Yi Kong9b14ac62018-07-17 13:48:38 -07002349 if (newTouchedWindowHandle == nullptr) {
Prabir Pradhan82e081e2022-12-06 09:50:09 +00002350 ALOGD("No new touched window at (%.1f, %.1f) in display %" PRId32, x, y, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002351 // Try to assign the pointer to the first foreground window we find, if there is one.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002352 newTouchedWindowHandle = tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002353 }
2354
Prabir Pradhan5735a322022-04-11 17:23:34 +00002355 // Verify targeted injection.
2356 if (const auto err = verifyTargetedInjection(newTouchedWindowHandle, entry); err) {
2357 ALOGW("Dropping injected touch event: %s", (*err).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002358 outInjectionResult = os::InputEventInjectionResult::TARGET_MISMATCH;
Prabir Pradhan5735a322022-04-11 17:23:34 +00002359 newTouchedWindowHandle = nullptr;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002360 return {};
Prabir Pradhan5735a322022-04-11 17:23:34 +00002361 }
2362
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002363 // Figure out whether splitting will be allowed for this window.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002364 if (newTouchedWindowHandle != nullptr) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002365 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
2366 // New window supports splitting, but we should never split mouse events.
2367 isSplit = !isFromMouse;
2368 } else if (isSplit) {
2369 // New window does not support splitting but we have already split events.
2370 // Ignore the new window.
Siarhei Vishniakou25537f82023-07-18 14:35:47 -07002371 LOG(INFO) << "Skipping " << newTouchedWindowHandle->getName()
2372 << " because it doesn't support split touch";
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002373 newTouchedWindowHandle = nullptr;
2374 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002375 } else {
2376 // No window is touched, so set split to true. This will allow the next pointer down to
Prabir Pradhan713bb3e2021-12-20 02:07:40 -08002377 // be delivered to a new window which supports split touch. Pointers from a mouse device
2378 // should never be split.
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07002379 isSplit = !isFromMouse;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002380 }
2381
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002382 std::vector<sp<WindowInfoHandle>> newTouchedWindows =
Prabir Pradhand65552b2021-10-07 11:23:50 -07002383 findTouchedSpyWindowsAtLocked(displayId, x, y, isStylus);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002384 if (newTouchedWindowHandle != nullptr) {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002385 // Process the foreground window first so that it is the first to receive the event.
2386 newTouchedWindows.insert(newTouchedWindows.begin(), newTouchedWindowHandle);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002387 }
2388
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002389 if (newTouchedWindows.empty()) {
Prabir Pradhan82e081e2022-12-06 09:50:09 +00002390 ALOGI("Dropping event because there is no touchable window at (%.1f, %.1f) on display "
2391 "%d.",
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002392 x, y, displayId);
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002393 outInjectionResult = InputEventInjectionResult::FAILED;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002394 return {};
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002395 }
2396
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002397 for (const sp<WindowInfoHandle>& windowHandle : newTouchedWindows) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07002398 if (!canWindowReceiveMotionLocked(windowHandle, entry)) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002399 continue;
2400 }
2401
Siarhei Vishniakoub681c202023-05-01 11:22:33 -07002402 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2403 maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE) {
Siarhei Vishniakoub681c202023-05-01 11:22:33 -07002404 // The "windowHandle" is the target of this hovering pointer.
2405 tempTouchState.addHoveringPointerToWindow(windowHandle, entry.deviceId, pointerId);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002406 }
2407
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002408 // Set target flags.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002409 ftl::Flags<InputTarget::Flags> targetFlags = InputTarget::Flags::DISPATCH_AS_IS;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002410
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002411 if (canReceiveForegroundTouches(*windowHandle->getInfo())) {
2412 // There should only be one touched window that can be "foreground" for the pointer.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002413 targetFlags |= InputTarget::Flags::FOREGROUND;
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002414 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002415
2416 if (isSplit) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002417 targetFlags |= InputTarget::Flags::SPLIT;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002418 }
2419 if (isWindowObscuredAtPointLocked(windowHandle, x, y)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002420 targetFlags |= InputTarget::Flags::WINDOW_IS_OBSCURED;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002421 } else if (isWindowObscuredLocked(windowHandle)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002422 targetFlags |= InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002423 }
Michael Wright3dd60e22019-03-27 22:06:44 +00002424
2425 // Update the temporary touch state.
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08002426 std::bitset<MAX_POINTER_ID + 1> pointerIds;
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002427 if (!isHoverAction) {
Siarhei Vishniakou70f3d8c2023-09-19 15:36:52 -07002428 pointerIds.set(pointerId);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002429 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002430
Siarhei Vishniakoue0431e42023-01-28 17:01:39 -08002431 const bool isDownOrPointerDown = maskedAction == AMOTION_EVENT_ACTION_DOWN ||
2432 maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN;
2433
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002434 // TODO(b/211379801): Currently, even if pointerIds are empty (hover case), we would
2435 // still add a window to the touch state. We should avoid doing that, but some of the
2436 // later checks ("at least one foreground window") rely on this in order to dispatch
2437 // the event properly, so that needs to be updated, possibly by looking at InputTargets.
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002438 tempTouchState.addOrUpdateWindow(windowHandle, targetFlags, entry.deviceId, pointerIds,
Siarhei Vishniakoue0431e42023-01-28 17:01:39 -08002439 isDownOrPointerDown
2440 ? std::make_optional(entry.eventTime)
2441 : std::nullopt);
Arthur Hungc539dbb2022-12-08 07:45:36 +00002442
2443 // If this is the pointer going down and the touched window has a wallpaper
2444 // then also add the touched wallpaper windows so they are locked in for the duration
2445 // of the touch gesture.
2446 // We do not collect wallpapers during HOVER_MOVE or SCROLL because the wallpaper
2447 // engine only supports touch events. We would need to add a mechanism similar
2448 // to View.onGenericMotionEvent to enable wallpapers to handle these events.
Siarhei Vishniakoue0431e42023-01-28 17:01:39 -08002449 if (isDownOrPointerDown) {
Arthur Hungc539dbb2022-12-08 07:45:36 +00002450 if (targetFlags.test(InputTarget::Flags::FOREGROUND) &&
2451 windowHandle->getInfo()->inputConfig.test(
2452 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER)) {
2453 sp<WindowInfoHandle> wallpaper = findWallpaperWindowBelow(windowHandle);
2454 if (wallpaper != nullptr) {
2455 ftl::Flags<InputTarget::Flags> wallpaperFlags =
2456 InputTarget::Flags::WINDOW_IS_OBSCURED |
2457 InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED |
2458 InputTarget::Flags::DISPATCH_AS_IS;
2459 if (isSplit) {
2460 wallpaperFlags |= InputTarget::Flags::SPLIT;
2461 }
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002462 tempTouchState.addOrUpdateWindow(wallpaper, wallpaperFlags, entry.deviceId,
2463 pointerIds, entry.eventTime);
Arthur Hungc539dbb2022-12-08 07:45:36 +00002464 }
2465 }
2466 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002467 }
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00002468
Siarhei Vishniakou060f82b2023-01-27 06:39:14 -08002469 // If a window is already pilfering some pointers, give it this new pointer as well and
2470 // make it pilfering. This will prevent other non-spy windows from getting this pointer,
2471 // which is a specific behaviour that we want.
Siarhei Vishniakou060f82b2023-01-27 06:39:14 -08002472 for (TouchedWindow& touchedWindow : tempTouchState.windows) {
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002473 if (touchedWindow.hasTouchingPointer(entry.deviceId, pointerId) &&
2474 touchedWindow.hasPilferingPointers(entry.deviceId)) {
Siarhei Vishniakou060f82b2023-01-27 06:39:14 -08002475 // This window is already pilfering some pointers, and this new pointer is also
2476 // going to it. Therefore, take over this pointer and don't give it to anyone
2477 // else.
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002478 touchedWindow.addPilferingPointer(entry.deviceId, pointerId);
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00002479 }
2480 }
Siarhei Vishniakou060f82b2023-01-27 06:39:14 -08002481
2482 // Restrict all pilfered pointers to the pilfering windows.
2483 tempTouchState.cancelPointersForNonPilferingWindows();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002484 } else {
2485 /* Case 2: Pointer move, up, cancel or non-splittable pointer down. */
2486
2487 // If the pointer is not currently down, then ignore the event.
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07002488 if (!tempTouchState.isDown() && maskedAction != AMOTION_EVENT_ACTION_HOVER_EXIT) {
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002489 LOG(INFO) << "Dropping event because the pointer is not down or we previously "
2490 "dropped the pointer down event in display "
2491 << displayId << ": " << entry.getDescription();
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002492 outInjectionResult = InputEventInjectionResult::FAILED;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002493 return {};
Michael Wrightd02c5b62014-02-10 15:10:22 -08002494 }
2495
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07002496 // If the pointer is not currently hovering, then ignore the event.
2497 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT) {
2498 const int32_t pointerId = entry.pointerProperties[0].id;
2499 if (oldState == nullptr ||
2500 oldState->getWindowsWithHoveringPointer(entry.deviceId, pointerId).empty()) {
2501 LOG(INFO) << "Dropping event because the hovering pointer is not in any windows in "
2502 "display "
2503 << displayId << ": " << entry.getDescription();
2504 outInjectionResult = InputEventInjectionResult::FAILED;
2505 return {};
2506 }
2507 tempTouchState.removeHoveringPointer(entry.deviceId, pointerId);
2508 }
2509
arthurhung6d4bed92021-03-17 11:59:33 +08002510 addDragEventLocked(entry);
arthurhungb89ccb02020-12-30 16:19:01 +08002511
Michael Wrightd02c5b62014-02-10 15:10:22 -08002512 // Check whether touches should slip outside of the current foreground window.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002513 if (maskedAction == AMOTION_EVENT_ACTION_MOVE && entry.pointerCount == 1 &&
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002514 tempTouchState.isSlippery()) {
Siarhei Vishniakou9306c382022-09-30 15:30:31 -07002515 const auto [x, y] = resolveTouchedPosition(entry);
Harry Cutts33476232023-01-30 19:57:29 +00002516 const bool isStylus = isPointerFromStylus(entry, /*pointerIndex=*/0);
chaviw98318de2021-05-19 16:45:23 -05002517 sp<WindowInfoHandle> oldTouchedWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002518 tempTouchState.getFirstForegroundWindowHandle();
Siarhei Vishniakou0f6558d2023-04-21 12:05:13 -07002519 LOG_ALWAYS_FATAL_IF(oldTouchedWindowHandle == nullptr);
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07002520 sp<WindowInfoHandle> newTouchedWindowHandle =
2521 findTouchedWindowAtLocked(displayId, x, y, isStylus);
Vishnu Nair062a8672021-09-03 16:07:44 -07002522
Prabir Pradhan5735a322022-04-11 17:23:34 +00002523 // Verify targeted injection.
2524 if (const auto err = verifyTargetedInjection(newTouchedWindowHandle, entry); err) {
2525 ALOGW("Dropping injected event: %s", (*err).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002526 outInjectionResult = os::InputEventInjectionResult::TARGET_MISMATCH;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002527 return {};
Prabir Pradhan5735a322022-04-11 17:23:34 +00002528 }
2529
Vishnu Nair062a8672021-09-03 16:07:44 -07002530 // Drop touch events if requested by input feature
2531 if (newTouchedWindowHandle != nullptr &&
2532 shouldDropInput(entry, newTouchedWindowHandle)) {
2533 newTouchedWindowHandle = nullptr;
2534 }
2535
Siarhei Vishniakouafa08cc2023-05-08 22:35:50 -07002536 if (newTouchedWindowHandle != nullptr &&
2537 !haveSameToken(oldTouchedWindowHandle, newTouchedWindowHandle)) {
Siarhei Vishniakou0f6558d2023-04-21 12:05:13 -07002538 ALOGD("Touch is slipping out of window %s into window %s in display %" PRId32,
2539 oldTouchedWindowHandle->getName().c_str(),
2540 newTouchedWindowHandle->getName().c_str(), displayId);
2541
Michael Wrightd02c5b62014-02-10 15:10:22 -08002542 // Make a slippery exit from the old window.
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08002543 std::bitset<MAX_POINTER_ID + 1> pointerIds;
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002544 const int32_t pointerId = entry.pointerProperties[0].id;
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08002545 pointerIds.set(pointerId);
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002546
2547 const TouchedWindow& touchedWindow =
2548 tempTouchState.getTouchedWindow(oldTouchedWindowHandle);
2549 addWindowTargetLocked(oldTouchedWindowHandle,
2550 InputTarget::Flags::DISPATCH_AS_SLIPPERY_EXIT, pointerIds,
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002551 touchedWindow.getDownTimeInTarget(entry.deviceId), targets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002552
2553 // Make a slippery entrance into the new window.
2554 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
Prabir Pradhan713bb3e2021-12-20 02:07:40 -08002555 isSplit = !isFromMouse;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002556 }
2557
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002558 ftl::Flags<InputTarget::Flags> targetFlags =
2559 InputTarget::Flags::DISPATCH_AS_SLIPPERY_ENTER;
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002560 if (canReceiveForegroundTouches(*newTouchedWindowHandle->getInfo())) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002561 targetFlags |= InputTarget::Flags::FOREGROUND;
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002562 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002563 if (isSplit) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002564 targetFlags |= InputTarget::Flags::SPLIT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002565 }
2566 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002567 targetFlags |= InputTarget::Flags::WINDOW_IS_OBSCURED;
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002568 } else if (isWindowObscuredLocked(newTouchedWindowHandle)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002569 targetFlags |= InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002570 }
2571
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002572 tempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags,
2573 entry.deviceId, pointerIds, entry.eventTime);
Arthur Hungc539dbb2022-12-08 07:45:36 +00002574
2575 // Check if the wallpaper window should deliver the corresponding event.
2576 slipWallpaperTouch(targetFlags, oldTouchedWindowHandle, newTouchedWindowHandle,
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002577 tempTouchState, entry.deviceId, pointerId, targets);
2578 tempTouchState.removeTouchingPointerFromWindow(entry.deviceId, pointerId,
2579 oldTouchedWindowHandle);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002580 }
2581 }
Arthur Hung96483742022-11-15 03:30:48 +00002582
2583 // Update the pointerIds for non-splittable when it received pointer down.
2584 if (!isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN) {
2585 // If no split, we suppose all touched windows should receive pointer down.
Siarhei Vishniakou5b9766d2023-07-18 14:06:29 -07002586 const int32_t pointerIndex = MotionEvent::getActionIndex(action);
Arthur Hung96483742022-11-15 03:30:48 +00002587 for (size_t i = 0; i < tempTouchState.windows.size(); i++) {
2588 TouchedWindow& touchedWindow = tempTouchState.windows[i];
2589 // Ignore drag window for it should just track one pointer.
2590 if (mDragState && mDragState->dragWindow == touchedWindow.windowHandle) {
2591 continue;
2592 }
Siarhei Vishniakou5b9766d2023-07-18 14:06:29 -07002593 std::bitset<MAX_POINTER_ID + 1> touchingPointers;
2594 touchingPointers.set(entry.pointerProperties[pointerIndex].id);
2595 touchedWindow.addTouchingPointers(entry.deviceId, touchingPointers);
Arthur Hung96483742022-11-15 03:30:48 +00002596 }
2597 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002598 }
2599
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002600 // Update dispatching for hover enter and exit.
Sam Dubeyf886dec2023-01-27 13:28:19 +00002601 {
2602 std::vector<TouchedWindow> hoveringWindows =
2603 getHoveringWindowsLocked(oldState, tempTouchState, entry);
2604 for (const TouchedWindow& touchedWindow : hoveringWindows) {
Siarhei Vishniakoud5876ba2023-05-15 17:58:34 -07002605 std::optional<InputTarget> target =
2606 createInputTargetLocked(touchedWindow.windowHandle, touchedWindow.targetFlags,
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002607 touchedWindow.getDownTimeInTarget(entry.deviceId));
Siarhei Vishniakoud5876ba2023-05-15 17:58:34 -07002608 if (!target) {
2609 continue;
2610 }
2611 // Hardcode to single hovering pointer for now.
2612 std::bitset<MAX_POINTER_ID + 1> pointerIds;
2613 pointerIds.set(entry.pointerProperties[0].id);
2614 target->addPointers(pointerIds, touchedWindow.windowHandle->getInfo()->transform);
2615 targets.push_back(*target);
Sam Dubeyf886dec2023-01-27 13:28:19 +00002616 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002617 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002618
Prabir Pradhan5735a322022-04-11 17:23:34 +00002619 // Ensure that all touched windows are valid for injection.
2620 if (entry.injectionState != nullptr) {
2621 std::string errs;
2622 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Prabir Pradhan5735a322022-04-11 17:23:34 +00002623 const auto err = verifyTargetedInjection(touchedWindow.windowHandle, entry);
2624 if (err) errs += "\n - " + *err;
2625 }
2626 if (!errs.empty()) {
2627 ALOGW("Dropping targeted injection: At least one touched window is not owned by uid "
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00002628 "%s:%s",
2629 entry.injectionState->targetUid->toString().c_str(), errs.c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002630 outInjectionResult = InputEventInjectionResult::TARGET_MISMATCH;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002631 return {};
Prabir Pradhan5735a322022-04-11 17:23:34 +00002632 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002633 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002634
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002635 // Check whether windows listening for outside touches are owned by the same UID. If the owner
2636 // has a different UID, then we will not reveal coordinate information to this window.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002637 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
chaviw98318de2021-05-19 16:45:23 -05002638 sp<WindowInfoHandle> foregroundWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002639 tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002640 if (foregroundWindowHandle) {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00002641 const auto foregroundWindowUid = foregroundWindowHandle->getInfo()->ownerUid;
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002642 for (InputTarget& target : targets) {
2643 if (target.flags.test(InputTarget::Flags::DISPATCH_AS_OUTSIDE)) {
2644 sp<WindowInfoHandle> targetWindow =
2645 getWindowHandleLocked(target.inputChannel->getConnectionToken());
2646 if (targetWindow->getInfo()->ownerUid != foregroundWindowUid) {
2647 target.flags |= InputTarget::Flags::ZERO_COORDS;
Michael Wright3dd60e22019-03-27 22:06:44 +00002648 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002649 }
2650 }
2651 }
2652 }
2653
Harry Cuttsb166c002023-05-09 13:06:05 +00002654 // If this is a touchpad navigation gesture, it needs to only be sent to trusted targets, as we
2655 // only want the system UI to handle these gestures.
2656 const bool isTouchpadNavGesture = isFromSource(entry.source, AINPUT_SOURCE_MOUSE) &&
2657 entry.classification == MotionClassification::MULTI_FINGER_SWIPE;
2658 if (isTouchpadNavGesture) {
2659 filterUntrustedTargets(/* byref */ tempTouchState, /* byref */ targets);
2660 }
2661
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07002662 // Output targets from the touch state.
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002663 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002664 if (!touchedWindow.hasTouchingPointers(entry.deviceId) &&
2665 !touchedWindow.hasHoveringPointers(entry.deviceId)) {
Siarhei Vishniakoue0431e42023-01-28 17:01:39 -08002666 // Windows with hovering pointers are getting persisted inside TouchState.
2667 // Do not send this event to those windows.
2668 continue;
2669 }
Harry Cuttsb166c002023-05-09 13:06:05 +00002670
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002671 addWindowTargetLocked(touchedWindow.windowHandle, touchedWindow.targetFlags,
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002672 touchedWindow.getTouchingPointers(entry.deviceId),
2673 touchedWindow.getDownTimeInTarget(entry.deviceId), targets);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002674 }
Sam Dubey39d37cf2022-12-07 18:05:35 +00002675
Siarhei Vishniakou580fb3a2023-05-05 15:02:20 -07002676 // During targeted injection, only allow owned targets to receive events
2677 std::erase_if(targets, [&](const InputTarget& target) {
2678 LOG_ALWAYS_FATAL_IF(target.windowHandle == nullptr);
2679 const auto err = verifyTargetedInjection(target.windowHandle, entry);
2680 if (err) {
2681 LOG(WARNING) << "Dropping injected event from " << target.windowHandle->getName()
2682 << ": " << (*err);
2683 return true;
2684 }
2685 return false;
2686 });
2687
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07002688 if (targets.empty()) {
2689 LOG(INFO) << "Dropping event because no targets were found: " << entry.getDescription();
2690 outInjectionResult = InputEventInjectionResult::FAILED;
2691 return {};
2692 }
2693
2694 // If we only have windows getting ACTION_OUTSIDE, then drop the event, because there is no
2695 // window that is actually receiving the entire gesture.
2696 if (std::all_of(targets.begin(), targets.end(), [](const InputTarget& target) {
2697 return target.flags.test(InputTarget::Flags::DISPATCH_AS_OUTSIDE);
2698 })) {
2699 LOG(INFO) << "Dropping event because all windows would just receive ACTION_OUTSIDE: "
2700 << entry.getDescription();
2701 outInjectionResult = InputEventInjectionResult::FAILED;
2702 return {};
2703 }
2704
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002705 outInjectionResult = InputEventInjectionResult::SUCCEEDED;
Sam Dubeyf886dec2023-01-27 13:28:19 +00002706 // Drop the outside or hover touch windows since we will not care about them
2707 // in the next iteration.
2708 tempTouchState.filterNonAsIsTouchWindows();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002709
Michael Wrightd02c5b62014-02-10 15:10:22 -08002710 // Update final pieces of touch state if the injector had permission.
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002711 if (switchedDevice) {
2712 if (DEBUG_FOCUS) {
2713 ALOGD("Conflicting pointer actions: Switched to a different device.");
2714 }
2715 *outConflictingPointerActions = true;
2716 }
2717
2718 if (isHoverAction) {
2719 // Started hovering, therefore no longer down.
Siarhei Vishniakou3ad385b2022-11-04 10:09:53 -07002720 if (oldState && oldState->isDown()) {
Siarhei Vishniakou6e1e9872022-11-08 17:51:35 -08002721 ALOGD_IF(DEBUG_FOCUS,
2722 "Conflicting pointer actions: Hover received while pointer was down.");
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002723 *outConflictingPointerActions = true;
2724 }
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002725 } else if (maskedAction == AMOTION_EVENT_ACTION_UP) {
2726 // Pointer went up.
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002727 tempTouchState.removeTouchingPointer(entry.deviceId, entry.pointerProperties[0].id);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002728 } else if (maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002729 // All pointers up or canceled.
2730 tempTouchState.reset();
2731 } else if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
2732 // First pointer went down.
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002733 if (oldState && (oldState->isDown() || oldState->hasHoveringPointers())) {
2734 ALOGD("Conflicting pointer actions: Down received while already down or hovering.");
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002735 *outConflictingPointerActions = true;
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002736 }
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002737 } else if (maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
2738 // One pointer went up.
Siarhei Vishniakou5b9766d2023-07-18 14:06:29 -07002739 const int32_t pointerIndex = MotionEvent::getActionIndex(action);
2740 const uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
2741 tempTouchState.removeTouchingPointer(entry.deviceId, pointerId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002742 }
2743
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002744 // Save changes unless the action was scroll in which case the temporary touch
2745 // state was only valid for this one action.
2746 if (maskedAction != AMOTION_EVENT_ACTION_SCROLL) {
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07002747 if (displayId >= 0) {
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002748 tempTouchState.clearWindowsWithoutPointers();
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002749 mTouchStatesByDisplay[displayId] = tempTouchState;
2750 } else {
2751 mTouchStatesByDisplay.erase(displayId);
2752 }
2753 }
2754
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -08002755 if (tempTouchState.windows.empty()) {
2756 mTouchStatesByDisplay.erase(displayId);
2757 }
2758
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002759 return targets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002760}
2761
arthurhung6d4bed92021-03-17 11:59:33 +08002762void InputDispatcher::finishDragAndDrop(int32_t displayId, float x, float y) {
Prabir Pradhand65552b2021-10-07 11:23:50 -07002763 // Prevent stylus interceptor windows from affecting drag and drop behavior for now, until we
2764 // have an explicit reason to support it.
2765 constexpr bool isStylus = false;
2766
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07002767 sp<WindowInfoHandle> dropWindow =
Harry Cutts33476232023-01-30 19:57:29 +00002768 findTouchedWindowAtLocked(displayId, x, y, isStylus, /*ignoreDragWindow=*/true);
arthurhung6d4bed92021-03-17 11:59:33 +08002769 if (dropWindow) {
2770 vec2 local = dropWindow->getInfo()->transform.transform(x, y);
Prabir Pradhancef936d2021-07-21 16:17:52 +00002771 sendDropWindowCommandLocked(dropWindow->getToken(), local.x, local.y);
Arthur Hung6d0571e2021-04-09 20:18:16 +08002772 } else {
Arthur Hung54745652022-04-20 07:17:41 +00002773 ALOGW("No window found when drop.");
Prabir Pradhancef936d2021-07-21 16:17:52 +00002774 sendDropWindowCommandLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08002775 }
2776 mDragState.reset();
2777}
2778
2779void InputDispatcher::addDragEventLocked(const MotionEntry& entry) {
Arthur Hung3915c1f2022-05-31 07:17:17 +00002780 if (!mDragState || mDragState->dragWindow->getInfo()->displayId != entry.displayId) {
arthurhungb89ccb02020-12-30 16:19:01 +08002781 return;
2782 }
2783
arthurhung6d4bed92021-03-17 11:59:33 +08002784 if (!mDragState->isStartDrag) {
2785 mDragState->isStartDrag = true;
2786 mDragState->isStylusButtonDownAtStart =
2787 (entry.buttonState & AMOTION_EVENT_BUTTON_STYLUS_PRIMARY) != 0;
2788 }
2789
Arthur Hung54745652022-04-20 07:17:41 +00002790 // Find the pointer index by id.
2791 int32_t pointerIndex = 0;
2792 for (; static_cast<uint32_t>(pointerIndex) < entry.pointerCount; pointerIndex++) {
2793 const PointerProperties& pointerProperties = entry.pointerProperties[pointerIndex];
2794 if (pointerProperties.id == mDragState->pointerId) {
2795 break;
arthurhung6d4bed92021-03-17 11:59:33 +08002796 }
Arthur Hung54745652022-04-20 07:17:41 +00002797 }
arthurhung6d4bed92021-03-17 11:59:33 +08002798
Arthur Hung54745652022-04-20 07:17:41 +00002799 if (uint32_t(pointerIndex) == entry.pointerCount) {
2800 LOG_ALWAYS_FATAL("Should find a valid pointer index by id %d", mDragState->pointerId);
Arthur Hung54745652022-04-20 07:17:41 +00002801 }
2802
2803 const int32_t maskedAction = entry.action & AMOTION_EVENT_ACTION_MASK;
2804 const int32_t x = entry.pointerCoords[pointerIndex].getX();
2805 const int32_t y = entry.pointerCoords[pointerIndex].getY();
2806
2807 switch (maskedAction) {
2808 case AMOTION_EVENT_ACTION_MOVE: {
2809 // Handle the special case : stylus button no longer pressed.
2810 bool isStylusButtonDown =
2811 (entry.buttonState & AMOTION_EVENT_BUTTON_STYLUS_PRIMARY) != 0;
2812 if (mDragState->isStylusButtonDownAtStart && !isStylusButtonDown) {
2813 finishDragAndDrop(entry.displayId, x, y);
2814 return;
2815 }
2816
2817 // Prevent stylus interceptor windows from affecting drag and drop behavior for now,
2818 // until we have an explicit reason to support it.
2819 constexpr bool isStylus = false;
2820
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07002821 sp<WindowInfoHandle> hoverWindowHandle =
2822 findTouchedWindowAtLocked(entry.displayId, x, y, isStylus,
2823 /*ignoreDragWindow=*/true);
Arthur Hung54745652022-04-20 07:17:41 +00002824 // enqueue drag exit if needed.
2825 if (hoverWindowHandle != mDragState->dragHoverWindowHandle &&
2826 !haveSameToken(hoverWindowHandle, mDragState->dragHoverWindowHandle)) {
2827 if (mDragState->dragHoverWindowHandle != nullptr) {
Harry Cutts33476232023-01-30 19:57:29 +00002828 enqueueDragEventLocked(mDragState->dragHoverWindowHandle, /*isExiting=*/true, x,
Arthur Hung54745652022-04-20 07:17:41 +00002829 y);
2830 }
2831 mDragState->dragHoverWindowHandle = hoverWindowHandle;
2832 }
2833 // enqueue drag location if needed.
2834 if (hoverWindowHandle != nullptr) {
Harry Cutts33476232023-01-30 19:57:29 +00002835 enqueueDragEventLocked(hoverWindowHandle, /*isExiting=*/false, x, y);
Arthur Hung54745652022-04-20 07:17:41 +00002836 }
2837 break;
2838 }
2839
2840 case AMOTION_EVENT_ACTION_POINTER_UP:
Siarhei Vishniakou5b9766d2023-07-18 14:06:29 -07002841 if (MotionEvent::getActionIndex(entry.action) != pointerIndex) {
Arthur Hung54745652022-04-20 07:17:41 +00002842 break;
2843 }
2844 // The drag pointer is up.
2845 [[fallthrough]];
2846 case AMOTION_EVENT_ACTION_UP:
2847 finishDragAndDrop(entry.displayId, x, y);
2848 break;
2849 case AMOTION_EVENT_ACTION_CANCEL: {
2850 ALOGD("Receiving cancel when drag and drop.");
2851 sendDropWindowCommandLocked(nullptr, 0, 0);
2852 mDragState.reset();
2853 break;
2854 }
arthurhungb89ccb02020-12-30 16:19:01 +08002855 }
2856}
2857
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002858std::optional<InputTarget> InputDispatcher::createInputTargetLocked(
2859 const sp<android::gui::WindowInfoHandle>& windowHandle,
2860 ftl::Flags<InputTarget::Flags> targetFlags,
2861 std::optional<nsecs_t> firstDownTimeInTarget) const {
2862 std::shared_ptr<InputChannel> inputChannel = getInputChannelLocked(windowHandle->getToken());
2863 if (inputChannel == nullptr) {
2864 ALOGW("Not creating InputTarget for %s, no input channel", windowHandle->getName().c_str());
2865 return {};
2866 }
2867 InputTarget inputTarget;
2868 inputTarget.inputChannel = inputChannel;
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00002869 inputTarget.windowHandle = windowHandle;
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002870 inputTarget.flags = targetFlags;
2871 inputTarget.globalScaleFactor = windowHandle->getInfo()->globalScaleFactor;
2872 inputTarget.firstDownTimeInTarget = firstDownTimeInTarget;
2873 const auto& displayInfoIt = mDisplayInfos.find(windowHandle->getInfo()->displayId);
2874 if (displayInfoIt != mDisplayInfos.end()) {
2875 inputTarget.displayTransform = displayInfoIt->second.transform;
2876 } else {
Siarhei Vishniakou580fb3a2023-05-05 15:02:20 -07002877 // DisplayInfo not found for this window on display windowHandle->getInfo()->displayId.
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002878 // TODO(b/198444055): Make this an error message after 'setInputWindows' API is removed.
2879 }
2880 return inputTarget;
2881}
2882
chaviw98318de2021-05-19 16:45:23 -05002883void InputDispatcher::addWindowTargetLocked(const sp<WindowInfoHandle>& windowHandle,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002884 ftl::Flags<InputTarget::Flags> targetFlags,
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08002885 std::bitset<MAX_POINTER_ID + 1> pointerIds,
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002886 std::optional<nsecs_t> firstDownTimeInTarget,
Siarhei Vishniakouf75cddb2022-10-25 10:42:16 -07002887 std::vector<InputTarget>& inputTargets) const {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002888 std::vector<InputTarget>::iterator it =
2889 std::find_if(inputTargets.begin(), inputTargets.end(),
2890 [&windowHandle](const InputTarget& inputTarget) {
2891 return inputTarget.inputChannel->getConnectionToken() ==
2892 windowHandle->getToken();
2893 });
Chavi Weingarten97b8eec2020-01-09 18:09:08 +00002894
chaviw98318de2021-05-19 16:45:23 -05002895 const WindowInfo* windowInfo = windowHandle->getInfo();
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002896
2897 if (it == inputTargets.end()) {
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002898 std::optional<InputTarget> target =
2899 createInputTargetLocked(windowHandle, targetFlags, firstDownTimeInTarget);
2900 if (!target) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002901 return;
2902 }
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002903 inputTargets.push_back(*target);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002904 it = inputTargets.end() - 1;
2905 }
2906
2907 ALOG_ASSERT(it->flags == targetFlags);
2908 ALOG_ASSERT(it->globalScaleFactor == windowInfo->globalScaleFactor);
2909
chaviw1ff3d1e2020-07-01 15:53:47 -07002910 it->addPointers(pointerIds, windowInfo->transform);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002911}
2912
Michael Wright3dd60e22019-03-27 22:06:44 +00002913void InputDispatcher::addGlobalMonitoringTargetsLocked(std::vector<InputTarget>& inputTargets,
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002914 int32_t displayId) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002915 auto monitorsIt = mGlobalMonitorsByDisplay.find(displayId);
2916 if (monitorsIt == mGlobalMonitorsByDisplay.end()) return;
Michael Wright3dd60e22019-03-27 22:06:44 +00002917
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002918 for (const Monitor& monitor : selectResponsiveMonitorsLocked(monitorsIt->second)) {
2919 InputTarget target;
2920 target.inputChannel = monitor.inputChannel;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002921 target.flags = InputTarget::Flags::DISPATCH_AS_IS;
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002922 // target.firstDownTimeInTarget is not set for global monitors. It is only required in split
2923 // touch and global monitoring works as intended even without setting firstDownTimeInTarget
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002924 if (const auto& it = mDisplayInfos.find(displayId); it != mDisplayInfos.end()) {
2925 target.displayTransform = it->second.transform;
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002926 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002927 target.setDefaultPointerTransform(target.displayTransform);
2928 inputTargets.push_back(target);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002929 }
2930}
2931
Robert Carrc9bf1d32020-04-13 17:21:08 -07002932/**
2933 * Indicate whether one window handle should be considered as obscuring
2934 * another window handle. We only check a few preconditions. Actually
2935 * checking the bounds is left to the caller.
2936 */
chaviw98318de2021-05-19 16:45:23 -05002937static bool canBeObscuredBy(const sp<WindowInfoHandle>& windowHandle,
2938 const sp<WindowInfoHandle>& otherHandle) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002939 // Compare by token so cloned layers aren't counted
2940 if (haveSameToken(windowHandle, otherHandle)) {
2941 return false;
2942 }
2943 auto info = windowHandle->getInfo();
2944 auto otherInfo = otherHandle->getInfo();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002945 if (otherInfo->inputConfig.test(WindowInfo::InputConfig::NOT_VISIBLE)) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002946 return false;
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002947 } else if (otherInfo->alpha == 0 &&
2948 otherInfo->inputConfig.test(WindowInfo::InputConfig::NOT_TOUCHABLE)) {
Bernardo Rufino653d2e02020-10-20 17:32:40 +00002949 // Those act as if they were invisible, so we don't need to flag them.
2950 // We do want to potentially flag touchable windows even if they have 0
2951 // opacity, since they can consume touches and alter the effects of the
2952 // user interaction (eg. apps that rely on
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002953 // Flags::WINDOW_IS_PARTIALLY_OBSCURED should still be told about those
Bernardo Rufino653d2e02020-10-20 17:32:40 +00002954 // windows), hence we also check for FLAG_NOT_TOUCHABLE.
2955 return false;
Bernardo Rufino8007daf2020-09-22 09:40:01 +00002956 } else if (info->ownerUid == otherInfo->ownerUid) {
2957 // If ownerUid is the same we don't generate occlusion events as there
2958 // is no security boundary within an uid.
Robert Carrc9bf1d32020-04-13 17:21:08 -07002959 return false;
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002960 } else if (otherInfo->inputConfig.test(gui::WindowInfo::InputConfig::TRUSTED_OVERLAY)) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002961 return false;
2962 } else if (otherInfo->displayId != info->displayId) {
2963 return false;
2964 }
2965 return true;
2966}
2967
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002968/**
2969 * Returns touch occlusion information in the form of TouchOcclusionInfo. To check if the touch is
2970 * untrusted, one should check:
2971 *
2972 * 1. If result.hasBlockingOcclusion is true.
2973 * If it's, it means the touch should be blocked due to a window with occlusion mode of
2974 * BLOCK_UNTRUSTED.
2975 *
2976 * 2. If result.obscuringOpacity > mMaximumObscuringOpacityForTouch.
2977 * If it is (and 1 is false), then the touch should be blocked because a stack of windows
2978 * (possibly only one) with occlusion mode of USE_OPACITY from one UID resulted in a composed
2979 * obscuring opacity above the threshold. Note that if there was no window of occlusion mode
2980 * USE_OPACITY, result.obscuringOpacity would've been 0 and since
2981 * mMaximumObscuringOpacityForTouch >= 0, the condition above would never be true.
2982 *
2983 * If neither of those is true, then it means the touch can be allowed.
2984 */
2985InputDispatcher::TouchOcclusionInfo InputDispatcher::computeTouchOcclusionInfoLocked(
chaviw98318de2021-05-19 16:45:23 -05002986 const sp<WindowInfoHandle>& windowHandle, int32_t x, int32_t y) const {
2987 const WindowInfo* windowInfo = windowHandle->getInfo();
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002988 int32_t displayId = windowInfo->displayId;
chaviw98318de2021-05-19 16:45:23 -05002989 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002990 TouchOcclusionInfo info;
2991 info.hasBlockingOcclusion = false;
2992 info.obscuringOpacity = 0;
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00002993 info.obscuringUid = gui::Uid::INVALID;
2994 std::map<gui::Uid, float> opacityByUid;
chaviw98318de2021-05-19 16:45:23 -05002995 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002996 if (windowHandle == otherHandle) {
2997 break; // All future windows are below us. Exit early.
2998 }
chaviw98318de2021-05-19 16:45:23 -05002999 const WindowInfo* otherInfo = otherHandle->getInfo();
Bernardo Rufino1ff9d592021-01-18 16:58:57 +00003000 if (canBeObscuredBy(windowHandle, otherHandle) && otherInfo->frameContainsPoint(x, y) &&
3001 !haveSameApplicationToken(windowInfo, otherInfo)) {
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00003002 if (DEBUG_TOUCH_OCCLUSION) {
3003 info.debugInfo.push_back(
Harry Cutts101ee9b2023-07-06 18:04:14 +00003004 dumpWindowForTouchOcclusion(otherInfo, /*isTouchedWindow=*/false));
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00003005 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003006 // canBeObscuredBy() has returned true above, which means this window is untrusted, so
3007 // we perform the checks below to see if the touch can be propagated or not based on the
3008 // window's touch occlusion mode
3009 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::BLOCK_UNTRUSTED) {
3010 info.hasBlockingOcclusion = true;
3011 info.obscuringUid = otherInfo->ownerUid;
3012 info.obscuringPackage = otherInfo->packageName;
3013 break;
3014 }
3015 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::USE_OPACITY) {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003016 const auto uid = otherInfo->ownerUid;
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003017 float opacity =
3018 (opacityByUid.find(uid) == opacityByUid.end()) ? 0 : opacityByUid[uid];
3019 // Given windows A and B:
3020 // opacity(A, B) = 1 - [1 - opacity(A)] * [1 - opacity(B)]
3021 opacity = 1 - (1 - opacity) * (1 - otherInfo->alpha);
3022 opacityByUid[uid] = opacity;
3023 if (opacity > info.obscuringOpacity) {
3024 info.obscuringOpacity = opacity;
3025 info.obscuringUid = uid;
3026 info.obscuringPackage = otherInfo->packageName;
3027 }
3028 }
3029 }
3030 }
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00003031 if (DEBUG_TOUCH_OCCLUSION) {
Harry Cutts101ee9b2023-07-06 18:04:14 +00003032 info.debugInfo.push_back(dumpWindowForTouchOcclusion(windowInfo, /*isTouchedWindow=*/true));
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00003033 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003034 return info;
3035}
3036
chaviw98318de2021-05-19 16:45:23 -05003037std::string InputDispatcher::dumpWindowForTouchOcclusion(const WindowInfo* info,
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00003038 bool isTouchedWindow) const {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003039 return StringPrintf(INDENT2 "* %spackage=%s/%s, id=%" PRId32 ", mode=%s, alpha=%.2f, "
Prabir Pradhan51e7db02022-02-07 06:02:57 -08003040 "frame=[%" PRId32 ",%" PRId32 "][%" PRId32 ",%" PRId32
3041 "], touchableRegion=%s, window={%s}, inputConfig={%s}, "
3042 "hasToken=%s, applicationInfo.name=%s, applicationInfo.token=%s\n",
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08003043 isTouchedWindow ? "[TOUCHED] " : "", info->packageName.c_str(),
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003044 info->ownerUid.toString().c_str(), info->id,
Chavi Weingarten7f019192023-08-08 20:39:01 +00003045 toString(info->touchOcclusionMode).c_str(), info->alpha, info->frame.left,
3046 info->frame.top, info->frame.right, info->frame.bottom,
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003047 dumpRegion(info->touchableRegion).c_str(), info->name.c_str(),
3048 info->inputConfig.string().c_str(), toString(info->token != nullptr),
3049 info->applicationInfo.name.c_str(),
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07003050 binderToString(info->applicationInfo.token).c_str());
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00003051}
3052
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003053bool InputDispatcher::isTouchTrustedLocked(const TouchOcclusionInfo& occlusionInfo) const {
3054 if (occlusionInfo.hasBlockingOcclusion) {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003055 ALOGW("Untrusted touch due to occlusion by %s/%s", occlusionInfo.obscuringPackage.c_str(),
3056 occlusionInfo.obscuringUid.toString().c_str());
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003057 return false;
3058 }
3059 if (occlusionInfo.obscuringOpacity > mMaximumObscuringOpacityForTouch) {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003060 ALOGW("Untrusted touch due to occlusion by %s/%s (obscuring opacity = "
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003061 "%.2f, maximum allowed = %.2f)",
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003062 occlusionInfo.obscuringPackage.c_str(), occlusionInfo.obscuringUid.toString().c_str(),
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003063 occlusionInfo.obscuringOpacity, mMaximumObscuringOpacityForTouch);
3064 return false;
3065 }
3066 return true;
3067}
3068
chaviw98318de2021-05-19 16:45:23 -05003069bool InputDispatcher::isWindowObscuredAtPointLocked(const sp<WindowInfoHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003070 int32_t x, int32_t y) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003071 int32_t displayId = windowHandle->getInfo()->displayId;
chaviw98318de2021-05-19 16:45:23 -05003072 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
3073 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07003074 if (windowHandle == otherHandle) {
3075 break; // All future windows are below us. Exit early.
Michael Wrightd02c5b62014-02-10 15:10:22 -08003076 }
chaviw98318de2021-05-19 16:45:23 -05003077 const WindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07003078 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08003079 otherInfo->frameContainsPoint(x, y)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003080 return true;
3081 }
3082 }
3083 return false;
3084}
3085
chaviw98318de2021-05-19 16:45:23 -05003086bool InputDispatcher::isWindowObscuredLocked(const sp<WindowInfoHandle>& windowHandle) const {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07003087 int32_t displayId = windowHandle->getInfo()->displayId;
chaviw98318de2021-05-19 16:45:23 -05003088 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
3089 const WindowInfo* windowInfo = windowHandle->getInfo();
3090 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07003091 if (windowHandle == otherHandle) {
3092 break; // All future windows are below us. Exit early.
Michael Wrightcdcd8f22016-03-22 16:52:13 -07003093 }
chaviw98318de2021-05-19 16:45:23 -05003094 const WindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07003095 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08003096 otherInfo->overlaps(windowInfo)) {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07003097 return true;
3098 }
3099 }
3100 return false;
3101}
3102
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08003103std::string InputDispatcher::getApplicationWindowLabel(
chaviw98318de2021-05-19 16:45:23 -05003104 const InputApplicationHandle* applicationHandle, const sp<WindowInfoHandle>& windowHandle) {
Yi Kong9b14ac62018-07-17 13:48:38 -07003105 if (applicationHandle != nullptr) {
3106 if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07003107 return applicationHandle->getName() + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003108 } else {
3109 return applicationHandle->getName();
3110 }
Yi Kong9b14ac62018-07-17 13:48:38 -07003111 } else if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07003112 return windowHandle->getInfo()->applicationInfo.name + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003113 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003114 return "<unknown application or window>";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003115 }
3116}
3117
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003118void InputDispatcher::pokeUserActivityLocked(const EventEntry& eventEntry) {
Antonio Kantekf16f2832021-09-28 04:39:20 +00003119 if (!isUserActivityEvent(eventEntry)) {
3120 // Not poking user activity if the event type does not represent a user activity
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003121 return;
3122 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003123 int32_t displayId = getTargetDisplayId(eventEntry);
chaviw98318de2021-05-19 16:45:23 -05003124 sp<WindowInfoHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Josep del Riob3981622023-04-18 15:49:45 +00003125 const WindowInfo* windowDisablingUserActivityInfo = nullptr;
Tiger Huang721e26f2018-07-24 22:26:19 +08003126 if (focusedWindowHandle != nullptr) {
chaviw98318de2021-05-19 16:45:23 -05003127 const WindowInfo* info = focusedWindowHandle->getInfo();
Prabir Pradhan51e7db02022-02-07 06:02:57 -08003128 if (info->inputConfig.test(WindowInfo::InputConfig::DISABLE_USER_ACTIVITY)) {
Josep del Riob3981622023-04-18 15:49:45 +00003129 windowDisablingUserActivityInfo = info;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003130 }
3131 }
3132
3133 int32_t eventType = USER_ACTIVITY_EVENT_OTHER;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003134 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003135 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003136 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
3137 if (motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003138 return;
3139 }
Josep del Riob3981622023-04-18 15:49:45 +00003140 if (windowDisablingUserActivityInfo != nullptr) {
3141 if (DEBUG_DISPATCH_CYCLE) {
3142 ALOGD("Not poking user activity: disabled by window '%s'.",
3143 windowDisablingUserActivityInfo->name.c_str());
3144 }
3145 return;
3146 }
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003147 if (MotionEvent::isTouchEvent(motionEntry.source, motionEntry.action)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003148 eventType = USER_ACTIVITY_EVENT_TOUCH;
3149 }
3150 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003151 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003152 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003153 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
3154 if (keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003155 return;
3156 }
Josep del Riob3981622023-04-18 15:49:45 +00003157 // If the key code is unknown, we don't consider it user activity
3158 if (keyEntry.keyCode == AKEYCODE_UNKNOWN) {
3159 return;
3160 }
3161 // Don't inhibit events that were intercepted or are not passed to
3162 // the apps, like system shortcuts
3163 if (windowDisablingUserActivityInfo != nullptr &&
3164 keyEntry.interceptKeyResult != KeyEntry::InterceptKeyResult::SKIP &&
3165 keyEntry.policyFlags & POLICY_FLAG_PASS_TO_USER) {
3166 if (DEBUG_DISPATCH_CYCLE) {
3167 ALOGD("Not poking user activity: disabled by window '%s'.",
3168 windowDisablingUserActivityInfo->name.c_str());
3169 }
3170 return;
3171 }
3172
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003173 eventType = USER_ACTIVITY_EVENT_BUTTON;
3174 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003175 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00003176 default: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003177 LOG_ALWAYS_FATAL("%s events are not user activity",
Dominik Laskowski75788452021-02-09 18:51:25 -08003178 ftl::enum_string(eventEntry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003179 break;
3180 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003181 }
3182
Prabir Pradhancef936d2021-07-21 16:17:52 +00003183 auto command = [this, eventTime = eventEntry.eventTime, eventType, displayId]()
3184 REQUIRES(mLock) {
3185 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00003186 mPolicy.pokeUserActivity(eventTime, eventType, displayId);
Prabir Pradhancef936d2021-07-21 16:17:52 +00003187 };
3188 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003189}
3190
3191void InputDispatcher::prepareDispatchCycleLocked(nsecs_t currentTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003192 const std::shared_ptr<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003193 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003194 const InputTarget& inputTarget) {
Prabir Pradhan2dac8b82023-09-06 01:11:51 +00003195 ATRACE_NAME_IF(ATRACE_ENABLED(),
3196 StringPrintf("prepareDispatchCycleLocked(inputChannel=%s, id=0x%" PRIx32 ")",
3197 connection->getInputChannelName().c_str(), eventEntry->id));
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003198 if (DEBUG_DISPATCH_CYCLE) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003199 ALOGD("channel '%s' ~ prepareDispatchCycle - flags=%s, "
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08003200 "globalScaleFactor=%f, pointerIds=%s %s",
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003201 connection->getInputChannelName().c_str(), inputTarget.flags.string().c_str(),
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08003202 inputTarget.globalScaleFactor, bitsetToString(inputTarget.pointerIds).c_str(),
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003203 inputTarget.getPointerInfoString().c_str());
3204 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003205
3206 // Skip this event if the connection status is not normal.
3207 // We don't want to enqueue additional outbound events if the connection is broken.
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003208 if (connection->status != Connection::Status::NORMAL) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003209 if (DEBUG_DISPATCH_CYCLE) {
3210 ALOGD("channel '%s' ~ Dropping event because the channel status is %s",
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003211 connection->getInputChannelName().c_str(),
3212 ftl::enum_string(connection->status).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003213 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003214 return;
3215 }
3216
3217 // Split a motion event if needed.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003218 if (inputTarget.flags.test(InputTarget::Flags::SPLIT)) {
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003219 LOG_ALWAYS_FATAL_IF(eventEntry->type != EventEntry::Type::MOTION,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003220 "Entry type %s should not have Flags::SPLIT",
Dominik Laskowski75788452021-02-09 18:51:25 -08003221 ftl::enum_string(eventEntry->type).c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003222
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003223 const MotionEntry& originalMotionEntry = static_cast<const MotionEntry&>(*eventEntry);
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003224 if (inputTarget.pointerIds.count() != originalMotionEntry.pointerCount) {
Siarhei Vishniakou16e4fa02023-02-16 17:48:56 -08003225 if (!inputTarget.firstDownTimeInTarget.has_value()) {
3226 logDispatchStateLocked();
3227 LOG(FATAL) << "Splitting motion events requires a down time to be set for the "
3228 "target on connection "
3229 << connection->getInputChannelName() << " for "
3230 << originalMotionEntry.getDescription();
3231 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003232 std::unique_ptr<MotionEntry> splitMotionEntry =
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00003233 splitMotionEvent(originalMotionEntry, inputTarget.pointerIds,
3234 inputTarget.firstDownTimeInTarget.value());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003235 if (!splitMotionEntry) {
3236 return; // split event was dropped
3237 }
Arthur Hungb3307ee2021-10-14 10:57:37 +00003238 if (splitMotionEntry->action == AMOTION_EVENT_ACTION_CANCEL) {
3239 std::string reason = std::string("reason=pointer cancel on split window");
3240 android_log_event_list(LOGTAG_INPUT_CANCEL)
3241 << connection->getInputChannelName().c_str() << reason << LOG_ID_EVENTS;
3242 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003243 if (DEBUG_FOCUS) {
3244 ALOGD("channel '%s' ~ Split motion event.",
3245 connection->getInputChannelName().c_str());
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003246 logOutboundMotionDetails(" ", *splitMotionEntry);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003247 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003248 enqueueDispatchEntriesLocked(currentTime, connection, std::move(splitMotionEntry),
3249 inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003250 return;
3251 }
3252 }
3253
3254 // Not splitting. Enqueue dispatch entries for the event as is.
3255 enqueueDispatchEntriesLocked(currentTime, connection, eventEntry, inputTarget);
3256}
3257
3258void InputDispatcher::enqueueDispatchEntriesLocked(nsecs_t currentTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003259 const std::shared_ptr<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003260 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003261 const InputTarget& inputTarget) {
Prabir Pradhan2dac8b82023-09-06 01:11:51 +00003262 ATRACE_NAME_IF(ATRACE_ENABLED(),
3263 StringPrintf("enqueueDispatchEntriesLocked(inputChannel=%s, id=0x%" PRIx32 ")",
3264 connection->getInputChannelName().c_str(), eventEntry->id));
Siarhei Vishniakou5cee1e32022-11-29 12:35:39 -08003265 LOG_ALWAYS_FATAL_IF(!inputTarget.flags.any(InputTarget::DISPATCH_MASK),
3266 "No dispatch flags are set for %s", eventEntry->getDescription().c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00003267
hongzuo liu95785e22022-09-06 02:51:35 +00003268 const bool wasEmpty = connection->outboundQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003269
3270 // Enqueue dispatch entries for the requested modes.
chaviw8c9cf542019-03-25 13:02:48 -07003271 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003272 InputTarget::Flags::DISPATCH_AS_HOVER_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07003273 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003274 InputTarget::Flags::DISPATCH_AS_OUTSIDE);
chaviw8c9cf542019-03-25 13:02:48 -07003275 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003276 InputTarget::Flags::DISPATCH_AS_HOVER_ENTER);
chaviw8c9cf542019-03-25 13:02:48 -07003277 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003278 InputTarget::Flags::DISPATCH_AS_IS);
chaviw8c9cf542019-03-25 13:02:48 -07003279 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003280 InputTarget::Flags::DISPATCH_AS_SLIPPERY_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07003281 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003282 InputTarget::Flags::DISPATCH_AS_SLIPPERY_ENTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003283
3284 // If the outbound queue was previously empty, start the dispatch cycle going.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003285 if (wasEmpty && !connection->outboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003286 startDispatchCycleLocked(currentTime, connection);
3287 }
3288}
3289
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003290void InputDispatcher::enqueueDispatchEntryLocked(const std::shared_ptr<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003291 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003292 const InputTarget& inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003293 ftl::Flags<InputTarget::Flags> dispatchMode) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003294 ftl::Flags<InputTarget::Flags> inputTargetFlags = inputTarget.flags;
3295 if (!inputTargetFlags.any(dispatchMode)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003296 return;
3297 }
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003298
3299 inputTargetFlags.clear(InputTarget::DISPATCH_MASK);
3300 inputTargetFlags |= dispatchMode;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003301
3302 // This is a new event.
3303 // Enqueue a new dispatch entry onto the outbound queue for this connection.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003304 std::unique_ptr<DispatchEntry> dispatchEntry =
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003305 createDispatchEntry(inputTarget, eventEntry, inputTargetFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003306
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003307 // Use the eventEntry from dispatchEntry since the entry may have changed and can now be a
3308 // different EventEntry than what was passed in.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003309 EventEntry& newEntry = *(dispatchEntry->eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003310 // Apply target flags and update the connection's input state.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003311 switch (newEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003312 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003313 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(newEntry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003314 if (!connection->inputState.trackKey(keyEntry, dispatchEntry->resolvedAction,
3315 dispatchEntry->resolvedFlags)) {
Siarhei Vishniakouc94dafe2023-05-26 10:24:19 -07003316 LOG(WARNING) << "channel " << connection->getInputChannelName()
3317 << "~ dropping inconsistent event: " << *dispatchEntry;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003318 return; // skip the inconsistent event
3319 }
3320 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003321 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003322
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003323 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003324 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003325 // Assign a default value to dispatchEntry that will never be generated by InputReader,
3326 // and assign a InputDispatcher value if it doesn't change in the if-else chain below.
3327 constexpr int32_t DEFAULT_RESOLVED_EVENT_ID =
3328 static_cast<int32_t>(IdGenerator::Source::OTHER);
3329 dispatchEntry->resolvedEventId = DEFAULT_RESOLVED_EVENT_ID;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003330 if (dispatchMode.test(InputTarget::Flags::DISPATCH_AS_OUTSIDE)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003331 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_OUTSIDE;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003332 } else if (dispatchMode.test(InputTarget::Flags::DISPATCH_AS_HOVER_EXIT)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003333 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_EXIT;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003334 } else if (dispatchMode.test(InputTarget::Flags::DISPATCH_AS_HOVER_ENTER)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003335 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003336 } else if (dispatchMode.test(InputTarget::Flags::DISPATCH_AS_SLIPPERY_EXIT)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003337 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_CANCEL;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003338 } else if (dispatchMode.test(InputTarget::Flags::DISPATCH_AS_SLIPPERY_ENTER)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003339 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_DOWN;
3340 } else {
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003341 dispatchEntry->resolvedEventId = motionEntry.id;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003342 }
3343 if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_HOVER_MOVE &&
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003344 !connection->inputState.isHovering(motionEntry.deviceId, motionEntry.source,
3345 motionEntry.displayId)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003346 if (DEBUG_DISPATCH_CYCLE) {
3347 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: filling in missing hover "
3348 "enter event",
3349 connection->getInputChannelName().c_str());
3350 }
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00003351 // We keep the 'resolvedEventId' here equal to the original 'motionEntry.id' because
3352 // this is a one-to-one event conversion.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003353 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
3354 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003355
Siarhei Vishniakou1ae72f12023-01-29 12:55:30 -08003356 if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_CANCEL) {
3357 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_CANCELED;
3358 }
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003359 if (dispatchEntry->targetFlags.test(InputTarget::Flags::WINDOW_IS_OBSCURED)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003360 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED;
3361 }
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003362 if (dispatchEntry->targetFlags.test(InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003363 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
3364 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003365
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003366 if (!connection->inputState.trackMotion(motionEntry, dispatchEntry->resolvedAction,
3367 dispatchEntry->resolvedFlags)) {
Siarhei Vishniakouc94dafe2023-05-26 10:24:19 -07003368 LOG(WARNING) << "channel " << connection->getInputChannelName()
3369 << "~ dropping inconsistent event: " << *dispatchEntry;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003370 return; // skip the inconsistent event
3371 }
3372
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003373 dispatchEntry->resolvedEventId =
3374 dispatchEntry->resolvedEventId == DEFAULT_RESOLVED_EVENT_ID
3375 ? mIdGenerator.nextId()
3376 : motionEntry.id;
3377 if (ATRACE_ENABLED() && dispatchEntry->resolvedEventId != motionEntry.id) {
3378 std::string message = StringPrintf("Transmute MotionEvent(id=0x%" PRIx32
3379 ") to MotionEvent(id=0x%" PRIx32 ").",
3380 motionEntry.id, dispatchEntry->resolvedEventId);
3381 ATRACE_NAME(message.c_str());
3382 }
3383
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08003384 if ((motionEntry.flags & AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE) &&
3385 (motionEntry.policyFlags & POLICY_FLAG_TRUSTED)) {
3386 // Skip reporting pointer down outside focus to the policy.
3387 break;
3388 }
3389
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003390 dispatchPointerDownOutsideFocus(motionEntry.source, dispatchEntry->resolvedAction,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003391 inputTarget.inputChannel->getConnectionToken());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003392
3393 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003394 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003395 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003396 case EventEntry::Type::TOUCH_MODE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08003397 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
3398 case EventEntry::Type::DRAG: {
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003399 break;
3400 }
Chris Yef59a2f42020-10-16 12:55:26 -07003401 case EventEntry::Type::SENSOR: {
3402 LOG_ALWAYS_FATAL("SENSOR events should not go to apps via input channel");
3403 break;
3404 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003405 case EventEntry::Type::CONFIGURATION_CHANGED:
3406 case EventEntry::Type::DEVICE_RESET: {
3407 LOG_ALWAYS_FATAL("%s events should not go to apps",
Dominik Laskowski75788452021-02-09 18:51:25 -08003408 ftl::enum_string(newEntry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003409 break;
3410 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003411 }
3412
3413 // Remember that we are waiting for this dispatch to complete.
3414 if (dispatchEntry->hasForegroundTarget()) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003415 incrementPendingForegroundDispatches(newEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003416 }
3417
3418 // Enqueue the dispatch entry.
Prabir Pradhan8c90d782023-09-15 21:16:44 +00003419 connection->outboundQueue.emplace_back(std::move(dispatchEntry));
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003420 traceOutboundQueueLength(*connection);
chaviw8c9cf542019-03-25 13:02:48 -07003421}
3422
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003423/**
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003424 * This function is for debugging and metrics collection. It has two roles.
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003425 *
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003426 * The first role is to log input interaction with windows, which helps determine what the user was
3427 * interacting with. For example, if user is touching launcher, we will see an input_interaction log
3428 * that user started interacting with launcher window, as well as any other window that received
3429 * that gesture, such as the wallpaper or other spy windows. A new input_interaction is only logged
3430 * when the set of tokens that received the event changes. It is not logged again as long as the
3431 * user is interacting with the same windows.
3432 *
3433 * The second role is to track input device activity for metrics collection. For each input event,
3434 * we report the set of UIDs that the input device interacted with to the policy. Unlike for the
3435 * input_interaction logs, the device interaction is reported even when the set of interaction
3436 * tokens do not change.
3437 *
3438 * For these purposes, we do not count ACTION_OUTSIDE, ACTION_UP and ACTION_CANCEL actions as
3439 * interaction. This includes up and cancel events for both keys and motions.
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003440 */
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003441void InputDispatcher::processInteractionsLocked(const EventEntry& entry,
3442 const std::vector<InputTarget>& targets) {
3443 int32_t deviceId;
3444 nsecs_t eventTime;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003445 // Skip ACTION_UP events, and all events other than keys and motions
3446 if (entry.type == EventEntry::Type::KEY) {
3447 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
3448 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
3449 return;
3450 }
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003451 deviceId = keyEntry.deviceId;
3452 eventTime = keyEntry.eventTime;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003453 } else if (entry.type == EventEntry::Type::MOTION) {
3454 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
3455 if (motionEntry.action == AMOTION_EVENT_ACTION_UP ||
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003456 motionEntry.action == AMOTION_EVENT_ACTION_CANCEL ||
3457 MotionEvent::getActionMasked(motionEntry.action) == AMOTION_EVENT_ACTION_POINTER_UP) {
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003458 return;
3459 }
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003460 deviceId = motionEntry.deviceId;
3461 eventTime = motionEntry.eventTime;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003462 } else {
3463 return; // Not a key or a motion
3464 }
3465
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003466 std::set<gui::Uid> interactionUids;
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07003467 std::unordered_set<sp<IBinder>, StrongPointerHash<IBinder>> newConnectionTokens;
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003468 std::vector<std::shared_ptr<Connection>> newConnections;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003469 for (const InputTarget& target : targets) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003470 if (target.flags.test(InputTarget::Flags::DISPATCH_AS_OUTSIDE)) {
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003471 continue; // Skip windows that receive ACTION_OUTSIDE
3472 }
3473
3474 sp<IBinder> token = target.inputChannel->getConnectionToken();
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003475 std::shared_ptr<Connection> connection = getConnectionLocked(token);
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003476 if (connection == nullptr) {
3477 continue;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003478 }
3479 newConnectionTokens.insert(std::move(token));
3480 newConnections.emplace_back(connection);
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003481 if (target.windowHandle) {
3482 interactionUids.emplace(target.windowHandle->getInfo()->ownerUid);
3483 }
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003484 }
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003485
3486 auto command = [this, deviceId, eventTime, uids = std::move(interactionUids)]()
3487 REQUIRES(mLock) {
3488 scoped_unlock unlock(mLock);
3489 mPolicy.notifyDeviceInteraction(deviceId, eventTime, uids);
3490 };
3491 postCommandLocked(std::move(command));
3492
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003493 if (newConnectionTokens == mInteractionConnectionTokens) {
3494 return; // no change
3495 }
3496 mInteractionConnectionTokens = newConnectionTokens;
3497
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003498 std::string targetList;
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003499 for (const std::shared_ptr<Connection>& connection : newConnections) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003500 targetList += connection->getWindowName() + ", ";
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003501 }
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003502 std::string message = "Interaction with: " + targetList;
3503 if (targetList.empty()) {
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003504 message += "<none>";
3505 }
3506 android_log_event_list(LOGTAG_INPUT_INTERACTION) << message << LOG_ID_EVENTS;
3507}
3508
chaviwfd6d3512019-03-25 13:23:49 -07003509void InputDispatcher::dispatchPointerDownOutsideFocus(uint32_t source, int32_t action,
Vishnu Nairad321cd2020-08-20 16:40:21 -07003510 const sp<IBinder>& token) {
chaviw8c9cf542019-03-25 13:02:48 -07003511 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
chaviwfd6d3512019-03-25 13:23:49 -07003512 uint32_t maskedSource = source & AINPUT_SOURCE_CLASS_MASK;
3513 if (maskedSource != AINPUT_SOURCE_CLASS_POINTER || maskedAction != AMOTION_EVENT_ACTION_DOWN) {
chaviw8c9cf542019-03-25 13:02:48 -07003514 return;
3515 }
3516
Vishnu Nairc519ff72021-01-21 08:23:08 -08003517 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07003518 if (focusedToken == token) {
3519 // ignore since token is focused
chaviw8c9cf542019-03-25 13:02:48 -07003520 return;
3521 }
3522
Prabir Pradhancef936d2021-07-21 16:17:52 +00003523 auto command = [this, token]() REQUIRES(mLock) {
3524 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00003525 mPolicy.onPointerDownOutsideFocus(token);
Prabir Pradhancef936d2021-07-21 16:17:52 +00003526 };
3527 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003528}
3529
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003530status_t InputDispatcher::publishMotionEvent(Connection& connection,
3531 DispatchEntry& dispatchEntry) const {
3532 const EventEntry& eventEntry = *(dispatchEntry.eventEntry);
3533 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
3534
3535 PointerCoords scaledCoords[MAX_POINTERS];
3536 const PointerCoords* usingCoords = motionEntry.pointerCoords;
3537
3538 // Set the X and Y offset and X and Y scale depending on the input source.
3539 if ((motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) &&
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003540 !(dispatchEntry.targetFlags.test(InputTarget::Flags::ZERO_COORDS))) {
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003541 float globalScaleFactor = dispatchEntry.globalScaleFactor;
3542 if (globalScaleFactor != 1.0f) {
3543 for (uint32_t i = 0; i < motionEntry.pointerCount; i++) {
3544 scaledCoords[i] = motionEntry.pointerCoords[i];
3545 // Don't apply window scale here since we don't want scale to affect raw
3546 // coordinates. The scale will be sent back to the client and applied
3547 // later when requesting relative coordinates.
Harry Cutts33476232023-01-30 19:57:29 +00003548 scaledCoords[i].scale(globalScaleFactor, /*windowXScale=*/1, /*windowYScale=*/1);
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003549 }
3550 usingCoords = scaledCoords;
3551 }
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003552 } else if (dispatchEntry.targetFlags.test(InputTarget::Flags::ZERO_COORDS)) {
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003553 // We don't want the dispatch target to know the coordinates
3554 for (uint32_t i = 0; i < motionEntry.pointerCount; i++) {
3555 scaledCoords[i].clear();
3556 }
3557 usingCoords = scaledCoords;
3558 }
3559
3560 std::array<uint8_t, 32> hmac = getSignature(motionEntry, dispatchEntry);
3561
3562 // Publish the motion event.
3563 return connection.inputPublisher
3564 .publishMotionEvent(dispatchEntry.seq, dispatchEntry.resolvedEventId,
3565 motionEntry.deviceId, motionEntry.source, motionEntry.displayId,
3566 std::move(hmac), dispatchEntry.resolvedAction,
3567 motionEntry.actionButton, dispatchEntry.resolvedFlags,
3568 motionEntry.edgeFlags, motionEntry.metaState,
3569 motionEntry.buttonState, motionEntry.classification,
3570 dispatchEntry.transform, motionEntry.xPrecision,
3571 motionEntry.yPrecision, motionEntry.xCursorPosition,
3572 motionEntry.yCursorPosition, dispatchEntry.rawTransform,
3573 motionEntry.downTime, motionEntry.eventTime,
3574 motionEntry.pointerCount, motionEntry.pointerProperties,
3575 usingCoords);
3576}
3577
Michael Wrightd02c5b62014-02-10 15:10:22 -08003578void InputDispatcher::startDispatchCycleLocked(nsecs_t currentTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003579 const std::shared_ptr<Connection>& connection) {
Prabir Pradhan2dac8b82023-09-06 01:11:51 +00003580 ATRACE_NAME_IF(ATRACE_ENABLED(),
3581 StringPrintf("startDispatchCycleLocked(inputChannel=%s)",
3582 connection->getInputChannelName().c_str()));
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003583 if (DEBUG_DISPATCH_CYCLE) {
3584 ALOGD("channel '%s' ~ startDispatchCycle", connection->getInputChannelName().c_str());
3585 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003586
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003587 while (connection->status == Connection::Status::NORMAL && !connection->outboundQueue.empty()) {
Prabir Pradhan8c90d782023-09-15 21:16:44 +00003588 std::unique_ptr<DispatchEntry>& dispatchEntry = connection->outboundQueue.front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003589 dispatchEntry->deliveryTime = currentTime;
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003590 const std::chrono::nanoseconds timeout = getDispatchingTimeoutLocked(connection);
Siarhei Vishniakou70622952020-07-30 11:17:23 -05003591 dispatchEntry->timeoutTime = currentTime + timeout.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003592
3593 // Publish the event.
3594 status_t status;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003595 const EventEntry& eventEntry = *(dispatchEntry->eventEntry);
3596 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003597 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003598 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
3599 std::array<uint8_t, 32> hmac = getSignature(keyEntry, *dispatchEntry);
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08003600 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07003601 LOG(INFO) << "Publishing " << *dispatchEntry << " to "
3602 << connection->getInputChannelName();
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08003603 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003604
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003605 // Publish the key event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003606 status = connection->inputPublisher
3607 .publishKeyEvent(dispatchEntry->seq,
3608 dispatchEntry->resolvedEventId, keyEntry.deviceId,
3609 keyEntry.source, keyEntry.displayId,
3610 std::move(hmac), dispatchEntry->resolvedAction,
3611 dispatchEntry->resolvedFlags, keyEntry.keyCode,
3612 keyEntry.scanCode, keyEntry.metaState,
3613 keyEntry.repeatCount, keyEntry.downTime,
3614 keyEntry.eventTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003615 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003616 }
3617
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003618 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08003619 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07003620 LOG(INFO) << "Publishing " << *dispatchEntry << " to "
3621 << connection->getInputChannelName();
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08003622 }
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003623 status = publishMotionEvent(*connection, *dispatchEntry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003624 break;
3625 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003626
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003627 case EventEntry::Type::FOCUS: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003628 const FocusEntry& focusEntry = static_cast<const FocusEntry&>(eventEntry);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003629 status = connection->inputPublisher.publishFocusEvent(dispatchEntry->seq,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003630 focusEntry.id,
Antonio Kantek3cfec7b2021-11-05 18:26:17 -07003631 focusEntry.hasFocus);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003632 break;
3633 }
3634
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003635 case EventEntry::Type::TOUCH_MODE_CHANGED: {
3636 const TouchModeEntry& touchModeEntry =
3637 static_cast<const TouchModeEntry&>(eventEntry);
3638 status = connection->inputPublisher
3639 .publishTouchModeEvent(dispatchEntry->seq, touchModeEntry.id,
3640 touchModeEntry.inTouchMode);
3641
3642 break;
3643 }
3644
Prabir Pradhan99987712020-11-10 18:43:05 -08003645 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
3646 const auto& captureEntry =
3647 static_cast<const PointerCaptureChangedEntry&>(eventEntry);
3648 status = connection->inputPublisher
3649 .publishCaptureEvent(dispatchEntry->seq, captureEntry.id,
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00003650 captureEntry.pointerCaptureRequest.enable);
Prabir Pradhan99987712020-11-10 18:43:05 -08003651 break;
3652 }
3653
arthurhungb89ccb02020-12-30 16:19:01 +08003654 case EventEntry::Type::DRAG: {
3655 const DragEntry& dragEntry = static_cast<const DragEntry&>(eventEntry);
3656 status = connection->inputPublisher.publishDragEvent(dispatchEntry->seq,
3657 dragEntry.id, dragEntry.x,
3658 dragEntry.y,
3659 dragEntry.isExiting);
3660 break;
3661 }
3662
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003663 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07003664 case EventEntry::Type::DEVICE_RESET:
3665 case EventEntry::Type::SENSOR: {
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003666 LOG_ALWAYS_FATAL("Should never start dispatch cycles for %s events",
Dominik Laskowski75788452021-02-09 18:51:25 -08003667 ftl::enum_string(eventEntry.type).c_str());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003668 return;
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003669 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003670 }
3671
3672 // Check the result.
3673 if (status) {
3674 if (status == WOULD_BLOCK) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003675 if (connection->waitQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003676 ALOGE("channel '%s' ~ Could not publish event because the pipe is full. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003677 "This is unexpected because the wait queue is empty, so the pipe "
3678 "should be empty and we shouldn't have any problems writing an "
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +00003679 "event to it, status=%s(%d)",
3680 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3681 status);
Harry Cutts33476232023-01-30 19:57:29 +00003682 abortBrokenDispatchCycleLocked(currentTime, connection, /*notify=*/true);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003683 } else {
3684 // Pipe is full and we are waiting for the app to finish process some events
3685 // before sending more events to it.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003686 if (DEBUG_DISPATCH_CYCLE) {
3687 ALOGD("channel '%s' ~ Could not publish event because the pipe is full, "
3688 "waiting for the application to catch up",
3689 connection->getInputChannelName().c_str());
3690 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003691 }
3692 } else {
3693 ALOGE("channel '%s' ~ Could not publish event due to an unexpected error, "
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +00003694 "status=%s(%d)",
3695 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3696 status);
Harry Cutts33476232023-01-30 19:57:29 +00003697 abortBrokenDispatchCycleLocked(currentTime, connection, /*notify=*/true);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003698 }
3699 return;
3700 }
3701
3702 // Re-enqueue the event on the wait queue.
Prabir Pradhan8c90d782023-09-15 21:16:44 +00003703 const nsecs_t timeoutTime = dispatchEntry->timeoutTime;
3704 connection->waitQueue.emplace_back(std::move(dispatchEntry));
3705 connection->outboundQueue.erase(connection->outboundQueue.begin());
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003706 traceOutboundQueueLength(*connection);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003707 if (connection->responsive) {
Prabir Pradhan8c90d782023-09-15 21:16:44 +00003708 mAnrTracker.insert(timeoutTime, connection->inputChannel->getConnectionToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003709 }
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003710 traceWaitQueueLength(*connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003711 }
3712}
3713
chaviw09c8d2d2020-08-24 15:48:26 -07003714std::array<uint8_t, 32> InputDispatcher::sign(const VerifiedInputEvent& event) const {
3715 size_t size;
3716 switch (event.type) {
3717 case VerifiedInputEvent::Type::KEY: {
3718 size = sizeof(VerifiedKeyEvent);
3719 break;
3720 }
3721 case VerifiedInputEvent::Type::MOTION: {
3722 size = sizeof(VerifiedMotionEvent);
3723 break;
3724 }
3725 }
3726 const uint8_t* start = reinterpret_cast<const uint8_t*>(&event);
3727 return mHmacKeyManager.sign(start, size);
3728}
3729
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003730const std::array<uint8_t, 32> InputDispatcher::getSignature(
3731 const MotionEntry& motionEntry, const DispatchEntry& dispatchEntry) const {
Siarhei Vishniakoubf880522023-05-01 11:03:22 -07003732 const int32_t actionMasked = MotionEvent::getActionMasked(dispatchEntry.resolvedAction);
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003733 if (actionMasked != AMOTION_EVENT_ACTION_UP && actionMasked != AMOTION_EVENT_ACTION_DOWN) {
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003734 // Only sign events up and down events as the purely move events
3735 // are tied to their up/down counterparts so signing would be redundant.
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003736 return INVALID_HMAC;
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003737 }
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003738
3739 VerifiedMotionEvent verifiedEvent =
3740 verifiedMotionEventFromMotionEntry(motionEntry, dispatchEntry.rawTransform);
3741 verifiedEvent.actionMasked = actionMasked;
3742 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_MOTION_EVENT_FLAGS;
3743 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003744}
3745
3746const std::array<uint8_t, 32> InputDispatcher::getSignature(
3747 const KeyEntry& keyEntry, const DispatchEntry& dispatchEntry) const {
3748 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEntry(keyEntry);
3749 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_KEY_EVENT_FLAGS;
3750 verifiedEvent.action = dispatchEntry.resolvedAction;
chaviw09c8d2d2020-08-24 15:48:26 -07003751 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003752}
3753
Michael Wrightd02c5b62014-02-10 15:10:22 -08003754void InputDispatcher::finishDispatchCycleLocked(nsecs_t currentTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003755 const std::shared_ptr<Connection>& connection,
3756 uint32_t seq, bool handled, nsecs_t consumeTime) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003757 if (DEBUG_DISPATCH_CYCLE) {
3758 ALOGD("channel '%s' ~ finishDispatchCycle - seq=%u, handled=%s",
3759 connection->getInputChannelName().c_str(), seq, toString(handled));
3760 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003761
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003762 if (connection->status == Connection::Status::BROKEN ||
3763 connection->status == Connection::Status::ZOMBIE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003764 return;
3765 }
3766
3767 // Notify other system components and prepare to start the next dispatch cycle.
Prabir Pradhancef936d2021-07-21 16:17:52 +00003768 auto command = [this, currentTime, connection, seq, handled, consumeTime]() REQUIRES(mLock) {
3769 doDispatchCycleFinishedCommand(currentTime, connection, seq, handled, consumeTime);
3770 };
3771 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003772}
3773
3774void InputDispatcher::abortBrokenDispatchCycleLocked(nsecs_t currentTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003775 const std::shared_ptr<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003776 bool notify) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003777 if (DEBUG_DISPATCH_CYCLE) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07003778 LOG(INFO) << "channel '" << connection->getInputChannelName() << "'~ " << __func__
3779 << " - notify=" << toString(notify);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003780 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003781
3782 // Clear the dispatch queues.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003783 drainDispatchQueue(connection->outboundQueue);
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003784 traceOutboundQueueLength(*connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003785 drainDispatchQueue(connection->waitQueue);
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003786 traceWaitQueueLength(*connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003787
3788 // The connection appears to be unrecoverably broken.
3789 // Ignore already broken or zombie connections.
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003790 if (connection->status == Connection::Status::NORMAL) {
3791 connection->status = Connection::Status::BROKEN;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003792
3793 if (notify) {
3794 // Notify other system components.
Prabir Pradhancef936d2021-07-21 16:17:52 +00003795 ALOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
3796 connection->getInputChannelName().c_str());
3797
3798 auto command = [this, connection]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00003799 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00003800 mPolicy.notifyInputChannelBroken(connection->inputChannel->getConnectionToken());
Prabir Pradhancef936d2021-07-21 16:17:52 +00003801 };
3802 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003803 }
3804 }
3805}
3806
Prabir Pradhan8c90d782023-09-15 21:16:44 +00003807void InputDispatcher::drainDispatchQueue(std::deque<std::unique_ptr<DispatchEntry>>& queue) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003808 while (!queue.empty()) {
Prabir Pradhan8c90d782023-09-15 21:16:44 +00003809 releaseDispatchEntry(std::move(queue.front()));
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003810 queue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003811 }
3812}
3813
Prabir Pradhan8c90d782023-09-15 21:16:44 +00003814void InputDispatcher::releaseDispatchEntry(std::unique_ptr<DispatchEntry> dispatchEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003815 if (dispatchEntry->hasForegroundTarget()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003816 decrementPendingForegroundDispatches(*(dispatchEntry->eventEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003817 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003818}
3819
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003820int InputDispatcher::handleReceiveCallback(int events, sp<IBinder> connectionToken) {
3821 std::scoped_lock _l(mLock);
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003822 std::shared_ptr<Connection> connection = getConnectionLocked(connectionToken);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003823 if (connection == nullptr) {
3824 ALOGW("Received looper callback for unknown input channel token %p. events=0x%x",
3825 connectionToken.get(), events);
3826 return 0; // remove the callback
3827 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003828
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003829 bool notify;
3830 if (!(events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP))) {
3831 if (!(events & ALOOPER_EVENT_INPUT)) {
3832 ALOGW("channel '%s' ~ Received spurious callback for unhandled poll event. "
3833 "events=0x%x",
3834 connection->getInputChannelName().c_str(), events);
3835 return 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003836 }
3837
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003838 nsecs_t currentTime = now();
3839 bool gotOne = false;
3840 status_t status = OK;
3841 for (;;) {
3842 Result<InputPublisher::ConsumerResponse> result =
3843 connection->inputPublisher.receiveConsumerResponse();
3844 if (!result.ok()) {
3845 status = result.error().code();
3846 break;
3847 }
3848
3849 if (std::holds_alternative<InputPublisher::Finished>(*result)) {
3850 const InputPublisher::Finished& finish =
3851 std::get<InputPublisher::Finished>(*result);
3852 finishDispatchCycleLocked(currentTime, connection, finish.seq, finish.handled,
3853 finish.consumeTime);
3854 } else if (std::holds_alternative<InputPublisher::Timeline>(*result)) {
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00003855 if (shouldReportMetricsForConnection(*connection)) {
3856 const InputPublisher::Timeline& timeline =
3857 std::get<InputPublisher::Timeline>(*result);
3858 mLatencyTracker
3859 .trackGraphicsLatency(timeline.inputEventId,
3860 connection->inputChannel->getConnectionToken(),
3861 std::move(timeline.graphicsTimeline));
3862 }
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003863 }
3864 gotOne = true;
3865 }
3866 if (gotOne) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00003867 runCommandsLockedInterruptable();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003868 if (status == WOULD_BLOCK) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003869 return 1;
3870 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003871 }
3872
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003873 notify = status != DEAD_OBJECT || !connection->monitor;
3874 if (notify) {
3875 ALOGE("channel '%s' ~ Failed to receive finished signal. status=%s(%d)",
3876 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3877 status);
3878 }
3879 } else {
3880 // Monitor channels are never explicitly unregistered.
3881 // We do it automatically when the remote endpoint is closed so don't warn about them.
3882 const bool stillHaveWindowHandle =
3883 getWindowHandleLocked(connection->inputChannel->getConnectionToken()) != nullptr;
3884 notify = !connection->monitor && stillHaveWindowHandle;
3885 if (notify) {
3886 ALOGW("channel '%s' ~ Consumer closed input channel or an error occurred. events=0x%x",
3887 connection->getInputChannelName().c_str(), events);
3888 }
3889 }
3890
3891 // Remove the channel.
3892 removeInputChannelLocked(connection->inputChannel->getConnectionToken(), notify);
3893 return 0; // remove the callback
Michael Wrightd02c5b62014-02-10 15:10:22 -08003894}
3895
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003896void InputDispatcher::synthesizeCancelationEventsForAllConnectionsLocked(
Michael Wrightd02c5b62014-02-10 15:10:22 -08003897 const CancelationOptions& options) {
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003898 for (const auto& [token, connection] : mConnectionsByToken) {
Siarhei Vishniakou2e2ea992020-12-15 02:57:19 +00003899 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003900 }
3901}
3902
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003903void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
Michael Wrightfa13dcf2015-06-12 13:25:11 +01003904 const CancelationOptions& options) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08003905 for (const auto& [_, monitors] : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003906 for (const Monitor& monitor : monitors) {
3907 synthesizeCancelationEventsForInputChannelLocked(monitor.inputChannel, options);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003908 }
Michael Wrightfa13dcf2015-06-12 13:25:11 +01003909 }
3910}
3911
Michael Wrightd02c5b62014-02-10 15:10:22 -08003912void InputDispatcher::synthesizeCancelationEventsForInputChannelLocked(
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05003913 const std::shared_ptr<InputChannel>& channel, const CancelationOptions& options) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003914 std::shared_ptr<Connection> connection = getConnectionLocked(channel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003915 if (connection == nullptr) {
3916 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003917 }
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003918
3919 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003920}
3921
3922void InputDispatcher::synthesizeCancelationEventsForConnectionLocked(
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003923 const std::shared_ptr<Connection>& connection, const CancelationOptions& options) {
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003924 if (connection->status == Connection::Status::BROKEN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003925 return;
3926 }
3927
3928 nsecs_t currentTime = now();
3929
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003930 std::vector<std::unique_ptr<EventEntry>> cancelationEvents =
Siarhei Vishniakou00fca7c2019-10-29 13:05:57 -07003931 connection->inputState.synthesizeCancelationEvents(currentTime, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003932
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003933 if (cancelationEvents.empty()) {
3934 return;
3935 }
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003936 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
3937 ALOGD("channel '%s' ~ Synthesized %zu cancelation events to bring channel back in sync "
Siarhei Vishniakou2e3e4432023-02-09 18:34:11 -08003938 "with reality: %s, mode=%s.",
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003939 connection->getInputChannelName().c_str(), cancelationEvents.size(), options.reason,
Siarhei Vishniakou2e3e4432023-02-09 18:34:11 -08003940 ftl::enum_string(options.mode).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003941 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08003942
Arthur Hungb3307ee2021-10-14 10:57:37 +00003943 std::string reason = std::string("reason=").append(options.reason);
3944 android_log_event_list(LOGTAG_INPUT_CANCEL)
3945 << connection->getInputChannelName().c_str() << reason << LOG_ID_EVENTS;
3946
Hu Guo771a7692023-09-17 20:51:08 +08003947 sp<WindowInfoHandle> windowHandle;
3948 if (options.displayId) {
3949 windowHandle = getWindowHandleLocked(connection->inputChannel->getConnectionToken(),
3950 options.displayId.value());
3951 } else {
3952 windowHandle = getWindowHandleLocked(connection->inputChannel->getConnectionToken());
3953 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08003954
hongzuo liu95785e22022-09-06 02:51:35 +00003955 const bool wasEmpty = connection->outboundQueue.empty();
3956
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003957 for (size_t i = 0; i < cancelationEvents.size(); i++) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003958 std::unique_ptr<EventEntry> cancelationEventEntry = std::move(cancelationEvents[i]);
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00003959 std::vector<InputTarget> targets{};
3960 // The target to use if we don't find a window associated with the channel.
3961 const InputTarget fallbackTarget{.inputChannel = connection->inputChannel,
3962 .flags = InputTarget::Flags::DISPATCH_AS_IS};
3963
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003964 switch (cancelationEventEntry->type) {
3965 case EventEntry::Type::KEY: {
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00003966 const auto& keyEntry = static_cast<const KeyEntry&>(*cancelationEventEntry);
3967 if (windowHandle != nullptr) {
3968 addWindowTargetLocked(windowHandle, InputTarget::Flags::DISPATCH_AS_IS,
3969 /*pointerIds=*/{}, keyEntry.downTime, targets);
3970 } else {
3971 targets.emplace_back(fallbackTarget);
3972 }
3973 logOutboundKeyDetails("cancel - ", keyEntry);
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003974 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003975 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003976 case EventEntry::Type::MOTION: {
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00003977 const auto& motionEntry = static_cast<const MotionEntry&>(*cancelationEventEntry);
3978 if (windowHandle != nullptr) {
3979 std::bitset<MAX_POINTER_ID + 1> pointerIds;
3980 for (uint32_t pointerIndex = 0; pointerIndex < motionEntry.pointerCount;
3981 pointerIndex++) {
3982 pointerIds.set(motionEntry.pointerProperties[pointerIndex].id);
3983 }
3984 addWindowTargetLocked(windowHandle, InputTarget::Flags::DISPATCH_AS_IS,
3985 pointerIds, motionEntry.downTime, targets);
3986 } else {
3987 targets.emplace_back(fallbackTarget);
3988 const auto it = mDisplayInfos.find(motionEntry.displayId);
3989 if (it != mDisplayInfos.end()) {
3990 targets.back().displayTransform = it->second.transform;
3991 targets.back().setDefaultPointerTransform(it->second.transform);
3992 }
3993 }
3994 logOutboundMotionDetails("cancel - ", motionEntry);
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003995 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003996 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003997 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003998 case EventEntry::Type::TOUCH_MODE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08003999 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
4000 case EventEntry::Type::DRAG: {
Prabir Pradhan99987712020-11-10 18:43:05 -08004001 LOG_ALWAYS_FATAL("Canceling %s events is not supported",
Dominik Laskowski75788452021-02-09 18:51:25 -08004002 ftl::enum_string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004003 break;
4004 }
4005 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07004006 case EventEntry::Type::DEVICE_RESET:
4007 case EventEntry::Type::SENSOR: {
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004008 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Dominik Laskowski75788452021-02-09 18:51:25 -08004009 ftl::enum_string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004010 break;
4011 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004012 }
4013
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00004014 if (targets.size() != 1) LOG(FATAL) << __func__ << ": InputTarget not created";
4015 enqueueDispatchEntryLocked(connection, std::move(cancelationEventEntry), targets[0],
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08004016 InputTarget::Flags::DISPATCH_AS_IS);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004017 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004018
hongzuo liu95785e22022-09-06 02:51:35 +00004019 // If the outbound queue was previously empty, start the dispatch cycle going.
4020 if (wasEmpty && !connection->outboundQueue.empty()) {
4021 startDispatchCycleLocked(currentTime, connection);
4022 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004023}
4024
Svet Ganov5d3bc372020-01-26 23:11:07 -08004025void InputDispatcher::synthesizePointerDownEventsForConnectionLocked(
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07004026 const nsecs_t downTime, const std::shared_ptr<Connection>& connection,
Arthur Hungc539dbb2022-12-08 07:45:36 +00004027 ftl::Flags<InputTarget::Flags> targetFlags) {
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08004028 if (connection->status == Connection::Status::BROKEN) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08004029 return;
4030 }
4031
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004032 std::vector<std::unique_ptr<EventEntry>> downEvents =
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00004033 connection->inputState.synthesizePointerDownEvents(downTime);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004034
4035 if (downEvents.empty()) {
4036 return;
4037 }
4038
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004039 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08004040 ALOGD("channel '%s' ~ Synthesized %zu down events to ensure consistent event stream.",
4041 connection->getInputChannelName().c_str(), downEvents.size());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004042 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08004043
chaviw98318de2021-05-19 16:45:23 -05004044 sp<WindowInfoHandle> windowHandle =
Svet Ganov5d3bc372020-01-26 23:11:07 -08004045 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
Svet Ganov5d3bc372020-01-26 23:11:07 -08004046
hongzuo liu95785e22022-09-06 02:51:35 +00004047 const bool wasEmpty = connection->outboundQueue.empty();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004048 for (std::unique_ptr<EventEntry>& downEventEntry : downEvents) {
Prabir Pradhan1c29a092023-09-21 10:29:29 +00004049 std::vector<InputTarget> targets{};
Svet Ganov5d3bc372020-01-26 23:11:07 -08004050 switch (downEventEntry->type) {
4051 case EventEntry::Type::MOTION: {
Prabir Pradhan1c29a092023-09-21 10:29:29 +00004052 const auto& motionEntry = static_cast<const MotionEntry&>(*downEventEntry);
4053 if (windowHandle != nullptr) {
4054 std::bitset<MAX_POINTER_ID + 1> pointerIds;
4055 for (uint32_t pointerIndex = 0; pointerIndex < motionEntry.pointerCount;
4056 pointerIndex++) {
4057 pointerIds.set(motionEntry.pointerProperties[pointerIndex].id);
4058 }
4059 addWindowTargetLocked(windowHandle, targetFlags, pointerIds,
4060 motionEntry.downTime, targets);
4061 } else {
4062 targets.emplace_back(InputTarget{.inputChannel = connection->inputChannel,
4063 .flags = targetFlags});
4064 const auto it = mDisplayInfos.find(motionEntry.displayId);
4065 if (it != mDisplayInfos.end()) {
4066 targets.back().displayTransform = it->second.transform;
4067 targets.back().setDefaultPointerTransform(it->second.transform);
4068 }
4069 }
4070 logOutboundMotionDetails("down - ", motionEntry);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004071 break;
4072 }
4073
4074 case EventEntry::Type::KEY:
4075 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07004076 case EventEntry::Type::TOUCH_MODE_CHANGED:
Svet Ganov5d3bc372020-01-26 23:11:07 -08004077 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08004078 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07004079 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08004080 case EventEntry::Type::SENSOR:
4081 case EventEntry::Type::DRAG: {
Svet Ganov5d3bc372020-01-26 23:11:07 -08004082 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Dominik Laskowski75788452021-02-09 18:51:25 -08004083 ftl::enum_string(downEventEntry->type).c_str());
Svet Ganov5d3bc372020-01-26 23:11:07 -08004084 break;
4085 }
4086 }
4087
Prabir Pradhan1c29a092023-09-21 10:29:29 +00004088 if (targets.size() != 1) LOG(FATAL) << __func__ << ": InputTarget not created";
4089 enqueueDispatchEntryLocked(connection, std::move(downEventEntry), targets[0],
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08004090 InputTarget::Flags::DISPATCH_AS_IS);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004091 }
4092
hongzuo liu95785e22022-09-06 02:51:35 +00004093 // If the outbound queue was previously empty, start the dispatch cycle going.
4094 if (wasEmpty && !connection->outboundQueue.empty()) {
4095 startDispatchCycleLocked(downTime, connection);
4096 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08004097}
4098
Arthur Hungc539dbb2022-12-08 07:45:36 +00004099void InputDispatcher::synthesizeCancelationEventsForWindowLocked(
4100 const sp<WindowInfoHandle>& windowHandle, const CancelationOptions& options) {
4101 if (windowHandle != nullptr) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07004102 std::shared_ptr<Connection> wallpaperConnection =
4103 getConnectionLocked(windowHandle->getToken());
Arthur Hungc539dbb2022-12-08 07:45:36 +00004104 if (wallpaperConnection != nullptr) {
4105 synthesizeCancelationEventsForConnectionLocked(wallpaperConnection, options);
4106 }
4107 }
4108}
4109
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004110std::unique_ptr<MotionEntry> InputDispatcher::splitMotionEvent(
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08004111 const MotionEntry& originalMotionEntry, std::bitset<MAX_POINTER_ID + 1> pointerIds,
4112 nsecs_t splitDownTime) {
4113 ALOG_ASSERT(pointerIds.any());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004114
4115 uint32_t splitPointerIndexMap[MAX_POINTERS];
4116 PointerProperties splitPointerProperties[MAX_POINTERS];
4117 PointerCoords splitPointerCoords[MAX_POINTERS];
4118
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07004119 uint32_t originalPointerCount = originalMotionEntry.pointerCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004120 uint32_t splitPointerCount = 0;
4121
4122 for (uint32_t originalPointerIndex = 0; originalPointerIndex < originalPointerCount;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004123 originalPointerIndex++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004124 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07004125 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08004126 uint32_t pointerId = uint32_t(pointerProperties.id);
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08004127 if (pointerIds.test(pointerId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004128 splitPointerIndexMap[splitPointerCount] = originalPointerIndex;
Siarhei Vishniakou73e6d372023-07-06 18:07:21 -07004129 splitPointerProperties[splitPointerCount] = pointerProperties;
4130 splitPointerCoords[splitPointerCount] =
4131 originalMotionEntry.pointerCoords[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08004132 splitPointerCount += 1;
4133 }
4134 }
4135
4136 if (splitPointerCount != pointerIds.count()) {
4137 // This is bad. We are missing some of the pointers that we expected to deliver.
4138 // Most likely this indicates that we received an ACTION_MOVE events that has
4139 // different pointer ids than we expected based on the previous ACTION_DOWN
4140 // or ACTION_POINTER_DOWN events that caused us to decide to split the pointers
4141 // in this way.
4142 ALOGW("Dropping split motion event because the pointer count is %d but "
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08004143 "we expected there to be %zu pointers. This probably means we received "
Siarhei Vishniakou16e4fa02023-02-16 17:48:56 -08004144 "a broken sequence of pointer ids from the input device: %s",
4145 splitPointerCount, pointerIds.count(), originalMotionEntry.getDescription().c_str());
Yi Kong9b14ac62018-07-17 13:48:38 -07004146 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004147 }
4148
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07004149 int32_t action = originalMotionEntry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004150 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004151 if (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN ||
4152 maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
Siarhei Vishniakou5b9766d2023-07-18 14:06:29 -07004153 int32_t originalPointerIndex = MotionEvent::getActionIndex(action);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004154 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07004155 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08004156 uint32_t pointerId = uint32_t(pointerProperties.id);
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08004157 if (pointerIds.test(pointerId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004158 if (pointerIds.count() == 1) {
4159 // The first/last pointer went down/up.
4160 action = maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004161 ? AMOTION_EVENT_ACTION_DOWN
arthurhungea3f4fc2020-12-21 23:18:53 +08004162 : (originalMotionEntry.flags & AMOTION_EVENT_FLAG_CANCELED) != 0
4163 ? AMOTION_EVENT_ACTION_CANCEL
4164 : AMOTION_EVENT_ACTION_UP;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004165 } else {
4166 // A secondary pointer went down/up.
4167 uint32_t splitPointerIndex = 0;
4168 while (pointerId != uint32_t(splitPointerProperties[splitPointerIndex].id)) {
4169 splitPointerIndex += 1;
4170 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004171 action = maskedAction |
4172 (splitPointerIndex << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004173 }
4174 } else {
4175 // An unrelated pointer changed.
4176 action = AMOTION_EVENT_ACTION_MOVE;
4177 }
4178 }
4179
Siarhei Vishniakou59e302b2023-06-05 08:04:53 -07004180 if (action == AMOTION_EVENT_ACTION_DOWN && splitDownTime != originalMotionEntry.eventTime) {
4181 logDispatchStateLocked();
4182 LOG_ALWAYS_FATAL("Split motion event has mismatching downTime and eventTime for "
4183 "ACTION_DOWN, motionEntry=%s, splitDownTime=%" PRId64,
4184 originalMotionEntry.getDescription().c_str(), splitDownTime);
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00004185 }
4186
Garfield Tanff1f1bb2020-01-28 13:24:04 -08004187 int32_t newId = mIdGenerator.nextId();
Prabir Pradhan2dac8b82023-09-06 01:11:51 +00004188 ATRACE_NAME_IF(ATRACE_ENABLED(),
4189 StringPrintf("Split MotionEvent(id=0x%" PRIx32 ") to MotionEvent(id=0x%" PRIx32
4190 ").",
4191 originalMotionEntry.id, newId));
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004192 std::unique_ptr<MotionEntry> splitMotionEntry =
4193 std::make_unique<MotionEntry>(newId, originalMotionEntry.eventTime,
4194 originalMotionEntry.deviceId, originalMotionEntry.source,
4195 originalMotionEntry.displayId,
4196 originalMotionEntry.policyFlags, action,
4197 originalMotionEntry.actionButton,
4198 originalMotionEntry.flags, originalMotionEntry.metaState,
4199 originalMotionEntry.buttonState,
4200 originalMotionEntry.classification,
4201 originalMotionEntry.edgeFlags,
4202 originalMotionEntry.xPrecision,
4203 originalMotionEntry.yPrecision,
4204 originalMotionEntry.xCursorPosition,
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00004205 originalMotionEntry.yCursorPosition, splitDownTime,
4206 splitPointerCount, splitPointerProperties,
4207 splitPointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004208
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07004209 if (originalMotionEntry.injectionState) {
4210 splitMotionEntry->injectionState = originalMotionEntry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004211 splitMotionEntry->injectionState->refCount += 1;
4212 }
4213
4214 return splitMotionEntry;
4215}
4216
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004217void InputDispatcher::notifyConfigurationChanged(const NotifyConfigurationChangedArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004218 if (debugInboundEventDetails()) {
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004219 ALOGD("notifyConfigurationChanged - eventTime=%" PRId64, args.eventTime);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004220 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004221
Antonio Kantekf16f2832021-09-28 04:39:20 +00004222 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004223 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004224 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004225
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004226 std::unique_ptr<ConfigurationChangedEntry> newEntry =
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004227 std::make_unique<ConfigurationChangedEntry>(args.id, args.eventTime);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004228 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004229 } // release lock
4230
4231 if (needWake) {
4232 mLooper->wake();
4233 }
4234}
4235
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004236void InputDispatcher::notifyKey(const NotifyKeyArgs& args) {
Prabir Pradhan96282b02023-02-24 22:36:17 +00004237 ALOGD_IF(debugInboundEventDetails(),
4238 "notifyKey - id=%" PRIx32 ", eventTime=%" PRId64
4239 ", deviceId=%d, source=%s, displayId=%" PRId32
4240 "policyFlags=0x%x, action=%s, flags=0x%x, keyCode=%s, scanCode=0x%x, metaState=0x%x, "
4241 "downTime=%" PRId64,
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004242 args.id, args.eventTime, args.deviceId, inputEventSourceToString(args.source).c_str(),
4243 args.displayId, args.policyFlags, KeyEvent::actionToString(args.action), args.flags,
4244 KeyEvent::getLabel(args.keyCode), args.scanCode, args.metaState, args.downTime);
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004245 Result<void> keyCheck = validateKeyEvent(args.action);
4246 if (!keyCheck.ok()) {
4247 LOG(ERROR) << "invalid key event: " << keyCheck.error();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004248 return;
4249 }
4250
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004251 uint32_t policyFlags = args.policyFlags;
4252 int32_t flags = args.flags;
4253 int32_t metaState = args.metaState;
Siarhei Vishniakou622bd322018-10-29 18:02:27 -07004254 // InputDispatcher tracks and generates key repeats on behalf of
4255 // whatever notifies it, so repeatCount should always be set to 0
4256 constexpr int32_t repeatCount = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004257 if ((policyFlags & POLICY_FLAG_VIRTUAL) || (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY)) {
4258 policyFlags |= POLICY_FLAG_VIRTUAL;
4259 flags |= AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
4260 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004261 if (policyFlags & POLICY_FLAG_FUNCTION) {
4262 metaState |= AMETA_FUNCTION_ON;
4263 }
4264
4265 policyFlags |= POLICY_FLAG_TRUSTED;
4266
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004267 int32_t keyCode = args.keyCode;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004268 KeyEvent event;
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004269 event.initialize(args.id, args.deviceId, args.source, args.displayId, INVALID_HMAC, args.action,
4270 flags, keyCode, args.scanCode, metaState, repeatCount, args.downTime,
4271 args.eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004272
Michael Wright2b3c3302018-03-02 17:19:13 +00004273 android::base::Timer t;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004274 mPolicy.interceptKeyBeforeQueueing(event, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00004275 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4276 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004277 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00004278 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004279
Antonio Kantekf16f2832021-09-28 04:39:20 +00004280 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004281 { // acquire lock
4282 mLock.lock();
4283
4284 if (shouldSendKeyToInputFilterLocked(args)) {
4285 mLock.unlock();
4286
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004287 policyFlags |= POLICY_FLAG_FILTERED;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004288 if (!mPolicy.filterInputEvent(event, policyFlags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004289 return; // event was consumed by the filter
4290 }
4291
4292 mLock.lock();
4293 }
4294
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004295 std::unique_ptr<KeyEntry> newEntry =
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004296 std::make_unique<KeyEntry>(args.id, args.eventTime, args.deviceId, args.source,
4297 args.displayId, policyFlags, args.action, flags, keyCode,
4298 args.scanCode, metaState, repeatCount, args.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004299
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004300 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004301 mLock.unlock();
4302 } // release lock
4303
4304 if (needWake) {
4305 mLooper->wake();
4306 }
4307}
4308
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004309bool InputDispatcher::shouldSendKeyToInputFilterLocked(const NotifyKeyArgs& args) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004310 return mInputFilterEnabled;
4311}
4312
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004313void InputDispatcher::notifyMotion(const NotifyMotionArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004314 if (debugInboundEventDetails()) {
Prabir Pradhan96282b02023-02-24 22:36:17 +00004315 ALOGD("notifyMotion - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=%s, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004316 "displayId=%" PRId32 ", policyFlags=0x%x, "
Siarhei Vishniakou6ebd0692022-10-20 15:05:45 -07004317 "action=%s, actionButton=0x%x, flags=0x%x, metaState=0x%x, buttonState=0x%x, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004318 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, xCursorPosition=%f, "
4319 "yCursorPosition=%f, downTime=%" PRId64,
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004320 args.id, args.eventTime, args.deviceId, inputEventSourceToString(args.source).c_str(),
4321 args.displayId, args.policyFlags, MotionEvent::actionToString(args.action).c_str(),
4322 args.actionButton, args.flags, args.metaState, args.buttonState, args.edgeFlags,
4323 args.xPrecision, args.yPrecision, args.xCursorPosition, args.yCursorPosition,
4324 args.downTime);
Siarhei Vishniakou3218fc02023-06-15 20:41:02 -07004325 for (uint32_t i = 0; i < args.getPointerCount(); i++) {
Prabir Pradhan96282b02023-02-24 22:36:17 +00004326 ALOGD(" Pointer %d: id=%d, toolType=%s, x=%f, y=%f, pressure=%f, size=%f, "
4327 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, orientation=%f",
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004328 i, args.pointerProperties[i].id,
4329 ftl::enum_string(args.pointerProperties[i].toolType).c_str(),
4330 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
4331 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
4332 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
4333 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
4334 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
4335 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
4336 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
4337 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
4338 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004339 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004340 }
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004341
Siarhei Vishniakou3218fc02023-06-15 20:41:02 -07004342 Result<void> motionCheck =
4343 validateMotionEvent(args.action, args.actionButton, args.getPointerCount(),
4344 args.pointerProperties.data());
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004345 if (!motionCheck.ok()) {
4346 LOG(FATAL) << "Invalid event: " << args.dump() << "; reason: " << motionCheck.error();
4347 return;
4348 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004349
Siarhei Vishniakou5c02a712023-05-15 15:45:02 -07004350 if (DEBUG_VERIFY_EVENTS) {
4351 auto [it, _] =
4352 mVerifiersByDisplay.try_emplace(args.displayId,
4353 StringPrintf("display %" PRId32, args.displayId));
4354 Result<void> result =
Siarhei Vishniakou2d151ac2023-09-19 13:30:24 -07004355 it->second.processMovement(args.deviceId, args.source, args.action,
4356 args.getPointerCount(), args.pointerProperties.data(),
4357 args.pointerCoords.data(), args.flags);
Siarhei Vishniakou5c02a712023-05-15 15:45:02 -07004358 if (!result.ok()) {
4359 LOG(FATAL) << "Bad stream: " << result.error() << " caused by " << args.dump();
4360 }
4361 }
4362
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004363 uint32_t policyFlags = args.policyFlags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004364 policyFlags |= POLICY_FLAG_TRUSTED;
Michael Wright2b3c3302018-03-02 17:19:13 +00004365
4366 android::base::Timer t;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004367 mPolicy.interceptMotionBeforeQueueing(args.displayId, args.eventTime, policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00004368 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4369 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004370 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00004371 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004372
Antonio Kantekf16f2832021-09-28 04:39:20 +00004373 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004374 { // acquire lock
4375 mLock.lock();
Siarhei Vishniakou5bf25d92023-02-08 15:43:38 -08004376 if (!(policyFlags & POLICY_FLAG_PASS_TO_USER)) {
4377 // Set the flag anyway if we already have an ongoing gesture. That would allow us to
4378 // complete the processing of the current stroke.
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004379 const auto touchStateIt = mTouchStatesByDisplay.find(args.displayId);
Siarhei Vishniakou5bf25d92023-02-08 15:43:38 -08004380 if (touchStateIt != mTouchStatesByDisplay.end()) {
4381 const TouchState& touchState = touchStateIt->second;
Siarhei Vishniakou45504fe2023-05-05 16:05:10 -07004382 if (touchState.hasTouchingPointers(args.deviceId)) {
Siarhei Vishniakou5bf25d92023-02-08 15:43:38 -08004383 policyFlags |= POLICY_FLAG_PASS_TO_USER;
4384 }
4385 }
4386 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004387
4388 if (shouldSendMotionToInputFilterLocked(args)) {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004389 ui::Transform displayTransform;
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004390 if (const auto it = mDisplayInfos.find(args.displayId); it != mDisplayInfos.end()) {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004391 displayTransform = it->second.transform;
4392 }
4393
Michael Wrightd02c5b62014-02-10 15:10:22 -08004394 mLock.unlock();
4395
4396 MotionEvent event;
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004397 event.initialize(args.id, args.deviceId, args.source, args.displayId, INVALID_HMAC,
4398 args.action, args.actionButton, args.flags, args.edgeFlags,
4399 args.metaState, args.buttonState, args.classification,
4400 displayTransform, args.xPrecision, args.yPrecision,
4401 args.xCursorPosition, args.yCursorPosition, displayTransform,
Siarhei Vishniakou3218fc02023-06-15 20:41:02 -07004402 args.downTime, args.eventTime, args.getPointerCount(),
4403 args.pointerProperties.data(), args.pointerCoords.data());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004404
4405 policyFlags |= POLICY_FLAG_FILTERED;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004406 if (!mPolicy.filterInputEvent(event, policyFlags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004407 return; // event was consumed by the filter
4408 }
4409
4410 mLock.lock();
4411 }
4412
4413 // Just enqueue a new motion event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004414 std::unique_ptr<MotionEntry> newEntry =
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004415 std::make_unique<MotionEntry>(args.id, args.eventTime, args.deviceId, args.source,
4416 args.displayId, policyFlags, args.action,
4417 args.actionButton, args.flags, args.metaState,
4418 args.buttonState, args.classification, args.edgeFlags,
4419 args.xPrecision, args.yPrecision,
4420 args.xCursorPosition, args.yCursorPosition,
Siarhei Vishniakou3218fc02023-06-15 20:41:02 -07004421 args.downTime, args.getPointerCount(),
4422 args.pointerProperties.data(),
4423 args.pointerCoords.data());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004424
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004425 if (args.id != android::os::IInputConstants::INVALID_INPUT_EVENT_ID &&
4426 IdGenerator::getSource(args.id) == IdGenerator::Source::INPUT_READER &&
Siarhei Vishniakou363e7292021-07-09 03:22:42 +00004427 !mInputFilterEnabled) {
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004428 const bool isDown = args.action == AMOTION_EVENT_ACTION_DOWN;
4429 mLatencyTracker.trackListener(args.id, isDown, args.eventTime, args.readTime);
Siarhei Vishniakou363e7292021-07-09 03:22:42 +00004430 }
4431
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004432 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004433 mLock.unlock();
4434 } // release lock
4435
4436 if (needWake) {
4437 mLooper->wake();
4438 }
4439}
4440
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004441void InputDispatcher::notifySensor(const NotifySensorArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004442 if (debugInboundEventDetails()) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004443 ALOGD("notifySensor - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=0x%x, "
4444 " sensorType=%s",
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004445 args.id, args.eventTime, args.deviceId, args.source,
4446 ftl::enum_string(args.sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004447 }
Chris Yef59a2f42020-10-16 12:55:26 -07004448
Antonio Kantekf16f2832021-09-28 04:39:20 +00004449 bool needWake = false;
Chris Yef59a2f42020-10-16 12:55:26 -07004450 { // acquire lock
4451 mLock.lock();
4452
4453 // Just enqueue a new sensor event.
4454 std::unique_ptr<SensorEntry> newEntry =
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004455 std::make_unique<SensorEntry>(args.id, args.eventTime, args.deviceId, args.source,
4456 /* policyFlags=*/0, args.hwTimestamp, args.sensorType,
4457 args.accuracy, args.accuracyChanged, args.values);
Chris Yef59a2f42020-10-16 12:55:26 -07004458
4459 needWake = enqueueInboundEventLocked(std::move(newEntry));
4460 mLock.unlock();
4461 } // release lock
4462
4463 if (needWake) {
4464 mLooper->wake();
4465 }
4466}
4467
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004468void InputDispatcher::notifyVibratorState(const NotifyVibratorStateArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004469 if (debugInboundEventDetails()) {
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004470 ALOGD("notifyVibratorState - eventTime=%" PRId64 ", device=%d, isOn=%d", args.eventTime,
4471 args.deviceId, args.isOn);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004472 }
Prabir Pradhana41d2442023-04-20 21:30:40 +00004473 mPolicy.notifyVibratorState(args.deviceId, args.isOn);
Chris Yefb552902021-02-03 17:18:37 -08004474}
4475
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004476bool InputDispatcher::shouldSendMotionToInputFilterLocked(const NotifyMotionArgs& args) {
Jackal Guof9696682018-10-05 12:23:23 +08004477 return mInputFilterEnabled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004478}
4479
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004480void InputDispatcher::notifySwitch(const NotifySwitchArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004481 if (debugInboundEventDetails()) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004482 ALOGD("notifySwitch - eventTime=%" PRId64 ", policyFlags=0x%x, switchValues=0x%08x, "
4483 "switchMask=0x%08x",
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004484 args.eventTime, args.policyFlags, args.switchValues, args.switchMask);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004485 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004486
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004487 uint32_t policyFlags = args.policyFlags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004488 policyFlags |= POLICY_FLAG_TRUSTED;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004489 mPolicy.notifySwitch(args.eventTime, args.switchValues, args.switchMask, policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004490}
4491
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004492void InputDispatcher::notifyDeviceReset(const NotifyDeviceResetArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004493 if (debugInboundEventDetails()) {
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004494 ALOGD("notifyDeviceReset - eventTime=%" PRId64 ", deviceId=%d", args.eventTime,
4495 args.deviceId);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004496 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004497
Antonio Kantekf16f2832021-09-28 04:39:20 +00004498 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004499 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004500 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004501
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004502 std::unique_ptr<DeviceResetEntry> newEntry =
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004503 std::make_unique<DeviceResetEntry>(args.id, args.eventTime, args.deviceId);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004504 needWake = enqueueInboundEventLocked(std::move(newEntry));
Siarhei Vishniakou1160ecd2023-06-28 15:57:47 -07004505
4506 for (auto& [_, verifier] : mVerifiersByDisplay) {
4507 verifier.resetDevice(args.deviceId);
4508 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004509 } // release lock
4510
4511 if (needWake) {
4512 mLooper->wake();
4513 }
4514}
4515
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004516void InputDispatcher::notifyPointerCaptureChanged(const NotifyPointerCaptureChangedArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004517 if (debugInboundEventDetails()) {
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004518 ALOGD("notifyPointerCaptureChanged - eventTime=%" PRId64 ", enabled=%s", args.eventTime,
4519 args.request.enable ? "true" : "false");
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004520 }
Prabir Pradhan7e186182020-11-10 13:56:45 -08004521
Antonio Kantekf16f2832021-09-28 04:39:20 +00004522 bool needWake = false;
Prabir Pradhan99987712020-11-10 18:43:05 -08004523 { // acquire lock
4524 std::scoped_lock _l(mLock);
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004525 auto entry =
4526 std::make_unique<PointerCaptureChangedEntry>(args.id, args.eventTime, args.request);
Prabir Pradhan99987712020-11-10 18:43:05 -08004527 needWake = enqueueInboundEventLocked(std::move(entry));
4528 } // release lock
4529
4530 if (needWake) {
4531 mLooper->wake();
4532 }
Prabir Pradhan7e186182020-11-10 13:56:45 -08004533}
4534
Prabir Pradhan5735a322022-04-11 17:23:34 +00004535InputEventInjectionResult InputDispatcher::injectInputEvent(const InputEvent* event,
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00004536 std::optional<gui::Uid> targetUid,
Prabir Pradhan5735a322022-04-11 17:23:34 +00004537 InputEventInjectionSync syncMode,
4538 std::chrono::milliseconds timeout,
4539 uint32_t policyFlags) {
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004540 Result<void> eventValidation = validateInputEvent(*event);
4541 if (!eventValidation.ok()) {
4542 LOG(INFO) << "Injection failed: invalid event: " << eventValidation.error();
4543 return InputEventInjectionResult::FAILED;
4544 }
4545
Prabir Pradhan65613802023-02-22 23:36:58 +00004546 if (debugInboundEventDetails()) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07004547 LOG(INFO) << __func__ << ": targetUid=" << toString(targetUid, &uidString)
4548 << ", syncMode=" << ftl::enum_string(syncMode) << ", timeout=" << timeout.count()
4549 << "ms, policyFlags=0x" << std::hex << policyFlags << std::dec
4550 << ", event=" << *event;
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004551 }
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07004552 nsecs_t endTime = now() + std::chrono::duration_cast<std::chrono::nanoseconds>(timeout).count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004553
Prabir Pradhan5735a322022-04-11 17:23:34 +00004554 policyFlags |= POLICY_FLAG_INJECTED | POLICY_FLAG_TRUSTED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004555
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004556 // For all injected events, set device id = VIRTUAL_KEYBOARD_ID. The only exception is events
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004557 // that have gone through the InputFilter. If the event passed through the InputFilter, assign
4558 // the provided device id. If the InputFilter is accessibility, and it modifies or synthesizes
4559 // the injected event, it is responsible for setting POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY.
4560 // For those events, we will set FLAG_IS_ACCESSIBILITY_EVENT to allow apps to distinguish them
4561 // from events that originate from actual hardware.
Siarhei Vishniakouf4043212023-09-18 19:33:03 -07004562 DeviceId resolvedDeviceId = VIRTUAL_KEYBOARD_ID;
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004563 if (policyFlags & POLICY_FLAG_FILTERED) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004564 resolvedDeviceId = event->getDeviceId();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004565 }
4566
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004567 std::queue<std::unique_ptr<EventEntry>> injectedEntries;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004568 switch (event->getType()) {
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004569 case InputEventType::KEY: {
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004570 const KeyEvent& incomingKey = static_cast<const KeyEvent&>(*event);
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004571 const int32_t action = incomingKey.getAction();
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004572 int32_t flags = incomingKey.getFlags();
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004573 if (policyFlags & POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY) {
4574 flags |= AKEY_EVENT_FLAG_IS_ACCESSIBILITY_EVENT;
4575 }
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004576 int32_t keyCode = incomingKey.getKeyCode();
4577 int32_t metaState = incomingKey.getMetaState();
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004578 KeyEvent keyEvent;
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004579 keyEvent.initialize(incomingKey.getId(), resolvedDeviceId, incomingKey.getSource(),
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004580 incomingKey.getDisplayId(), INVALID_HMAC, action, flags, keyCode,
4581 incomingKey.getScanCode(), metaState, incomingKey.getRepeatCount(),
4582 incomingKey.getDownTime(), incomingKey.getEventTime());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004583
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004584 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
4585 policyFlags |= POLICY_FLAG_VIRTUAL;
Michael Wright2b3c3302018-03-02 17:19:13 +00004586 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004587
4588 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
4589 android::base::Timer t;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004590 mPolicy.interceptKeyBeforeQueueing(keyEvent, /*byref*/ policyFlags);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004591 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4592 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
4593 std::to_string(t.duration().count()).c_str());
4594 }
4595 }
4596
4597 mLock.lock();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004598 std::unique_ptr<KeyEntry> injectedEntry =
4599 std::make_unique<KeyEntry>(incomingKey.getId(), incomingKey.getEventTime(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004600 resolvedDeviceId, incomingKey.getSource(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004601 incomingKey.getDisplayId(), policyFlags, action,
4602 flags, keyCode, incomingKey.getScanCode(), metaState,
4603 incomingKey.getRepeatCount(),
4604 incomingKey.getDownTime());
4605 injectedEntries.push(std::move(injectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004606 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004607 }
4608
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004609 case InputEventType::MOTION: {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004610 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(*event);
Prabir Pradhanaa561d12021-09-24 06:57:33 -07004611 const bool isPointerEvent =
4612 isFromSource(event->getSource(), AINPUT_SOURCE_CLASS_POINTER);
4613 // If a pointer event has no displayId specified, inject it to the default display.
4614 const uint32_t displayId = isPointerEvent && (event->getDisplayId() == ADISPLAY_ID_NONE)
4615 ? ADISPLAY_ID_DEFAULT
4616 : event->getDisplayId();
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004617 int32_t flags = motionEvent.getFlags();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004618
4619 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004620 nsecs_t eventTime = motionEvent.getEventTime();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004621 android::base::Timer t;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004622 mPolicy.interceptMotionBeforeQueueing(displayId, eventTime, /*byref*/ policyFlags);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004623 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4624 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
4625 std::to_string(t.duration().count()).c_str());
4626 }
4627 }
4628
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004629 if (policyFlags & POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY) {
4630 flags |= AMOTION_EVENT_FLAG_IS_ACCESSIBILITY_EVENT;
4631 }
4632
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004633 mLock.lock();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004634 const nsecs_t* sampleEventTimes = motionEvent.getSampleEventTimes();
4635 const PointerCoords* samplePointerCoords = motionEvent.getSamplePointerCoords();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004636 std::unique_ptr<MotionEntry> injectedEntry =
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004637 std::make_unique<MotionEntry>(motionEvent.getId(), *sampleEventTimes,
4638 resolvedDeviceId, motionEvent.getSource(),
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004639 displayId, policyFlags, motionEvent.getAction(),
4640 motionEvent.getActionButton(), flags,
4641 motionEvent.getMetaState(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004642 motionEvent.getButtonState(),
4643 motionEvent.getClassification(),
4644 motionEvent.getEdgeFlags(),
4645 motionEvent.getXPrecision(),
4646 motionEvent.getYPrecision(),
4647 motionEvent.getRawXCursorPosition(),
4648 motionEvent.getRawYCursorPosition(),
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004649 motionEvent.getDownTime(),
4650 motionEvent.getPointerCount(),
4651 motionEvent.getPointerProperties(),
4652 samplePointerCoords);
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004653 transformMotionEntryForInjectionLocked(*injectedEntry, motionEvent.getTransform());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004654 injectedEntries.push(std::move(injectedEntry));
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004655 for (size_t i = motionEvent.getHistorySize(); i > 0; i--) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004656 sampleEventTimes += 1;
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004657 samplePointerCoords += motionEvent.getPointerCount();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004658 std::unique_ptr<MotionEntry> nextInjectedEntry =
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004659 std::make_unique<MotionEntry>(motionEvent.getId(), *sampleEventTimes,
4660 resolvedDeviceId, motionEvent.getSource(),
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004661 displayId, policyFlags,
4662 motionEvent.getAction(),
4663 motionEvent.getActionButton(), flags,
4664 motionEvent.getMetaState(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004665 motionEvent.getButtonState(),
4666 motionEvent.getClassification(),
4667 motionEvent.getEdgeFlags(),
4668 motionEvent.getXPrecision(),
4669 motionEvent.getYPrecision(),
4670 motionEvent.getRawXCursorPosition(),
4671 motionEvent.getRawYCursorPosition(),
4672 motionEvent.getDownTime(),
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004673 motionEvent.getPointerCount(),
4674 motionEvent.getPointerProperties(),
Prabir Pradhan5beda762021-12-10 09:30:08 +00004675 samplePointerCoords);
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004676 transformMotionEntryForInjectionLocked(*nextInjectedEntry,
4677 motionEvent.getTransform());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004678 injectedEntries.push(std::move(nextInjectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004679 }
4680 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004681 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004682
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004683 default:
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004684 LOG(WARNING) << "Cannot inject " << ftl::enum_string(event->getType()) << " events";
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004685 return InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004686 }
4687
Prabir Pradhan5735a322022-04-11 17:23:34 +00004688 InjectionState* injectionState = new InjectionState(targetUid);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004689 if (syncMode == InputEventInjectionSync::NONE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004690 injectionState->injectionIsAsync = true;
4691 }
4692
4693 injectionState->refCount += 1;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004694 injectedEntries.back()->injectionState = injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004695
4696 bool needWake = false;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004697 while (!injectedEntries.empty()) {
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08004698 if (DEBUG_INJECTION) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07004699 LOG(INFO) << "Injecting " << injectedEntries.front()->getDescription();
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08004700 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004701 needWake |= enqueueInboundEventLocked(std::move(injectedEntries.front()));
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004702 injectedEntries.pop();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004703 }
4704
4705 mLock.unlock();
4706
4707 if (needWake) {
4708 mLooper->wake();
4709 }
4710
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004711 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004712 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004713 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004714
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004715 if (syncMode == InputEventInjectionSync::NONE) {
4716 injectionResult = InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004717 } else {
4718 for (;;) {
4719 injectionResult = injectionState->injectionResult;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004720 if (injectionResult != InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004721 break;
4722 }
4723
4724 nsecs_t remainingTimeout = endTime - now();
4725 if (remainingTimeout <= 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004726 if (DEBUG_INJECTION) {
4727 ALOGD("injectInputEvent - Timed out waiting for injection result "
4728 "to become available.");
4729 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004730 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004731 break;
4732 }
4733
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004734 mInjectionResultAvailable.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004735 }
4736
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004737 if (injectionResult == InputEventInjectionResult::SUCCEEDED &&
4738 syncMode == InputEventInjectionSync::WAIT_FOR_FINISHED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004739 while (injectionState->pendingForegroundDispatches != 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004740 if (DEBUG_INJECTION) {
4741 ALOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
4742 injectionState->pendingForegroundDispatches);
4743 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004744 nsecs_t remainingTimeout = endTime - now();
4745 if (remainingTimeout <= 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004746 if (DEBUG_INJECTION) {
4747 ALOGD("injectInputEvent - Timed out waiting for pending foreground "
4748 "dispatches to finish.");
4749 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004750 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004751 break;
4752 }
4753
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004754 mInjectionSyncFinished.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004755 }
4756 }
4757 }
4758
4759 injectionState->release();
4760 } // release lock
4761
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004762 if (DEBUG_INJECTION) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07004763 LOG(INFO) << "injectInputEvent - Finished with result "
4764 << ftl::enum_string(injectionResult);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004765 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004766
4767 return injectionResult;
4768}
4769
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004770std::unique_ptr<VerifiedInputEvent> InputDispatcher::verifyInputEvent(const InputEvent& event) {
Gang Wange9087892020-01-07 12:17:14 -05004771 std::array<uint8_t, 32> calculatedHmac;
4772 std::unique_ptr<VerifiedInputEvent> result;
4773 switch (event.getType()) {
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004774 case InputEventType::KEY: {
Gang Wange9087892020-01-07 12:17:14 -05004775 const KeyEvent& keyEvent = static_cast<const KeyEvent&>(event);
4776 VerifiedKeyEvent verifiedKeyEvent = verifiedKeyEventFromKeyEvent(keyEvent);
4777 result = std::make_unique<VerifiedKeyEvent>(verifiedKeyEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004778 calculatedHmac = sign(verifiedKeyEvent);
Gang Wange9087892020-01-07 12:17:14 -05004779 break;
4780 }
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004781 case InputEventType::MOTION: {
Gang Wange9087892020-01-07 12:17:14 -05004782 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(event);
4783 VerifiedMotionEvent verifiedMotionEvent =
4784 verifiedMotionEventFromMotionEvent(motionEvent);
4785 result = std::make_unique<VerifiedMotionEvent>(verifiedMotionEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004786 calculatedHmac = sign(verifiedMotionEvent);
Gang Wange9087892020-01-07 12:17:14 -05004787 break;
4788 }
4789 default: {
4790 ALOGE("Cannot verify events of type %" PRId32, event.getType());
4791 return nullptr;
4792 }
4793 }
4794 if (calculatedHmac == INVALID_HMAC) {
4795 return nullptr;
4796 }
tyiu1573a672023-02-21 22:38:32 +00004797 if (0 != CRYPTO_memcmp(calculatedHmac.data(), event.getHmac().data(), calculatedHmac.size())) {
Gang Wange9087892020-01-07 12:17:14 -05004798 return nullptr;
4799 }
4800 return result;
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004801}
4802
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004803void InputDispatcher::setInjectionResult(EventEntry& entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004804 InputEventInjectionResult injectionResult) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004805 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004806 if (injectionState) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004807 if (DEBUG_INJECTION) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07004808 LOG(INFO) << "Setting input event injection result to "
4809 << ftl::enum_string(injectionResult);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004810 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004811
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004812 if (injectionState->injectionIsAsync && !(entry.policyFlags & POLICY_FLAG_FILTERED)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004813 // Log the outcome since the injector did not wait for the injection result.
4814 switch (injectionResult) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004815 case InputEventInjectionResult::SUCCEEDED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004816 ALOGV("Asynchronous input event injection succeeded.");
4817 break;
Prabir Pradhan5735a322022-04-11 17:23:34 +00004818 case InputEventInjectionResult::TARGET_MISMATCH:
4819 ALOGV("Asynchronous input event injection target mismatch.");
4820 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004821 case InputEventInjectionResult::FAILED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004822 ALOGW("Asynchronous input event injection failed.");
4823 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004824 case InputEventInjectionResult::TIMED_OUT:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004825 ALOGW("Asynchronous input event injection timed out.");
4826 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004827 case InputEventInjectionResult::PENDING:
4828 ALOGE("Setting result to 'PENDING' for asynchronous injection");
4829 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004830 }
4831 }
4832
4833 injectionState->injectionResult = injectionResult;
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004834 mInjectionResultAvailable.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004835 }
4836}
4837
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004838void InputDispatcher::transformMotionEntryForInjectionLocked(
4839 MotionEntry& entry, const ui::Transform& injectedTransform) const {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004840 // Input injection works in the logical display coordinate space, but the input pipeline works
4841 // display space, so we need to transform the injected events accordingly.
4842 const auto it = mDisplayInfos.find(entry.displayId);
4843 if (it == mDisplayInfos.end()) return;
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004844 const auto& transformToDisplay = it->second.transform.inverse() * injectedTransform;
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004845
Prabir Pradhand9a2ebe2022-07-20 19:25:13 +00004846 if (entry.xCursorPosition != AMOTION_EVENT_INVALID_CURSOR_POSITION &&
4847 entry.yCursorPosition != AMOTION_EVENT_INVALID_CURSOR_POSITION) {
4848 const vec2 cursor =
4849 MotionEvent::calculateTransformedXY(entry.source, transformToDisplay,
4850 {entry.xCursorPosition, entry.yCursorPosition});
4851 entry.xCursorPosition = cursor.x;
4852 entry.yCursorPosition = cursor.y;
4853 }
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004854 for (uint32_t i = 0; i < entry.pointerCount; i++) {
Prabir Pradhan8e6ce222022-02-24 09:08:54 -08004855 entry.pointerCoords[i] =
4856 MotionEvent::calculateTransformedCoords(entry.source, transformToDisplay,
4857 entry.pointerCoords[i]);
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004858 }
4859}
4860
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004861void InputDispatcher::incrementPendingForegroundDispatches(EventEntry& entry) {
4862 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004863 if (injectionState) {
4864 injectionState->pendingForegroundDispatches += 1;
4865 }
4866}
4867
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004868void InputDispatcher::decrementPendingForegroundDispatches(EventEntry& entry) {
4869 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004870 if (injectionState) {
4871 injectionState->pendingForegroundDispatches -= 1;
4872
4873 if (injectionState->pendingForegroundDispatches == 0) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004874 mInjectionSyncFinished.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004875 }
4876 }
4877}
4878
chaviw98318de2021-05-19 16:45:23 -05004879const std::vector<sp<WindowInfoHandle>>& InputDispatcher::getWindowHandlesLocked(
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004880 int32_t displayId) const {
chaviw98318de2021-05-19 16:45:23 -05004881 static const std::vector<sp<WindowInfoHandle>> EMPTY_WINDOW_HANDLES;
Vishnu Nairad321cd2020-08-20 16:40:21 -07004882 auto it = mWindowHandlesByDisplay.find(displayId);
4883 return it != mWindowHandlesByDisplay.end() ? it->second : EMPTY_WINDOW_HANDLES;
Arthur Hungb92218b2018-08-14 12:00:21 +08004884}
4885
chaviw98318de2021-05-19 16:45:23 -05004886sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(
chaviwfbe5d9c2018-12-26 12:23:37 -08004887 const sp<IBinder>& windowHandleToken) const {
arthurhungbe737672020-06-24 12:29:21 +08004888 if (windowHandleToken == nullptr) {
4889 return nullptr;
4890 }
4891
Arthur Hungb92218b2018-08-14 12:00:21 +08004892 for (auto& it : mWindowHandlesByDisplay) {
chaviw98318de2021-05-19 16:45:23 -05004893 const std::vector<sp<WindowInfoHandle>>& windowHandles = it.second;
4894 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
chaviwfbe5d9c2018-12-26 12:23:37 -08004895 if (windowHandle->getToken() == windowHandleToken) {
Arthur Hungb92218b2018-08-14 12:00:21 +08004896 return windowHandle;
4897 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004898 }
4899 }
Yi Kong9b14ac62018-07-17 13:48:38 -07004900 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004901}
4902
chaviw98318de2021-05-19 16:45:23 -05004903sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(const sp<IBinder>& windowHandleToken,
4904 int displayId) const {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004905 if (windowHandleToken == nullptr) {
4906 return nullptr;
4907 }
4908
chaviw98318de2021-05-19 16:45:23 -05004909 for (const sp<WindowInfoHandle>& windowHandle : getWindowHandlesLocked(displayId)) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004910 if (windowHandle->getToken() == windowHandleToken) {
4911 return windowHandle;
4912 }
4913 }
4914 return nullptr;
4915}
4916
chaviw98318de2021-05-19 16:45:23 -05004917sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(
4918 const sp<WindowInfoHandle>& windowHandle) const {
Mady Mellor017bcd12020-06-23 19:12:00 +00004919 for (auto& it : mWindowHandlesByDisplay) {
chaviw98318de2021-05-19 16:45:23 -05004920 const std::vector<sp<WindowInfoHandle>>& windowHandles = it.second;
4921 for (const sp<WindowInfoHandle>& handle : windowHandles) {
arthurhungbe737672020-06-24 12:29:21 +08004922 if (handle->getId() == windowHandle->getId() &&
4923 handle->getToken() == windowHandle->getToken()) {
Mady Mellor017bcd12020-06-23 19:12:00 +00004924 if (windowHandle->getInfo()->displayId != it.first) {
4925 ALOGE("Found window %s in display %" PRId32
4926 ", but it should belong to display %" PRId32,
4927 windowHandle->getName().c_str(), it.first,
4928 windowHandle->getInfo()->displayId);
4929 }
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004930 return handle;
Arthur Hungb92218b2018-08-14 12:00:21 +08004931 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004932 }
4933 }
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004934 return nullptr;
4935}
4936
chaviw98318de2021-05-19 16:45:23 -05004937sp<WindowInfoHandle> InputDispatcher::getFocusedWindowHandleLocked(int displayId) const {
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004938 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(displayId);
4939 return getWindowHandleLocked(focusedToken, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004940}
4941
Prabir Pradhan33e3baa2022-12-06 20:30:22 +00004942ui::Transform InputDispatcher::getTransformLocked(int32_t displayId) const {
4943 auto displayInfoIt = mDisplayInfos.find(displayId);
4944 return displayInfoIt != mDisplayInfos.end() ? displayInfoIt->second.transform
4945 : kIdentityTransform;
4946}
4947
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004948bool InputDispatcher::canWindowReceiveMotionLocked(const sp<WindowInfoHandle>& window,
4949 const MotionEntry& motionEntry) const {
4950 const WindowInfo& info = *window->getInfo();
4951
4952 // Skip spy window targets that are not valid for targeted injection.
4953 if (const auto err = verifyTargetedInjection(window, motionEntry); err) {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004954 return false;
4955 }
4956
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004957 if (info.inputConfig.test(WindowInfo::InputConfig::PAUSE_DISPATCHING)) {
4958 ALOGI("Not sending touch event to %s because it is paused", window->getName().c_str());
4959 return false;
4960 }
4961
4962 if (info.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL)) {
4963 ALOGW("Not sending touch gesture to %s because it has config NO_INPUT_CHANNEL",
4964 window->getName().c_str());
4965 return false;
4966 }
4967
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07004968 std::shared_ptr<Connection> connection = getConnectionLocked(window->getToken());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004969 if (connection == nullptr) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004970 ALOGW("Not sending touch to %s because there's no corresponding connection",
4971 window->getName().c_str());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004972 return false;
4973 }
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004974
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004975 if (!connection->responsive) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004976 ALOGW("Not sending touch to %s because it is not responsive", window->getName().c_str());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004977 return false;
4978 }
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004979
4980 // Drop events that can't be trusted due to occlusion
4981 const auto [x, y] = resolveTouchedPosition(motionEntry);
4982 TouchOcclusionInfo occlusionInfo = computeTouchOcclusionInfoLocked(window, x, y);
4983 if (!isTouchTrustedLocked(occlusionInfo)) {
4984 if (DEBUG_TOUCH_OCCLUSION) {
Prabir Pradhan82e081e2022-12-06 09:50:09 +00004985 ALOGD("Stack of obscuring windows during untrusted touch (%.1f, %.1f):", x, y);
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004986 for (const auto& log : occlusionInfo.debugInfo) {
4987 ALOGD("%s", log.c_str());
4988 }
4989 }
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00004990 ALOGW("Dropping untrusted touch event due to %s/%s", occlusionInfo.obscuringPackage.c_str(),
4991 occlusionInfo.obscuringUid.toString().c_str());
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004992 return false;
4993 }
4994
4995 // Drop touch events if requested by input feature
4996 if (shouldDropInput(motionEntry, window)) {
4997 return false;
4998 }
4999
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005000 return true;
5001}
5002
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005003std::shared_ptr<InputChannel> InputDispatcher::getInputChannelLocked(
5004 const sp<IBinder>& token) const {
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005005 auto connectionIt = mConnectionsByToken.find(token);
5006 if (connectionIt == mConnectionsByToken.end()) {
Robert Carr5c8a0262018-10-03 16:30:44 -07005007 return nullptr;
5008 }
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005009 return connectionIt->second->inputChannel;
Robert Carr5c8a0262018-10-03 16:30:44 -07005010}
5011
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005012void InputDispatcher::updateWindowHandlesForDisplayLocked(
chaviw98318de2021-05-19 16:45:23 -05005013 const std::vector<sp<WindowInfoHandle>>& windowInfoHandles, int32_t displayId) {
5014 if (windowInfoHandles.empty()) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005015 // Remove all handles on a display if there are no windows left.
5016 mWindowHandlesByDisplay.erase(displayId);
5017 return;
5018 }
5019
5020 // Since we compare the pointer of input window handles across window updates, we need
5021 // to make sure the handle object for the same window stays unchanged across updates.
chaviw98318de2021-05-19 16:45:23 -05005022 const std::vector<sp<WindowInfoHandle>>& oldHandles = getWindowHandlesLocked(displayId);
5023 std::unordered_map<int32_t /*id*/, sp<WindowInfoHandle>> oldHandlesById;
5024 for (const sp<WindowInfoHandle>& handle : oldHandles) {
chaviwaf87b3e2019-10-01 16:59:28 -07005025 oldHandlesById[handle->getId()] = handle;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005026 }
5027
chaviw98318de2021-05-19 16:45:23 -05005028 std::vector<sp<WindowInfoHandle>> newHandles;
5029 for (const sp<WindowInfoHandle>& handle : windowInfoHandles) {
chaviw98318de2021-05-19 16:45:23 -05005030 const WindowInfo* info = handle->getInfo();
Siarhei Vishniakou64452932020-11-06 17:51:32 -06005031 if (getInputChannelLocked(handle->getToken()) == nullptr) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005032 const bool noInputChannel =
Prabir Pradhan51e7db02022-02-07 06:02:57 -08005033 info->inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005034 const bool canReceiveInput =
5035 !info->inputConfig.test(WindowInfo::InputConfig::NOT_TOUCHABLE) ||
5036 !info->inputConfig.test(WindowInfo::InputConfig::NOT_FOCUSABLE);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005037 if (canReceiveInput && !noInputChannel) {
John Recke0710582019-09-26 13:46:12 -07005038 ALOGV("Window handle %s has no registered input channel",
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005039 handle->getName().c_str());
Robert Carr2984b7a2020-04-13 17:06:45 -07005040 continue;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005041 }
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005042 }
5043
5044 if (info->displayId != displayId) {
5045 ALOGE("Window %s updated by wrong display %d, should belong to display %d",
5046 handle->getName().c_str(), displayId, info->displayId);
5047 continue;
5048 }
5049
Robert Carredd13602020-04-13 17:24:34 -07005050 if ((oldHandlesById.find(handle->getId()) != oldHandlesById.end()) &&
5051 (oldHandlesById.at(handle->getId())->getToken() == handle->getToken())) {
chaviw98318de2021-05-19 16:45:23 -05005052 const sp<WindowInfoHandle>& oldHandle = oldHandlesById.at(handle->getId());
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005053 oldHandle->updateFrom(handle);
5054 newHandles.push_back(oldHandle);
5055 } else {
5056 newHandles.push_back(handle);
5057 }
5058 }
5059
5060 // Insert or replace
5061 mWindowHandlesByDisplay[displayId] = newHandles;
5062}
5063
Arthur Hungb92218b2018-08-14 12:00:21 +08005064/**
5065 * Called from InputManagerService, update window handle list by displayId that can receive input.
5066 * A window handle contains information about InputChannel, Touch Region, Types, Focused,...
5067 * If set an empty list, remove all handles from the specific display.
5068 * For focused handle, check if need to change and send a cancel event to previous one.
5069 * For removed handle, check if need to send a cancel event if already in touch.
5070 */
Arthur Hung72d8dc32020-03-28 00:48:39 +00005071void InputDispatcher::setInputWindowsLocked(
chaviw98318de2021-05-19 16:45:23 -05005072 const std::vector<sp<WindowInfoHandle>>& windowInfoHandles, int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005073 if (DEBUG_FOCUS) {
5074 std::string windowList;
chaviw98318de2021-05-19 16:45:23 -05005075 for (const sp<WindowInfoHandle>& iwh : windowInfoHandles) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005076 windowList += iwh->getName() + " ";
5077 }
5078 ALOGD("setInputWindows displayId=%" PRId32 " %s", displayId, windowList.c_str());
5079 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005080
Prabir Pradhand65552b2021-10-07 11:23:50 -07005081 // Check preconditions for new input windows
chaviw98318de2021-05-19 16:45:23 -05005082 for (const sp<WindowInfoHandle>& window : windowInfoHandles) {
Prabir Pradhand65552b2021-10-07 11:23:50 -07005083 const WindowInfo& info = *window->getInfo();
5084
5085 // Ensure all tokens are null if the window has feature NO_INPUT_CHANNEL
Prabir Pradhan51e7db02022-02-07 06:02:57 -08005086 const bool noInputWindow = info.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005087 if (noInputWindow && window->getToken() != nullptr) {
5088 ALOGE("%s has feature NO_INPUT_WINDOW, but a non-null token. Clearing",
5089 window->getName().c_str());
5090 window->releaseChannel();
5091 }
Prabir Pradhand65552b2021-10-07 11:23:50 -07005092
Prabir Pradhan5c85e052021-12-22 02:27:12 -08005093 // Ensure all spy windows are trusted overlays
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005094 LOG_ALWAYS_FATAL_IF(info.isSpy() &&
5095 !info.inputConfig.test(
5096 WindowInfo::InputConfig::TRUSTED_OVERLAY),
Prabir Pradhan5c85e052021-12-22 02:27:12 -08005097 "%s has feature SPY, but is not a trusted overlay.",
5098 window->getName().c_str());
5099
Prabir Pradhand65552b2021-10-07 11:23:50 -07005100 // Ensure all stylus interceptors are trusted overlays
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005101 LOG_ALWAYS_FATAL_IF(info.interceptsStylus() &&
5102 !info.inputConfig.test(
5103 WindowInfo::InputConfig::TRUSTED_OVERLAY),
Prabir Pradhand65552b2021-10-07 11:23:50 -07005104 "%s has feature INTERCEPTS_STYLUS, but is not a trusted overlay.",
5105 window->getName().c_str());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005106 }
5107
Arthur Hung72d8dc32020-03-28 00:48:39 +00005108 // Copy old handles for release if they are no longer present.
chaviw98318de2021-05-19 16:45:23 -05005109 const std::vector<sp<WindowInfoHandle>> oldWindowHandles = getWindowHandlesLocked(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005110
chaviw98318de2021-05-19 16:45:23 -05005111 updateWindowHandlesForDisplayLocked(windowInfoHandles, displayId);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005112
chaviw98318de2021-05-19 16:45:23 -05005113 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Arthur Hung72d8dc32020-03-28 00:48:39 +00005114
Vishnu Nairc519ff72021-01-21 08:23:08 -08005115 std::optional<FocusResolver::FocusChanges> changes =
5116 mFocusResolver.setInputWindows(displayId, windowHandles);
5117 if (changes) {
5118 onFocusChangedLocked(*changes);
Arthur Hung72d8dc32020-03-28 00:48:39 +00005119 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005120
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005121 std::unordered_map<int32_t, TouchState>::iterator stateIt =
5122 mTouchStatesByDisplay.find(displayId);
5123 if (stateIt != mTouchStatesByDisplay.end()) {
5124 TouchState& state = stateIt->second;
Arthur Hung72d8dc32020-03-28 00:48:39 +00005125 for (size_t i = 0; i < state.windows.size();) {
5126 TouchedWindow& touchedWindow = state.windows[i];
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07005127 if (getWindowHandleLocked(touchedWindow.windowHandle) == nullptr) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005128 if (DEBUG_FOCUS) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00005129 ALOGD("Touched window was removed: %s in display %" PRId32,
5130 touchedWindow.windowHandle->getName().c_str(), displayId);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005131 }
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005132 std::shared_ptr<InputChannel> touchedInputChannel =
Arthur Hung72d8dc32020-03-28 00:48:39 +00005133 getInputChannelLocked(touchedWindow.windowHandle->getToken());
5134 if (touchedInputChannel != nullptr) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00005135 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
Arthur Hung72d8dc32020-03-28 00:48:39 +00005136 "touched window was removed");
5137 synthesizeCancelationEventsForInputChannelLocked(touchedInputChannel, options);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00005138 // Since we are about to drop the touch, cancel the events for the wallpaper as
5139 // well.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005140 if (touchedWindow.targetFlags.test(InputTarget::Flags::FOREGROUND) &&
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005141 touchedWindow.windowHandle->getInfo()->inputConfig.test(
5142 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER)) {
Siarhei Vishniakouca205502021-07-16 21:31:58 +00005143 sp<WindowInfoHandle> wallpaper = state.getWallpaperWindow();
Arthur Hungc539dbb2022-12-08 07:45:36 +00005144 synthesizeCancelationEventsForWindowLocked(wallpaper, options);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00005145 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005146 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00005147 state.windows.erase(state.windows.begin() + i);
5148 } else {
5149 ++i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005150 }
5151 }
arthurhungb89ccb02020-12-30 16:19:01 +08005152
arthurhung6d4bed92021-03-17 11:59:33 +08005153 // If drag window is gone, it would receive a cancel event and broadcast the DRAG_END. We
arthurhungb89ccb02020-12-30 16:19:01 +08005154 // could just clear the state here.
Arthur Hung3915c1f2022-05-31 07:17:17 +00005155 if (mDragState && mDragState->dragWindow->getInfo()->displayId == displayId &&
arthurhung6d4bed92021-03-17 11:59:33 +08005156 std::find(windowHandles.begin(), windowHandles.end(), mDragState->dragWindow) ==
arthurhungb89ccb02020-12-30 16:19:01 +08005157 windowHandles.end()) {
Arthur Hung3915c1f2022-05-31 07:17:17 +00005158 ALOGI("Drag window went away: %s", mDragState->dragWindow->getName().c_str());
5159 sendDropWindowCommandLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08005160 mDragState.reset();
arthurhungb89ccb02020-12-30 16:19:01 +08005161 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00005162 }
Arthur Hung25e2af12020-03-26 12:58:37 +00005163
Arthur Hung72d8dc32020-03-28 00:48:39 +00005164 // Release information for windows that are no longer present.
5165 // This ensures that unused input channels are released promptly.
5166 // Otherwise, they might stick around until the window handle is destroyed
5167 // which might not happen until the next GC.
chaviw98318de2021-05-19 16:45:23 -05005168 for (const sp<WindowInfoHandle>& oldWindowHandle : oldWindowHandles) {
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07005169 if (getWindowHandleLocked(oldWindowHandle) == nullptr) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00005170 if (DEBUG_FOCUS) {
5171 ALOGD("Window went away: %s", oldWindowHandle->getName().c_str());
Arthur Hung25e2af12020-03-26 12:58:37 +00005172 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00005173 oldWindowHandle->releaseChannel();
Arthur Hung25e2af12020-03-26 12:58:37 +00005174 }
chaviw291d88a2019-02-14 10:33:58 -08005175 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005176}
5177
5178void InputDispatcher::setFocusedApplication(
Chris Yea209fde2020-07-22 13:54:51 -07005179 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005180 if (DEBUG_FOCUS) {
5181 ALOGD("setFocusedApplication displayId=%" PRId32 " %s", displayId,
5182 inputApplicationHandle ? inputApplicationHandle->getName().c_str() : "<nullptr>");
5183 }
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05005184 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005185 std::scoped_lock _l(mLock);
Vishnu Nair599f1412021-06-21 10:39:58 -07005186 setFocusedApplicationLocked(displayId, inputApplicationHandle);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005187 } // release lock
5188
5189 // Wake up poll loop since it may need to make new input dispatching choices.
5190 mLooper->wake();
5191}
5192
Vishnu Nair599f1412021-06-21 10:39:58 -07005193void InputDispatcher::setFocusedApplicationLocked(
5194 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
5195 std::shared_ptr<InputApplicationHandle> oldFocusedApplicationHandle =
5196 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
5197
5198 if (sharedPointersEqual(oldFocusedApplicationHandle, inputApplicationHandle)) {
5199 return; // This application is already focused. No need to wake up or change anything.
5200 }
5201
5202 // Set the new application handle.
5203 if (inputApplicationHandle != nullptr) {
5204 mFocusedApplicationHandlesByDisplay[displayId] = inputApplicationHandle;
5205 } else {
5206 mFocusedApplicationHandlesByDisplay.erase(displayId);
5207 }
5208
5209 // No matter what the old focused application was, stop waiting on it because it is
5210 // no longer focused.
5211 resetNoFocusedWindowTimeoutLocked();
5212}
5213
Tiger Huang721e26f2018-07-24 22:26:19 +08005214/**
5215 * Sets the focused display, which is responsible for receiving focus-dispatched input events where
5216 * the display not specified.
5217 *
5218 * We track any unreleased events for each window. If a window loses the ability to receive the
5219 * released event, we will send a cancel event to it. So when the focused display is changed, we
5220 * cancel all the unreleased display-unspecified events for the focused window on the old focused
5221 * display. The display-specified events won't be affected.
5222 */
5223void InputDispatcher::setFocusedDisplay(int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005224 if (DEBUG_FOCUS) {
5225 ALOGD("setFocusedDisplay displayId=%" PRId32, displayId);
5226 }
Tiger Huang721e26f2018-07-24 22:26:19 +08005227 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005228 std::scoped_lock _l(mLock);
Tiger Huang721e26f2018-07-24 22:26:19 +08005229
5230 if (mFocusedDisplayId != displayId) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07005231 sp<IBinder> oldFocusedWindowToken =
Vishnu Nairc519ff72021-01-21 08:23:08 -08005232 mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07005233 if (oldFocusedWindowToken != nullptr) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005234 std::shared_ptr<InputChannel> inputChannel =
Vishnu Nairad321cd2020-08-20 16:40:21 -07005235 getInputChannelLocked(oldFocusedWindowToken);
Tiger Huang721e26f2018-07-24 22:26:19 +08005236 if (inputChannel != nullptr) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005237 CancelationOptions
Michael Wrightfb04fd52022-11-24 22:31:11 +00005238 options(CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005239 "The display which contains this window no longer has focus.");
Michael Wright3dd60e22019-03-27 22:06:44 +00005240 options.displayId = ADISPLAY_ID_NONE;
Tiger Huang721e26f2018-07-24 22:26:19 +08005241 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
5242 }
5243 }
5244 mFocusedDisplayId = displayId;
5245
Chris Ye3c2d6f52020-08-09 10:39:48 -07005246 // Find new focused window and validate
Vishnu Nairc519ff72021-01-21 08:23:08 -08005247 sp<IBinder> newFocusedWindowToken = mFocusResolver.getFocusedWindowToken(displayId);
Prabir Pradhancef936d2021-07-21 16:17:52 +00005248 sendFocusChangedCommandLocked(oldFocusedWindowToken, newFocusedWindowToken);
Robert Carrf759f162018-11-13 12:57:11 -08005249
Vishnu Nairad321cd2020-08-20 16:40:21 -07005250 if (newFocusedWindowToken == nullptr) {
Tiger Huang721e26f2018-07-24 22:26:19 +08005251 ALOGW("Focused display #%" PRId32 " does not have a focused window.", displayId);
Vishnu Nairc519ff72021-01-21 08:23:08 -08005252 if (mFocusResolver.hasFocusedWindowTokens()) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07005253 ALOGE("But another display has a focused window\n%s",
Vishnu Nairc519ff72021-01-21 08:23:08 -08005254 mFocusResolver.dumpFocusedWindows().c_str());
Tiger Huang721e26f2018-07-24 22:26:19 +08005255 }
5256 }
5257 }
Tiger Huang721e26f2018-07-24 22:26:19 +08005258 } // release lock
5259
5260 // Wake up poll loop since it may need to make new input dispatching choices.
5261 mLooper->wake();
5262}
5263
Michael Wrightd02c5b62014-02-10 15:10:22 -08005264void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005265 if (DEBUG_FOCUS) {
5266 ALOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
5267 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005268
5269 bool changed;
5270 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005271 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005272
5273 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
5274 if (mDispatchFrozen && !frozen) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005275 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005276 }
5277
5278 if (mDispatchEnabled && !enabled) {
5279 resetAndDropEverythingLocked("dispatcher is being disabled");
5280 }
5281
5282 mDispatchEnabled = enabled;
5283 mDispatchFrozen = frozen;
5284 changed = true;
5285 } else {
5286 changed = false;
5287 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005288 } // release lock
5289
5290 if (changed) {
5291 // Wake up poll loop since it may need to make new input dispatching choices.
5292 mLooper->wake();
5293 }
5294}
5295
5296void InputDispatcher::setInputFilterEnabled(bool enabled) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005297 if (DEBUG_FOCUS) {
5298 ALOGD("setInputFilterEnabled: enabled=%d", enabled);
5299 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005300
5301 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005302 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005303
5304 if (mInputFilterEnabled == enabled) {
5305 return;
5306 }
5307
5308 mInputFilterEnabled = enabled;
5309 resetAndDropEverythingLocked("input filter is being enabled or disabled");
5310 } // release lock
5311
5312 // Wake up poll loop since there might be work to do to drop everything.
5313 mLooper->wake();
5314}
5315
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005316bool InputDispatcher::setInTouchMode(bool inTouchMode, gui::Pid pid, gui::Uid uid,
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00005317 bool hasPermission, int32_t displayId) {
Antonio Kantekf16f2832021-09-28 04:39:20 +00005318 bool needWake = false;
5319 {
5320 std::scoped_lock lock(mLock);
Antonio Kantek15beb512022-06-13 22:35:41 +00005321 ALOGD_IF(DEBUG_TOUCH_MODE,
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005322 "Request to change touch mode to %s (calling pid=%s, uid=%s, "
Antonio Kantek15beb512022-06-13 22:35:41 +00005323 "hasPermission=%s, target displayId=%d, mTouchModePerDisplay[displayId]=%s)",
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005324 toString(inTouchMode), pid.toString().c_str(), uid.toString().c_str(),
5325 toString(hasPermission), displayId,
Antonio Kantek15beb512022-06-13 22:35:41 +00005326 mTouchModePerDisplay.count(displayId) == 0
5327 ? "not set"
5328 : std::to_string(mTouchModePerDisplay[displayId]).c_str());
5329
Antonio Kantek15beb512022-06-13 22:35:41 +00005330 auto touchModeIt = mTouchModePerDisplay.find(displayId);
5331 if (touchModeIt != mTouchModePerDisplay.end() && touchModeIt->second == inTouchMode) {
Antonio Kantekea47acb2021-12-23 12:41:25 -08005332 return false;
Antonio Kantekf16f2832021-09-28 04:39:20 +00005333 }
Antonio Kantekea47acb2021-12-23 12:41:25 -08005334 if (!hasPermission) {
Antonio Kantek48710e42022-03-24 14:19:30 -07005335 if (!focusedWindowIsOwnedByLocked(pid, uid) &&
5336 !recentWindowsAreOwnedByLocked(pid, uid)) {
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005337 ALOGD("Touch mode switch rejected, caller (pid=%s, uid=%s) doesn't own the focused "
Antonio Kantek48710e42022-03-24 14:19:30 -07005338 "window nor none of the previously interacted window",
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005339 pid.toString().c_str(), uid.toString().c_str());
Antonio Kantekea47acb2021-12-23 12:41:25 -08005340 return false;
5341 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00005342 }
Antonio Kantek15beb512022-06-13 22:35:41 +00005343 mTouchModePerDisplay[displayId] = inTouchMode;
5344 auto entry = std::make_unique<TouchModeEntry>(mIdGenerator.nextId(), now(), inTouchMode,
5345 displayId);
Antonio Kantekf16f2832021-09-28 04:39:20 +00005346 needWake = enqueueInboundEventLocked(std::move(entry));
5347 } // release lock
5348
5349 if (needWake) {
5350 mLooper->wake();
5351 }
Antonio Kantekea47acb2021-12-23 12:41:25 -08005352 return true;
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -08005353}
5354
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005355bool InputDispatcher::focusedWindowIsOwnedByLocked(gui::Pid pid, gui::Uid uid) {
Antonio Kantek48710e42022-03-24 14:19:30 -07005356 const sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
5357 if (focusedToken == nullptr) {
5358 return false;
5359 }
5360 sp<WindowInfoHandle> windowHandle = getWindowHandleLocked(focusedToken);
5361 return isWindowOwnedBy(windowHandle, pid, uid);
5362}
5363
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005364bool InputDispatcher::recentWindowsAreOwnedByLocked(gui::Pid pid, gui::Uid uid) {
Antonio Kantek48710e42022-03-24 14:19:30 -07005365 return std::find_if(mInteractionConnectionTokens.begin(), mInteractionConnectionTokens.end(),
5366 [&](const sp<IBinder>& connectionToken) REQUIRES(mLock) {
5367 const sp<WindowInfoHandle> windowHandle =
5368 getWindowHandleLocked(connectionToken);
5369 return isWindowOwnedBy(windowHandle, pid, uid);
5370 }) != mInteractionConnectionTokens.end();
5371}
5372
Bernardo Rufinoea97d182020-08-19 14:43:14 +01005373void InputDispatcher::setMaximumObscuringOpacityForTouch(float opacity) {
5374 if (opacity < 0 || opacity > 1) {
5375 LOG_ALWAYS_FATAL("Maximum obscuring opacity for touch should be >= 0 and <= 1");
5376 return;
5377 }
5378
5379 std::scoped_lock lock(mLock);
5380 mMaximumObscuringOpacityForTouch = opacity;
5381}
5382
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005383std::tuple<TouchState*, TouchedWindow*, int32_t /*displayId*/>
5384InputDispatcher::findTouchStateWindowAndDisplayLocked(const sp<IBinder>& token) {
Arthur Hungabbb9d82021-09-01 14:52:30 +00005385 for (auto& [displayId, state] : mTouchStatesByDisplay) {
5386 for (TouchedWindow& w : state.windows) {
5387 if (w.windowHandle->getToken() == token) {
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005388 return std::make_tuple(&state, &w, displayId);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005389 }
5390 }
5391 }
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005392 return std::make_tuple(nullptr, nullptr, ADISPLAY_ID_DEFAULT);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005393}
5394
arthurhungb89ccb02020-12-30 16:19:01 +08005395bool InputDispatcher::transferTouchFocus(const sp<IBinder>& fromToken, const sp<IBinder>& toToken,
5396 bool isDragDrop) {
chaviwfbe5d9c2018-12-26 12:23:37 -08005397 if (fromToken == toToken) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005398 if (DEBUG_FOCUS) {
5399 ALOGD("Trivial transfer to same window.");
5400 }
chaviwfbe5d9c2018-12-26 12:23:37 -08005401 return true;
5402 }
5403
Michael Wrightd02c5b62014-02-10 15:10:22 -08005404 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005405 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005406
Arthur Hungabbb9d82021-09-01 14:52:30 +00005407 // Find the target touch state and touched window by fromToken.
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005408 auto [state, touchedWindow, displayId] = findTouchStateWindowAndDisplayLocked(fromToken);
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005409
Arthur Hungabbb9d82021-09-01 14:52:30 +00005410 if (state == nullptr || touchedWindow == nullptr) {
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005411 ALOGD("Touch transfer failed because from window is not being touched.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005412 return false;
5413 }
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005414 std::set<int32_t> deviceIds = touchedWindow->getTouchingDeviceIds();
5415 if (deviceIds.size() != 1) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07005416 LOG(INFO) << "Can't transfer touch. Currently touching devices: " << dumpSet(deviceIds)
5417 << " for window: " << touchedWindow->dump();
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005418 return false;
5419 }
5420 const int32_t deviceId = *deviceIds.begin();
Arthur Hungabbb9d82021-09-01 14:52:30 +00005421
Arthur Hungabbb9d82021-09-01 14:52:30 +00005422 sp<WindowInfoHandle> toWindowHandle = getWindowHandleLocked(toToken, displayId);
5423 if (toWindowHandle == nullptr) {
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005424 ALOGW("Cannot transfer touch because to window not found.");
Arthur Hungabbb9d82021-09-01 14:52:30 +00005425 return false;
5426 }
5427
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005428 if (DEBUG_FOCUS) {
5429 ALOGD("transferTouchFocus: fromWindowHandle=%s, toWindowHandle=%s",
Arthur Hungabbb9d82021-09-01 14:52:30 +00005430 touchedWindow->windowHandle->getName().c_str(),
5431 toWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005432 }
5433
Arthur Hungabbb9d82021-09-01 14:52:30 +00005434 // Erase old window.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005435 ftl::Flags<InputTarget::Flags> oldTargetFlags = touchedWindow->targetFlags;
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005436 std::bitset<MAX_POINTER_ID + 1> pointerIds = touchedWindow->getTouchingPointers(deviceId);
Arthur Hungc539dbb2022-12-08 07:45:36 +00005437 sp<WindowInfoHandle> fromWindowHandle = touchedWindow->windowHandle;
Arthur Hungabbb9d82021-09-01 14:52:30 +00005438 state->removeWindowByToken(fromToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005439
Arthur Hungabbb9d82021-09-01 14:52:30 +00005440 // Add new window.
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00005441 nsecs_t downTimeInTarget = now();
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005442 ftl::Flags<InputTarget::Flags> newTargetFlags =
5443 oldTargetFlags & (InputTarget::Flags::SPLIT | InputTarget::Flags::DISPATCH_AS_IS);
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00005444 if (canReceiveForegroundTouches(*toWindowHandle->getInfo())) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005445 newTargetFlags |= InputTarget::Flags::FOREGROUND;
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00005446 }
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005447 state->addOrUpdateWindow(toWindowHandle, newTargetFlags, deviceId, pointerIds,
5448 downTimeInTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005449
Arthur Hungabbb9d82021-09-01 14:52:30 +00005450 // Store the dragging window.
5451 if (isDragDrop) {
Arthur Hungb75c2aa2022-07-15 09:35:36 +00005452 if (pointerIds.count() != 1) {
5453 ALOGW("The drag and drop cannot be started when there is no pointer or more than 1"
5454 " pointer on the window.");
Arthur Hung54745652022-04-20 07:17:41 +00005455 return false;
5456 }
Arthur Hungb75c2aa2022-07-15 09:35:36 +00005457 // Track the pointer id for drag window and generate the drag state.
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08005458 const size_t id = firstMarkedBit(pointerIds);
Arthur Hung54745652022-04-20 07:17:41 +00005459 mDragState = std::make_unique<DragState>(toWindowHandle, id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005460 }
5461
Arthur Hungabbb9d82021-09-01 14:52:30 +00005462 // Synthesize cancel for old window and down for new window.
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07005463 std::shared_ptr<Connection> fromConnection = getConnectionLocked(fromToken);
5464 std::shared_ptr<Connection> toConnection = getConnectionLocked(toToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005465 if (fromConnection != nullptr && toConnection != nullptr) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08005466 fromConnection->inputState.mergePointerStateTo(toConnection->inputState);
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005467 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
5468 "transferring touch from this window to another window");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005469 synthesizeCancelationEventsForConnectionLocked(fromConnection, options);
Arthur Hungc539dbb2022-12-08 07:45:36 +00005470 synthesizePointerDownEventsForConnectionLocked(downTimeInTarget, toConnection,
5471 newTargetFlags);
5472
5473 // Check if the wallpaper window should deliver the corresponding event.
5474 transferWallpaperTouch(oldTargetFlags, newTargetFlags, fromWindowHandle, toWindowHandle,
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005475 *state, deviceId, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005476 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005477 } // release lock
5478
5479 // Wake up poll loop since it may need to make new input dispatching choices.
5480 mLooper->wake();
5481 return true;
5482}
5483
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005484/**
5485 * Get the touched foreground window on the given display.
5486 * Return null if there are no windows touched on that display, or if more than one foreground
5487 * window is being touched.
5488 */
5489sp<WindowInfoHandle> InputDispatcher::findTouchedForegroundWindowLocked(int32_t displayId) const {
5490 auto stateIt = mTouchStatesByDisplay.find(displayId);
5491 if (stateIt == mTouchStatesByDisplay.end()) {
5492 ALOGI("No touch state on display %" PRId32, displayId);
5493 return nullptr;
5494 }
5495
5496 const TouchState& state = stateIt->second;
5497 sp<WindowInfoHandle> touchedForegroundWindow;
5498 // If multiple foreground windows are touched, return nullptr
5499 for (const TouchedWindow& window : state.windows) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005500 if (window.targetFlags.test(InputTarget::Flags::FOREGROUND)) {
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005501 if (touchedForegroundWindow != nullptr) {
5502 ALOGI("Two or more foreground windows: %s and %s",
5503 touchedForegroundWindow->getName().c_str(),
5504 window.windowHandle->getName().c_str());
5505 return nullptr;
5506 }
5507 touchedForegroundWindow = window.windowHandle;
5508 }
5509 }
5510 return touchedForegroundWindow;
5511}
5512
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005513// Binder call
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005514bool InputDispatcher::transferTouch(const sp<IBinder>& destChannelToken, int32_t displayId) {
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005515 sp<IBinder> fromToken;
5516 { // acquire lock
5517 std::scoped_lock _l(mLock);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005518 sp<WindowInfoHandle> toWindowHandle = getWindowHandleLocked(destChannelToken, displayId);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005519 if (toWindowHandle == nullptr) {
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005520 ALOGW("Could not find window associated with token=%p on display %" PRId32,
5521 destChannelToken.get(), displayId);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005522 return false;
5523 }
5524
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005525 sp<WindowInfoHandle> from = findTouchedForegroundWindowLocked(displayId);
5526 if (from == nullptr) {
5527 ALOGE("Could not find a source window in %s for %p", __func__, destChannelToken.get());
5528 return false;
5529 }
5530
5531 fromToken = from->getToken();
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005532 } // release lock
5533
5534 return transferTouchFocus(fromToken, destChannelToken);
5535}
5536
Michael Wrightd02c5b62014-02-10 15:10:22 -08005537void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005538 if (DEBUG_FOCUS) {
5539 ALOGD("Resetting and dropping all events (%s).", reason);
5540 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005541
Michael Wrightfb04fd52022-11-24 22:31:11 +00005542 CancelationOptions options(CancelationOptions::Mode::CANCEL_ALL_EVENTS, reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005543 synthesizeCancelationEventsForAllConnectionsLocked(options);
5544
5545 resetKeyRepeatLocked();
5546 releasePendingEventLocked();
5547 drainInboundQueueLocked();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005548 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005549
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005550 mAnrTracker.clear();
Jeff Brownf086ddb2014-02-11 14:28:48 -08005551 mTouchStatesByDisplay.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005552}
5553
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005554void InputDispatcher::logDispatchStateLocked() const {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005555 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005556 dumpDispatchStateLocked(dump);
5557
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005558 std::istringstream stream(dump);
5559 std::string line;
5560
5561 while (std::getline(stream, line, '\n')) {
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07005562 ALOGI("%s", line.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005563 }
5564}
5565
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005566std::string InputDispatcher::dumpPointerCaptureStateLocked() const {
Prabir Pradhan99987712020-11-10 18:43:05 -08005567 std::string dump;
5568
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005569 dump += StringPrintf(INDENT "Pointer Capture Requested: %s\n",
5570 toString(mCurrentPointerCaptureRequest.enable));
Prabir Pradhan99987712020-11-10 18:43:05 -08005571
5572 std::string windowName = "None";
5573 if (mWindowTokenWithPointerCapture) {
chaviw98318de2021-05-19 16:45:23 -05005574 const sp<WindowInfoHandle> captureWindowHandle =
Prabir Pradhan99987712020-11-10 18:43:05 -08005575 getWindowHandleLocked(mWindowTokenWithPointerCapture);
5576 windowName = captureWindowHandle ? captureWindowHandle->getName().c_str()
5577 : "token has capture without window";
5578 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005579 dump += StringPrintf(INDENT "Current Window with Pointer Capture: %s\n", windowName.c_str());
Prabir Pradhan99987712020-11-10 18:43:05 -08005580
5581 return dump;
5582}
5583
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005584void InputDispatcher::dumpDispatchStateLocked(std::string& dump) const {
Siarhei Vishniakou043a3ec2019-05-01 11:30:46 -07005585 dump += StringPrintf(INDENT "DispatchEnabled: %s\n", toString(mDispatchEnabled));
5586 dump += StringPrintf(INDENT "DispatchFrozen: %s\n", toString(mDispatchFrozen));
5587 dump += StringPrintf(INDENT "InputFilterEnabled: %s\n", toString(mInputFilterEnabled));
Tiger Huang721e26f2018-07-24 22:26:19 +08005588 dump += StringPrintf(INDENT "FocusedDisplayId: %" PRId32 "\n", mFocusedDisplayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005589
Tiger Huang721e26f2018-07-24 22:26:19 +08005590 if (!mFocusedApplicationHandlesByDisplay.empty()) {
5591 dump += StringPrintf(INDENT "FocusedApplications:\n");
5592 for (auto& it : mFocusedApplicationHandlesByDisplay) {
5593 const int32_t displayId = it.first;
Chris Yea209fde2020-07-22 13:54:51 -07005594 const std::shared_ptr<InputApplicationHandle>& applicationHandle = it.second;
Siarhei Vishniakou70622952020-07-30 11:17:23 -05005595 const std::chrono::duration timeout =
5596 applicationHandle->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005597 dump += StringPrintf(INDENT2 "displayId=%" PRId32
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005598 ", name='%s', dispatchingTimeout=%" PRId64 "ms\n",
Siarhei Vishniakou70622952020-07-30 11:17:23 -05005599 displayId, applicationHandle->getName().c_str(), millis(timeout));
Tiger Huang721e26f2018-07-24 22:26:19 +08005600 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005601 } else {
Tiger Huang721e26f2018-07-24 22:26:19 +08005602 dump += StringPrintf(INDENT "FocusedApplications: <none>\n");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005603 }
Tiger Huang721e26f2018-07-24 22:26:19 +08005604
Vishnu Nairc519ff72021-01-21 08:23:08 -08005605 dump += mFocusResolver.dump();
Prabir Pradhan99987712020-11-10 18:43:05 -08005606 dump += dumpPointerCaptureStateLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005607
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005608 if (!mTouchStatesByDisplay.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005609 dump += StringPrintf(INDENT "TouchStatesByDisplay:\n");
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005610 for (const auto& [displayId, state] : mTouchStatesByDisplay) {
Siarhei Vishniakou6e1e9872022-11-08 17:51:35 -08005611 std::string touchStateDump = addLinePrefix(state.dump(), INDENT2);
5612 dump += INDENT2 + std::to_string(displayId) + " : " + touchStateDump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005613 }
5614 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005615 dump += INDENT "TouchStates: <no displays touched>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005616 }
5617
arthurhung6d4bed92021-03-17 11:59:33 +08005618 if (mDragState) {
5619 dump += StringPrintf(INDENT "DragState:\n");
5620 mDragState->dump(dump, INDENT2);
5621 }
5622
Arthur Hungb92218b2018-08-14 12:00:21 +08005623 if (!mWindowHandlesByDisplay.empty()) {
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005624 for (const auto& [displayId, windowHandles] : mWindowHandlesByDisplay) {
5625 dump += StringPrintf(INDENT "Display: %" PRId32 "\n", displayId);
5626 if (const auto& it = mDisplayInfos.find(displayId); it != mDisplayInfos.end()) {
5627 const auto& displayInfo = it->second;
5628 dump += StringPrintf(INDENT2 "logicalSize=%dx%d\n", displayInfo.logicalWidth,
5629 displayInfo.logicalHeight);
5630 displayInfo.transform.dump(dump, "transform", INDENT4);
5631 } else {
5632 dump += INDENT2 "No DisplayInfo found!\n";
5633 }
5634
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08005635 if (!windowHandles.empty()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08005636 dump += INDENT2 "Windows:\n";
5637 for (size_t i = 0; i < windowHandles.size(); i++) {
chaviw98318de2021-05-19 16:45:23 -05005638 const sp<WindowInfoHandle>& windowHandle = windowHandles[i];
5639 const WindowInfo* windowInfo = windowHandle->getInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005640
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00005641 dump += StringPrintf(INDENT3 "%zu: name='%s', id=%" PRId32 ", displayId=%d, "
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005642 "inputConfig=%s, alpha=%.2f, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005643 "frame=[%d,%d][%d,%d], globalScale=%f, "
Bernardo Rufino49d99e42021-01-18 15:16:59 +00005644 "applicationInfo.name=%s, "
5645 "applicationInfo.token=%s, "
chaviw1ff3d1e2020-07-01 15:53:47 -07005646 "touchableRegion=",
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00005647 i, windowInfo->name.c_str(), windowInfo->id,
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005648 windowInfo->displayId,
5649 windowInfo->inputConfig.string().c_str(),
Chavi Weingarten7f019192023-08-08 20:39:01 +00005650 windowInfo->alpha, windowInfo->frame.left,
5651 windowInfo->frame.top, windowInfo->frame.right,
5652 windowInfo->frame.bottom, windowInfo->globalScaleFactor,
Bernardo Rufino49d99e42021-01-18 15:16:59 +00005653 windowInfo->applicationInfo.name.c_str(),
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07005654 binderToString(windowInfo->applicationInfo.token).c_str());
Bernardo Rufino53fc31e2020-11-03 11:01:07 +00005655 dump += dumpRegion(windowInfo->touchableRegion);
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005656 dump += StringPrintf(", ownerPid=%s, ownerUid=%s, dispatchingTimeout=%" PRId64
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005657 "ms, hasToken=%s, "
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005658 "touchOcclusionMode=%s\n",
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005659 windowInfo->ownerPid.toString().c_str(),
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00005660 windowInfo->ownerUid.toString().c_str(),
Bernardo Rufinoc2f1fad2020-11-04 17:30:57 +00005661 millis(windowInfo->dispatchingTimeout),
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07005662 binderToString(windowInfo->token).c_str(),
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005663 toString(windowInfo->touchOcclusionMode).c_str());
chaviw85b44202020-07-24 11:46:21 -07005664 windowInfo->transform.dump(dump, "transform", INDENT4);
Arthur Hungb92218b2018-08-14 12:00:21 +08005665 }
5666 } else {
5667 dump += INDENT2 "Windows: <none>\n";
5668 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005669 }
5670 } else {
Arthur Hungb92218b2018-08-14 12:00:21 +08005671 dump += INDENT "Displays: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005672 }
5673
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005674 if (!mGlobalMonitorsByDisplay.empty()) {
5675 for (const auto& [displayId, monitors] : mGlobalMonitorsByDisplay) {
5676 dump += StringPrintf(INDENT "Global monitors on display %d:\n", displayId);
Michael Wright3dd60e22019-03-27 22:06:44 +00005677 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005678 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005679 } else {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005680 dump += INDENT "Global Monitors: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005681 }
5682
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005683 const nsecs_t currentTime = now();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005684
5685 // Dump recently dispatched or dropped events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005686 if (!mRecentQueue.empty()) {
5687 dump += StringPrintf(INDENT "RecentQueue: length=%zu\n", mRecentQueue.size());
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005688 for (const std::shared_ptr<EventEntry>& entry : mRecentQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005689 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005690 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005691 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005692 }
5693 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005694 dump += INDENT "RecentQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005695 }
5696
5697 // Dump event currently being dispatched.
5698 if (mPendingEvent) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005699 dump += INDENT "PendingEvent:\n";
5700 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005701 dump += mPendingEvent->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005702 dump += StringPrintf(", age=%" PRId64 "ms\n",
5703 ns2ms(currentTime - mPendingEvent->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005704 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005705 dump += INDENT "PendingEvent: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005706 }
5707
5708 // Dump inbound events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005709 if (!mInboundQueue.empty()) {
5710 dump += StringPrintf(INDENT "InboundQueue: length=%zu\n", mInboundQueue.size());
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005711 for (const std::shared_ptr<EventEntry>& entry : mInboundQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005712 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005713 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005714 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005715 }
5716 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005717 dump += INDENT "InboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005718 }
5719
Prabir Pradhancef936d2021-07-21 16:17:52 +00005720 if (!mCommandQueue.empty()) {
5721 dump += StringPrintf(INDENT "CommandQueue: size=%zu\n", mCommandQueue.size());
5722 } else {
5723 dump += INDENT "CommandQueue: <empty>\n";
5724 }
5725
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005726 if (!mConnectionsByToken.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005727 dump += INDENT "Connections:\n";
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005728 for (const auto& [token, connection] : mConnectionsByToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005729 dump += StringPrintf(INDENT2 "%i: channelName='%s', windowName='%s', "
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005730 "status=%s, monitor=%s, responsive=%s\n",
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005731 connection->inputChannel->getFd().get(),
5732 connection->getInputChannelName().c_str(),
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08005733 connection->getWindowName().c_str(),
5734 ftl::enum_string(connection->status).c_str(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005735 toString(connection->monitor), toString(connection->responsive));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005736
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005737 if (!connection->outboundQueue.empty()) {
5738 dump += StringPrintf(INDENT3 "OutboundQueue: length=%zu\n",
5739 connection->outboundQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005740 dump += dumpQueue(connection->outboundQueue, currentTime);
5741
Michael Wrightd02c5b62014-02-10 15:10:22 -08005742 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005743 dump += INDENT3 "OutboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005744 }
5745
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005746 if (!connection->waitQueue.empty()) {
5747 dump += StringPrintf(INDENT3 "WaitQueue: length=%zu\n",
5748 connection->waitQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005749 dump += dumpQueue(connection->waitQueue, currentTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005750 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005751 dump += INDENT3 "WaitQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005752 }
Siarhei Vishniakoud38a1e02023-07-18 11:55:17 -07005753 std::stringstream inputStateDump;
5754 inputStateDump << connection->inputState;
5755 if (!isEmpty(inputStateDump)) {
5756 dump += INDENT3 "InputState: ";
5757 dump += inputStateDump.str() + "\n";
5758 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005759 }
5760 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005761 dump += INDENT "Connections: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005762 }
5763
5764 if (isAppSwitchPendingLocked()) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005765 dump += StringPrintf(INDENT "AppSwitch: pending, due in %" PRId64 "ms\n",
5766 ns2ms(mAppSwitchDueTime - now()));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005767 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005768 dump += INDENT "AppSwitch: not pending\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005769 }
5770
Antonio Kantek15beb512022-06-13 22:35:41 +00005771 if (!mTouchModePerDisplay.empty()) {
5772 dump += INDENT "TouchModePerDisplay:\n";
5773 for (const auto& [displayId, touchMode] : mTouchModePerDisplay) {
5774 dump += StringPrintf(INDENT2 "Display: %" PRId32 " TouchMode: %s\n", displayId,
5775 std::to_string(touchMode).c_str());
5776 }
5777 } else {
5778 dump += INDENT "TouchModePerDisplay: <none>\n";
5779 }
5780
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005781 dump += INDENT "Configuration:\n";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005782 dump += StringPrintf(INDENT2 "KeyRepeatDelay: %" PRId64 "ms\n", ns2ms(mConfig.keyRepeatDelay));
5783 dump += StringPrintf(INDENT2 "KeyRepeatTimeout: %" PRId64 "ms\n",
5784 ns2ms(mConfig.keyRepeatTimeout));
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00005785 dump += mLatencyTracker.dump(INDENT2);
Siarhei Vishniakoua04181f2021-03-26 05:56:49 +00005786 dump += mLatencyAggregator.dump(INDENT2);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005787}
5788
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005789void InputDispatcher::dumpMonitors(std::string& dump, const std::vector<Monitor>& monitors) const {
Michael Wright3dd60e22019-03-27 22:06:44 +00005790 const size_t numMonitors = monitors.size();
5791 for (size_t i = 0; i < numMonitors; i++) {
5792 const Monitor& monitor = monitors[i];
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005793 const std::shared_ptr<InputChannel>& channel = monitor.inputChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005794 dump += StringPrintf(INDENT2 "%zu: '%s', ", i, channel->getName().c_str());
5795 dump += "\n";
5796 }
5797}
5798
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005799class LooperEventCallback : public LooperCallback {
5800public:
5801 LooperEventCallback(std::function<int(int events)> callback) : mCallback(callback) {}
5802 int handleEvent(int /*fd*/, int events, void* /*data*/) override { return mCallback(events); }
5803
5804private:
5805 std::function<int(int events)> mCallback;
5806};
5807
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005808Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputChannel(const std::string& name) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00005809 if (DEBUG_CHANNEL_CREATION) {
5810 ALOGD("channel '%s' ~ createInputChannel", name.c_str());
5811 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005812
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005813 std::unique_ptr<InputChannel> serverChannel;
Garfield Tan15601662020-09-22 15:32:38 -07005814 std::unique_ptr<InputChannel> clientChannel;
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005815 status_t result = InputChannel::openInputChannelPair(name, serverChannel, clientChannel);
Garfield Tan15601662020-09-22 15:32:38 -07005816
5817 if (result) {
5818 return base::Error(result) << "Failed to open input channel pair with name " << name;
5819 }
5820
Michael Wrightd02c5b62014-02-10 15:10:22 -08005821 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005822 std::scoped_lock _l(mLock);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005823 const sp<IBinder>& token = serverChannel->getConnectionToken();
Garfield Tan15601662020-09-22 15:32:38 -07005824 int fd = serverChannel->getFd();
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07005825 std::shared_ptr<Connection> connection =
5826 std::make_shared<Connection>(std::move(serverChannel), /*monitor=*/false,
5827 mIdGenerator);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005828
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005829 if (mConnectionsByToken.find(token) != mConnectionsByToken.end()) {
5830 ALOGE("Created a new connection, but the token %p is already known", token.get());
5831 }
5832 mConnectionsByToken.emplace(token, connection);
5833
5834 std::function<int(int events)> callback = std::bind(&InputDispatcher::handleReceiveCallback,
5835 this, std::placeholders::_1, token);
5836
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005837 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, sp<LooperEventCallback>::make(callback),
5838 nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005839 } // release lock
5840
5841 // Wake the looper because some connections have changed.
5842 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07005843 return clientChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005844}
5845
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005846Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputMonitor(int32_t displayId,
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005847 const std::string& name,
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005848 gui::Pid pid) {
Garfield Tan15601662020-09-22 15:32:38 -07005849 std::shared_ptr<InputChannel> serverChannel;
5850 std::unique_ptr<InputChannel> clientChannel;
5851 status_t result = openInputChannelPair(name, serverChannel, clientChannel);
5852 if (result) {
5853 return base::Error(result) << "Failed to open input channel pair with name " << name;
5854 }
5855
Michael Wright3dd60e22019-03-27 22:06:44 +00005856 { // acquire lock
5857 std::scoped_lock _l(mLock);
5858
5859 if (displayId < 0) {
Garfield Tan15601662020-09-22 15:32:38 -07005860 return base::Error(BAD_VALUE) << "Attempted to create input monitor with name " << name
5861 << " without a specified display.";
Michael Wright3dd60e22019-03-27 22:06:44 +00005862 }
5863
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07005864 std::shared_ptr<Connection> connection =
5865 std::make_shared<Connection>(serverChannel, /*monitor=*/true, mIdGenerator);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005866 const sp<IBinder>& token = serverChannel->getConnectionToken();
Garfield Tan15601662020-09-22 15:32:38 -07005867 const int fd = serverChannel->getFd();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005868
5869 if (mConnectionsByToken.find(token) != mConnectionsByToken.end()) {
5870 ALOGE("Created a new connection, but the token %p is already known", token.get());
5871 }
5872 mConnectionsByToken.emplace(token, connection);
5873 std::function<int(int events)> callback = std::bind(&InputDispatcher::handleReceiveCallback,
5874 this, std::placeholders::_1, token);
Michael Wright3dd60e22019-03-27 22:06:44 +00005875
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005876 mGlobalMonitorsByDisplay[displayId].emplace_back(serverChannel, pid);
Michael Wright3dd60e22019-03-27 22:06:44 +00005877
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005878 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, sp<LooperEventCallback>::make(callback),
5879 nullptr);
Michael Wright3dd60e22019-03-27 22:06:44 +00005880 }
Garfield Tan15601662020-09-22 15:32:38 -07005881
Michael Wright3dd60e22019-03-27 22:06:44 +00005882 // Wake the looper because some connections have changed.
5883 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07005884 return clientChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005885}
5886
Garfield Tan15601662020-09-22 15:32:38 -07005887status_t InputDispatcher::removeInputChannel(const sp<IBinder>& connectionToken) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005888 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005889 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005890
Harry Cutts33476232023-01-30 19:57:29 +00005891 status_t status = removeInputChannelLocked(connectionToken, /*notify=*/false);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005892 if (status) {
5893 return status;
5894 }
5895 } // release lock
5896
5897 // Wake the poll loop because removing the connection may have changed the current
5898 // synchronization state.
5899 mLooper->wake();
5900 return OK;
5901}
5902
Garfield Tan15601662020-09-22 15:32:38 -07005903status_t InputDispatcher::removeInputChannelLocked(const sp<IBinder>& connectionToken,
5904 bool notify) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07005905 std::shared_ptr<Connection> connection = getConnectionLocked(connectionToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005906 if (connection == nullptr) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005907 // Connection can be removed via socket hang up or an explicit call to 'removeInputChannel'
Michael Wrightd02c5b62014-02-10 15:10:22 -08005908 return BAD_VALUE;
5909 }
5910
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005911 removeConnectionLocked(connection);
Robert Carr5c8a0262018-10-03 16:30:44 -07005912
Michael Wrightd02c5b62014-02-10 15:10:22 -08005913 if (connection->monitor) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005914 removeMonitorChannelLocked(connectionToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005915 }
5916
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005917 mLooper->removeFd(connection->inputChannel->getFd());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005918
5919 nsecs_t currentTime = now();
5920 abortBrokenDispatchCycleLocked(currentTime, connection, notify);
5921
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08005922 connection->status = Connection::Status::ZOMBIE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005923 return OK;
5924}
5925
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005926void InputDispatcher::removeMonitorChannelLocked(const sp<IBinder>& connectionToken) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005927 for (auto it = mGlobalMonitorsByDisplay.begin(); it != mGlobalMonitorsByDisplay.end();) {
5928 auto& [displayId, monitors] = *it;
5929 std::erase_if(monitors, [connectionToken](const Monitor& monitor) {
5930 return monitor.inputChannel->getConnectionToken() == connectionToken;
5931 });
Michael Wright3dd60e22019-03-27 22:06:44 +00005932
Michael Wright3dd60e22019-03-27 22:06:44 +00005933 if (monitors.empty()) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005934 it = mGlobalMonitorsByDisplay.erase(it);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005935 } else {
5936 ++it;
5937 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005938 }
5939}
5940
Michael Wright3dd60e22019-03-27 22:06:44 +00005941status_t InputDispatcher::pilferPointers(const sp<IBinder>& token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005942 std::scoped_lock _l(mLock);
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00005943 return pilferPointersLocked(token);
5944}
Michael Wright3dd60e22019-03-27 22:06:44 +00005945
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00005946status_t InputDispatcher::pilferPointersLocked(const sp<IBinder>& token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005947 const std::shared_ptr<InputChannel> requestingChannel = getInputChannelLocked(token);
5948 if (!requestingChannel) {
Siarhei Vishniakou8384e0d2023-09-18 18:48:27 -07005949 LOG(WARNING)
5950 << "Attempted to pilfer pointers from an un-registered channel or invalid token";
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005951 return BAD_VALUE;
Michael Wright3dd60e22019-03-27 22:06:44 +00005952 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005953
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005954 auto [statePtr, windowPtr, displayId] = findTouchStateWindowAndDisplayLocked(token);
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005955 if (statePtr == nullptr || windowPtr == nullptr) {
Siarhei Vishniakou8384e0d2023-09-18 18:48:27 -07005956 LOG(WARNING)
5957 << "Attempted to pilfer points from a channel without any on-going pointer streams."
5958 " Ignoring.";
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005959 return BAD_VALUE;
5960 }
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005961 std::set<int32_t> deviceIds = windowPtr->getTouchingDeviceIds();
5962 if (deviceIds.size() != 1) {
5963 LOG(WARNING) << "Can't pilfer. Currently touching devices: " << dumpSet(deviceIds)
5964 << " in window: " << windowPtr->dump();
5965 return BAD_VALUE;
5966 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005967
Siarhei Vishniakou8384e0d2023-09-18 18:48:27 -07005968 for (const DeviceId deviceId : deviceIds) {
5969 TouchState& state = *statePtr;
5970 TouchedWindow& window = *windowPtr;
5971 // Send cancel events to all the input channels we're stealing from.
5972 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
5973 "input channel stole pointer stream");
5974 options.deviceId = deviceId;
5975 options.displayId = displayId;
5976 std::bitset<MAX_POINTER_ID + 1> pointerIds = window.getTouchingPointers(deviceId);
5977 options.pointerIds = pointerIds;
5978 std::string canceledWindows;
5979 for (const TouchedWindow& w : state.windows) {
5980 const std::shared_ptr<InputChannel> channel =
5981 getInputChannelLocked(w.windowHandle->getToken());
5982 if (channel != nullptr && channel->getConnectionToken() != token) {
5983 synthesizeCancelationEventsForInputChannelLocked(channel, options);
5984 canceledWindows += canceledWindows.empty() ? "[" : ", ";
5985 canceledWindows += channel->getName();
5986 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005987 }
Siarhei Vishniakou8384e0d2023-09-18 18:48:27 -07005988 canceledWindows += canceledWindows.empty() ? "[]" : "]";
5989 LOG(INFO) << "Channel " << requestingChannel->getName()
5990 << " is stealing input gesture for device " << deviceId << " from "
5991 << canceledWindows;
5992
5993 // Prevent the gesture from being sent to any other windows.
5994 // This only blocks relevant pointers to be sent to other windows
5995 window.addPilferingPointers(deviceId, pointerIds);
5996
5997 state.cancelPointersForWindowsExcept(deviceId, pointerIds, token);
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005998 }
Michael Wright3dd60e22019-03-27 22:06:44 +00005999 return OK;
6000}
6001
Prabir Pradhan99987712020-11-10 18:43:05 -08006002void InputDispatcher::requestPointerCapture(const sp<IBinder>& windowToken, bool enabled) {
6003 { // acquire lock
6004 std::scoped_lock _l(mLock);
6005 if (DEBUG_FOCUS) {
chaviw98318de2021-05-19 16:45:23 -05006006 const sp<WindowInfoHandle> windowHandle = getWindowHandleLocked(windowToken);
Prabir Pradhan99987712020-11-10 18:43:05 -08006007 ALOGI("Request to %s Pointer Capture from: %s.", enabled ? "enable" : "disable",
6008 windowHandle != nullptr ? windowHandle->getName().c_str()
6009 : "token without window");
6010 }
6011
Vishnu Nairc519ff72021-01-21 08:23:08 -08006012 const sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Prabir Pradhan99987712020-11-10 18:43:05 -08006013 if (focusedToken != windowToken) {
6014 ALOGW("Ignoring request to %s Pointer Capture: window does not have focus.",
6015 enabled ? "enable" : "disable");
6016 return;
6017 }
6018
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006019 if (enabled == mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006020 ALOGW("Ignoring request to %s Pointer Capture: "
6021 "window has %s requested pointer capture.",
6022 enabled ? "enable" : "disable", enabled ? "already" : "not");
6023 return;
6024 }
6025
Christine Franksb768bb42021-11-29 12:11:31 -08006026 if (enabled) {
6027 if (std::find(mIneligibleDisplaysForPointerCapture.begin(),
6028 mIneligibleDisplaysForPointerCapture.end(),
6029 mFocusedDisplayId) != mIneligibleDisplaysForPointerCapture.end()) {
6030 ALOGW("Ignoring request to enable Pointer Capture: display is not eligible");
6031 return;
6032 }
6033 }
6034
Prabir Pradhan99987712020-11-10 18:43:05 -08006035 setPointerCaptureLocked(enabled);
6036 } // release lock
6037
6038 // Wake the thread to process command entries.
6039 mLooper->wake();
6040}
6041
Christine Franksb768bb42021-11-29 12:11:31 -08006042void InputDispatcher::setDisplayEligibilityForPointerCapture(int32_t displayId, bool isEligible) {
6043 { // acquire lock
6044 std::scoped_lock _l(mLock);
6045 std::erase(mIneligibleDisplaysForPointerCapture, displayId);
6046 if (!isEligible) {
6047 mIneligibleDisplaysForPointerCapture.push_back(displayId);
6048 }
6049 } // release lock
6050}
6051
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00006052std::optional<gui::Pid> InputDispatcher::findMonitorPidByTokenLocked(const sp<IBinder>& token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006053 for (const auto& [_, monitors] : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00006054 for (const Monitor& monitor : monitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07006055 if (monitor.inputChannel->getConnectionToken() == token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006056 return monitor.pid;
Michael Wright3dd60e22019-03-27 22:06:44 +00006057 }
6058 }
6059 }
6060 return std::nullopt;
6061}
6062
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006063std::shared_ptr<Connection> InputDispatcher::getConnectionLocked(
6064 const sp<IBinder>& inputConnectionToken) const {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07006065 if (inputConnectionToken == nullptr) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07006066 return nullptr;
Arthur Hung3b413f22018-10-26 18:05:34 +08006067 }
6068
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00006069 for (const auto& [token, connection] : mConnectionsByToken) {
6070 if (token == inputConnectionToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07006071 return connection;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006072 }
6073 }
Robert Carr4e670e52018-08-15 13:26:12 -07006074
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07006075 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006076}
6077
Siarhei Vishniakouad991402020-10-28 11:40:09 -05006078std::string InputDispatcher::getConnectionNameLocked(const sp<IBinder>& connectionToken) const {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006079 std::shared_ptr<Connection> connection = getConnectionLocked(connectionToken);
Siarhei Vishniakouad991402020-10-28 11:40:09 -05006080 if (connection == nullptr) {
6081 return "<nullptr>";
6082 }
6083 return connection->getInputChannelName();
6084}
6085
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006086void InputDispatcher::removeConnectionLocked(const std::shared_ptr<Connection>& connection) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006087 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00006088 mConnectionsByToken.erase(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07006089}
6090
Prabir Pradhancef936d2021-07-21 16:17:52 +00006091void InputDispatcher::doDispatchCycleFinishedCommand(nsecs_t finishTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006092 const std::shared_ptr<Connection>& connection,
6093 uint32_t seq, bool handled,
6094 nsecs_t consumeTime) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006095 // Handle post-event policy actions.
Prabir Pradhancef936d2021-07-21 16:17:52 +00006096 bool restartEvent;
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006097
6098 { // Start critical section
6099 auto dispatchEntryIt =
6100 std::find_if(connection->waitQueue.begin(), connection->waitQueue.end(),
6101 [seq](auto& e) { return e->seq == seq; });
6102 if (dispatchEntryIt == connection->waitQueue.end()) {
6103 return;
6104 }
6105
6106 DispatchEntry& dispatchEntry = **dispatchEntryIt;
6107
6108 const nsecs_t eventDuration = finishTime - dispatchEntry.deliveryTime;
6109 if (eventDuration > SLOW_EVENT_PROCESSING_WARNING_TIMEOUT) {
6110 ALOGI("%s spent %" PRId64 "ms processing %s", connection->getWindowName().c_str(),
6111 ns2ms(eventDuration), dispatchEntry.eventEntry->getDescription().c_str());
6112 }
6113 if (shouldReportFinishedEvent(dispatchEntry, *connection)) {
6114 mLatencyTracker.trackFinishedEvent(dispatchEntry.eventEntry->id,
6115 connection->inputChannel->getConnectionToken(),
6116 dispatchEntry.deliveryTime, consumeTime, finishTime);
6117 }
6118
6119 if (dispatchEntry.eventEntry->type == EventEntry::Type::KEY) {
6120 KeyEntry& keyEntry = static_cast<KeyEntry&>(*(dispatchEntry.eventEntry));
6121 restartEvent =
6122 afterKeyEventLockedInterruptable(connection, dispatchEntry, keyEntry, handled);
6123 } else if (dispatchEntry.eventEntry->type == EventEntry::Type::MOTION) {
6124 MotionEntry& motionEntry = static_cast<MotionEntry&>(*(dispatchEntry.eventEntry));
6125 restartEvent = afterMotionEventLockedInterruptable(connection, dispatchEntry,
6126 motionEntry, handled);
6127 } else {
6128 restartEvent = false;
6129 }
6130 } // End critical section: The -LockedInterruptable methods may have released the lock.
Prabir Pradhancef936d2021-07-21 16:17:52 +00006131
6132 // Dequeue the event and start the next cycle.
6133 // Because the lock might have been released, it is possible that the
6134 // contents of the wait queue to have been drained, so we need to double-check
6135 // a few things.
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006136 auto entryIt = std::find_if(connection->waitQueue.begin(), connection->waitQueue.end(),
6137 [seq](auto& e) { return e->seq == seq; });
6138 if (entryIt != connection->waitQueue.end()) {
6139 std::unique_ptr<DispatchEntry> dispatchEntry = std::move(*entryIt);
6140 connection->waitQueue.erase(entryIt);
6141
Prabir Pradhancef936d2021-07-21 16:17:52 +00006142 const sp<IBinder>& connectionToken = connection->inputChannel->getConnectionToken();
6143 mAnrTracker.erase(dispatchEntry->timeoutTime, connectionToken);
6144 if (!connection->responsive) {
6145 connection->responsive = isConnectionResponsive(*connection);
6146 if (connection->responsive) {
6147 // The connection was unresponsive, and now it's responsive.
6148 processConnectionResponsiveLocked(*connection);
6149 }
6150 }
6151 traceWaitQueueLength(*connection);
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08006152 if (restartEvent && connection->status == Connection::Status::NORMAL) {
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006153 connection->outboundQueue.emplace_front(std::move(dispatchEntry));
Prabir Pradhancef936d2021-07-21 16:17:52 +00006154 traceOutboundQueueLength(*connection);
6155 } else {
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006156 releaseDispatchEntry(std::move(dispatchEntry));
Prabir Pradhancef936d2021-07-21 16:17:52 +00006157 }
6158 }
6159
6160 // Start the next dispatch cycle for this connection.
6161 startDispatchCycleLocked(now(), connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006162}
6163
Prabir Pradhancef936d2021-07-21 16:17:52 +00006164void InputDispatcher::sendFocusChangedCommandLocked(const sp<IBinder>& oldToken,
6165 const sp<IBinder>& newToken) {
6166 auto command = [this, oldToken, newToken]() REQUIRES(mLock) {
6167 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00006168 mPolicy.notifyFocusChanged(oldToken, newToken);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006169 };
6170 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08006171}
6172
Prabir Pradhancef936d2021-07-21 16:17:52 +00006173void InputDispatcher::sendDropWindowCommandLocked(const sp<IBinder>& token, float x, float y) {
6174 auto command = [this, token, x, y]() REQUIRES(mLock) {
6175 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00006176 mPolicy.notifyDropWindow(token, x, y);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006177 };
6178 postCommandLocked(std::move(command));
Robert Carrf759f162018-11-13 12:57:11 -08006179}
6180
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006181void InputDispatcher::onAnrLocked(const std::shared_ptr<Connection>& connection) {
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006182 if (connection == nullptr) {
6183 LOG_ALWAYS_FATAL("Caller must check for nullness");
6184 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006185 // Since we are allowing the policy to extend the timeout, maybe the waitQueue
6186 // is already healthy again. Don't raise ANR in this situation
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006187 if (connection->waitQueue.empty()) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006188 ALOGI("Not raising ANR because the connection %s has recovered",
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006189 connection->inputChannel->getName().c_str());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006190 return;
6191 }
6192 /**
6193 * The "oldestEntry" is the entry that was first sent to the application. That entry, however,
6194 * may not be the one that caused the timeout to occur. One possibility is that window timeout
6195 * has changed. This could cause newer entries to time out before the already dispatched
6196 * entries. In that situation, the newest entries caused ANR. But in all likelihood, the app
6197 * processes the events linearly. So providing information about the oldest entry seems to be
6198 * most useful.
6199 */
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006200 DispatchEntry& oldestEntry = *connection->waitQueue.front();
6201 const nsecs_t currentWait = now() - oldestEntry.deliveryTime;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006202 std::string reason =
6203 android::base::StringPrintf("%s is not responding. Waited %" PRId64 "ms for %s",
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006204 connection->inputChannel->getName().c_str(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006205 ns2ms(currentWait),
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006206 oldestEntry.eventEntry->getDescription().c_str());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006207 sp<IBinder> connectionToken = connection->inputChannel->getConnectionToken();
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -06006208 updateLastAnrStateLocked(getWindowHandleLocked(connectionToken), reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006209
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006210 processConnectionUnresponsiveLocked(*connection, std::move(reason));
6211
6212 // Stop waking up for events on this connection, it is already unresponsive
6213 cancelEventsForAnrLocked(connection);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006214}
6215
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05006216void InputDispatcher::onAnrLocked(std::shared_ptr<InputApplicationHandle> application) {
6217 std::string reason =
6218 StringPrintf("%s does not have a focused window", application->getName().c_str());
6219 updateLastAnrStateLocked(*application, reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006220
Yabin Cui8eb9c552023-06-08 18:05:07 +00006221 auto command = [this, app = std::move(application)]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006222 scoped_unlock unlock(mLock);
Yabin Cuiced952f2023-06-09 21:12:51 +00006223 mPolicy.notifyNoFocusedWindowAnr(app);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006224 };
6225 postCommandLocked(std::move(command));
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00006226}
6227
chaviw98318de2021-05-19 16:45:23 -05006228void InputDispatcher::updateLastAnrStateLocked(const sp<WindowInfoHandle>& window,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006229 const std::string& reason) {
6230 const std::string windowLabel = getApplicationWindowLabel(nullptr, window);
6231 updateLastAnrStateLocked(windowLabel, reason);
6232}
6233
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05006234void InputDispatcher::updateLastAnrStateLocked(const InputApplicationHandle& application,
6235 const std::string& reason) {
6236 const std::string windowLabel = getApplicationWindowLabel(&application, nullptr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006237 updateLastAnrStateLocked(windowLabel, reason);
6238}
6239
6240void InputDispatcher::updateLastAnrStateLocked(const std::string& windowLabel,
6241 const std::string& reason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006242 // Capture a record of the InputDispatcher state at the time of the ANR.
Yi Kong9b14ac62018-07-17 13:48:38 -07006243 time_t t = time(nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006244 struct tm tm;
6245 localtime_r(&t, &tm);
6246 char timestr[64];
6247 strftime(timestr, sizeof(timestr), "%F %T", &tm);
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006248 mLastAnrState.clear();
6249 mLastAnrState += INDENT "ANR:\n";
6250 mLastAnrState += StringPrintf(INDENT2 "Time: %s\n", timestr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006251 mLastAnrState += StringPrintf(INDENT2 "Reason: %s\n", reason.c_str());
6252 mLastAnrState += StringPrintf(INDENT2 "Window: %s\n", windowLabel.c_str());
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006253 dumpDispatchStateLocked(mLastAnrState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006254}
6255
Prabir Pradhancef936d2021-07-21 16:17:52 +00006256void InputDispatcher::doInterceptKeyBeforeDispatchingCommand(const sp<IBinder>& focusedWindowToken,
6257 KeyEntry& entry) {
6258 const KeyEvent event = createKeyEvent(entry);
6259 nsecs_t delay = 0;
6260 { // release lock
6261 scoped_unlock unlock(mLock);
6262 android::base::Timer t;
Prabir Pradhana41d2442023-04-20 21:30:40 +00006263 delay = mPolicy.interceptKeyBeforeDispatching(focusedWindowToken, event, entry.policyFlags);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006264 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
6265 ALOGW("Excessive delay in interceptKeyBeforeDispatching; took %s ms",
6266 std::to_string(t.duration().count()).c_str());
6267 }
6268 } // acquire lock
Michael Wrightd02c5b62014-02-10 15:10:22 -08006269
6270 if (delay < 0) {
Michael Wright5caf55a2022-11-24 22:31:42 +00006271 entry.interceptKeyResult = KeyEntry::InterceptKeyResult::SKIP;
Prabir Pradhancef936d2021-07-21 16:17:52 +00006272 } else if (delay == 0) {
Michael Wright5caf55a2022-11-24 22:31:42 +00006273 entry.interceptKeyResult = KeyEntry::InterceptKeyResult::CONTINUE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006274 } else {
Michael Wright5caf55a2022-11-24 22:31:42 +00006275 entry.interceptKeyResult = KeyEntry::InterceptKeyResult::TRY_AGAIN_LATER;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006276 entry.interceptKeyWakeupTime = now() + delay;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006277 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006278}
6279
Prabir Pradhancef936d2021-07-21 16:17:52 +00006280void InputDispatcher::sendWindowUnresponsiveCommandLocked(const sp<IBinder>& token,
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00006281 std::optional<gui::Pid> pid,
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006282 std::string reason) {
Yabin Cui8eb9c552023-06-08 18:05:07 +00006283 auto command = [this, token, pid, r = std::move(reason)]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006284 scoped_unlock unlock(mLock);
Yabin Cuiced952f2023-06-09 21:12:51 +00006285 mPolicy.notifyWindowUnresponsive(token, pid, r);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006286 };
6287 postCommandLocked(std::move(command));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006288}
6289
Prabir Pradhanedd96402022-02-15 01:46:16 -08006290void InputDispatcher::sendWindowResponsiveCommandLocked(const sp<IBinder>& token,
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00006291 std::optional<gui::Pid> pid) {
Prabir Pradhanedd96402022-02-15 01:46:16 -08006292 auto command = [this, token, pid]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006293 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00006294 mPolicy.notifyWindowResponsive(token, pid);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006295 };
6296 postCommandLocked(std::move(command));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006297}
6298
6299/**
6300 * Tell the policy that a connection has become unresponsive so that it can start ANR.
6301 * Check whether the connection of interest is a monitor or a window, and add the corresponding
6302 * command entry to the command queue.
6303 */
6304void InputDispatcher::processConnectionUnresponsiveLocked(const Connection& connection,
6305 std::string reason) {
6306 const sp<IBinder>& connectionToken = connection.inputChannel->getConnectionToken();
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00006307 std::optional<gui::Pid> pid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006308 if (connection.monitor) {
6309 ALOGW("Monitor %s is unresponsive: %s", connection.inputChannel->getName().c_str(),
6310 reason.c_str());
Prabir Pradhanedd96402022-02-15 01:46:16 -08006311 pid = findMonitorPidByTokenLocked(connectionToken);
6312 } else {
6313 // The connection is a window
6314 ALOGW("Window %s is unresponsive: %s", connection.inputChannel->getName().c_str(),
6315 reason.c_str());
6316 const sp<WindowInfoHandle> handle = getWindowHandleLocked(connectionToken);
6317 if (handle != nullptr) {
6318 pid = handle->getInfo()->ownerPid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006319 }
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006320 }
Prabir Pradhanedd96402022-02-15 01:46:16 -08006321 sendWindowUnresponsiveCommandLocked(connectionToken, pid, std::move(reason));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006322}
6323
6324/**
6325 * Tell the policy that a connection has become responsive so that it can stop ANR.
6326 */
6327void InputDispatcher::processConnectionResponsiveLocked(const Connection& connection) {
6328 const sp<IBinder>& connectionToken = connection.inputChannel->getConnectionToken();
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00006329 std::optional<gui::Pid> pid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006330 if (connection.monitor) {
Prabir Pradhanedd96402022-02-15 01:46:16 -08006331 pid = findMonitorPidByTokenLocked(connectionToken);
6332 } else {
6333 // The connection is a window
6334 const sp<WindowInfoHandle> handle = getWindowHandleLocked(connectionToken);
6335 if (handle != nullptr) {
6336 pid = handle->getInfo()->ownerPid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006337 }
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006338 }
Prabir Pradhanedd96402022-02-15 01:46:16 -08006339 sendWindowResponsiveCommandLocked(connectionToken, pid);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006340}
6341
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006342bool InputDispatcher::afterKeyEventLockedInterruptable(
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006343 const std::shared_ptr<Connection>& connection, DispatchEntry& dispatchEntry,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006344 KeyEntry& keyEntry, bool handled) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006345 if (keyEntry.flags & AKEY_EVENT_FLAG_FALLBACK) {
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006346 if (!handled) {
6347 // Report the key as unhandled, since the fallback was not handled.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006348 mReporter->reportUnhandledKey(keyEntry.id);
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006349 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006350 return false;
6351 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006352
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006353 // Get the fallback key state.
6354 // Clear it out after dispatching the UP.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006355 int32_t originalKeyCode = keyEntry.keyCode;
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006356 std::optional<int32_t> fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006357 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006358 connection->inputState.removeFallbackKey(originalKeyCode);
6359 }
6360
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006361 if (handled || !dispatchEntry.hasForegroundTarget()) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006362 // If the application handles the original key for which we previously
6363 // generated a fallback or if the window is not a foreground window,
6364 // then cancel the associated fallback key, if any.
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006365 if (fallbackKeyCode) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006366 // Dispatch the unhandled key to the policy with the cancel flag.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006367 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6368 ALOGD("Unhandled key event: Asking policy to cancel fallback action. "
6369 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6370 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount,
6371 keyEntry.policyFlags);
6372 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006373 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006374 event.setFlags(event.getFlags() | AKEY_EVENT_FLAG_CANCELED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006375
6376 mLock.unlock();
6377
Prabir Pradhana41d2442023-04-20 21:30:40 +00006378 if (const auto unhandledKeyFallback =
6379 mPolicy.dispatchUnhandledKey(connection->inputChannel->getConnectionToken(),
6380 event, keyEntry.policyFlags);
6381 unhandledKeyFallback) {
6382 event = *unhandledKeyFallback;
6383 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006384
6385 mLock.lock();
6386
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006387 // Cancel the fallback key.
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006388 if (*fallbackKeyCode != AKEYCODE_UNKNOWN) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00006389 CancelationOptions options(CancelationOptions::Mode::CANCEL_FALLBACK_EVENTS,
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006390 "application handled the original non-fallback key "
6391 "or is no longer a foreground target, "
6392 "canceling previously dispatched fallback key");
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006393 options.keyCode = *fallbackKeyCode;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006394 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006395 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006396 connection->inputState.removeFallbackKey(originalKeyCode);
6397 }
6398 } else {
6399 // If the application did not handle a non-fallback key, first check
6400 // that we are in a good state to perform unhandled key event processing
6401 // Then ask the policy what to do with it.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006402 bool initialDown = keyEntry.action == AKEY_EVENT_ACTION_DOWN && keyEntry.repeatCount == 0;
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006403 if (!fallbackKeyCode && !initialDown) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006404 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6405 ALOGD("Unhandled key event: Skipping unhandled key event processing "
6406 "since this is not an initial down. "
6407 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6408 originalKeyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
6409 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006410 return false;
6411 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006412
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006413 // Dispatch the unhandled key to the policy.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006414 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6415 ALOGD("Unhandled key event: Asking policy to perform fallback action. "
6416 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6417 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
6418 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006419 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006420
6421 mLock.unlock();
6422
Prabir Pradhana41d2442023-04-20 21:30:40 +00006423 bool fallback = false;
6424 if (auto fb = mPolicy.dispatchUnhandledKey(connection->inputChannel->getConnectionToken(),
6425 event, keyEntry.policyFlags);
6426 fb) {
6427 fallback = true;
6428 event = *fb;
6429 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006430
6431 mLock.lock();
6432
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08006433 if (connection->status != Connection::Status::NORMAL) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006434 connection->inputState.removeFallbackKey(originalKeyCode);
6435 return false;
6436 }
6437
6438 // Latch the fallback keycode for this key on an initial down.
6439 // The fallback keycode cannot change at any other point in the lifecycle.
6440 if (initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006441 if (fallback) {
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006442 *fallbackKeyCode = event.getKeyCode();
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006443 } else {
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006444 *fallbackKeyCode = AKEYCODE_UNKNOWN;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006445 }
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006446 connection->inputState.setFallbackKey(originalKeyCode, *fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006447 }
6448
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006449 ALOG_ASSERT(fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006450
6451 // Cancel the fallback key if the policy decides not to send it anymore.
6452 // We will continue to dispatch the key to the policy but we will no
6453 // longer dispatch a fallback key to the application.
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006454 if (*fallbackKeyCode != AKEYCODE_UNKNOWN &&
6455 (!fallback || *fallbackKeyCode != event.getKeyCode())) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006456 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6457 if (fallback) {
6458 ALOGD("Unhandled key event: Policy requested to send key %d"
6459 "as a fallback for %d, but on the DOWN it had requested "
6460 "to send %d instead. Fallback canceled.",
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006461 event.getKeyCode(), originalKeyCode, *fallbackKeyCode);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006462 } else {
6463 ALOGD("Unhandled key event: Policy did not request fallback for %d, "
6464 "but on the DOWN it had requested to send %d. "
6465 "Fallback canceled.",
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006466 originalKeyCode, *fallbackKeyCode);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006467 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006468 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006469
Michael Wrightfb04fd52022-11-24 22:31:11 +00006470 CancelationOptions options(CancelationOptions::Mode::CANCEL_FALLBACK_EVENTS,
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006471 "canceling fallback, policy no longer desires it");
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006472 options.keyCode = *fallbackKeyCode;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006473 synthesizeCancelationEventsForConnectionLocked(connection, options);
6474
6475 fallback = false;
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006476 *fallbackKeyCode = AKEYCODE_UNKNOWN;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006477 if (keyEntry.action != AKEY_EVENT_ACTION_UP) {
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006478 connection->inputState.setFallbackKey(originalKeyCode, *fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006479 }
6480 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006481
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006482 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6483 {
6484 std::string msg;
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006485 const std::map<int32_t, int32_t>& fallbackKeys =
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006486 connection->inputState.getFallbackKeys();
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006487 for (const auto& [key, value] : fallbackKeys) {
6488 msg += StringPrintf(", %d->%d", key, value);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006489 }
6490 ALOGD("Unhandled key event: %zu currently tracked fallback keys%s.",
6491 fallbackKeys.size(), msg.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006492 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006493 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006494
6495 if (fallback) {
6496 // Restart the dispatch cycle using the fallback key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006497 keyEntry.eventTime = event.getEventTime();
6498 keyEntry.deviceId = event.getDeviceId();
6499 keyEntry.source = event.getSource();
6500 keyEntry.displayId = event.getDisplayId();
6501 keyEntry.flags = event.getFlags() | AKEY_EVENT_FLAG_FALLBACK;
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006502 keyEntry.keyCode = *fallbackKeyCode;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006503 keyEntry.scanCode = event.getScanCode();
6504 keyEntry.metaState = event.getMetaState();
6505 keyEntry.repeatCount = event.getRepeatCount();
6506 keyEntry.downTime = event.getDownTime();
6507 keyEntry.syntheticRepeat = false;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006508
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006509 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6510 ALOGD("Unhandled key event: Dispatching fallback key. "
6511 "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006512 originalKeyCode, *fallbackKeyCode, keyEntry.metaState);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006513 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006514 return true; // restart the event
6515 } else {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006516 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6517 ALOGD("Unhandled key event: No fallback key.");
6518 }
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006519
6520 // Report the key as unhandled, since there is no fallback key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006521 mReporter->reportUnhandledKey(keyEntry.id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006522 }
6523 }
6524 return false;
6525}
6526
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006527bool InputDispatcher::afterMotionEventLockedInterruptable(
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006528 const std::shared_ptr<Connection>& connection, DispatchEntry& dispatchEntry,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006529 MotionEntry& motionEntry, bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006530 return false;
6531}
6532
Michael Wrightd02c5b62014-02-10 15:10:22 -08006533void InputDispatcher::traceInboundQueueLengthLocked() {
6534 if (ATRACE_ENABLED()) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07006535 ATRACE_INT("iq", mInboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006536 }
6537}
6538
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006539void InputDispatcher::traceOutboundQueueLength(const Connection& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006540 if (ATRACE_ENABLED()) {
6541 char counterName[40];
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006542 snprintf(counterName, sizeof(counterName), "oq:%s", connection.getWindowName().c_str());
6543 ATRACE_INT(counterName, connection.outboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006544 }
6545}
6546
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006547void InputDispatcher::traceWaitQueueLength(const Connection& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006548 if (ATRACE_ENABLED()) {
6549 char counterName[40];
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006550 snprintf(counterName, sizeof(counterName), "wq:%s", connection.getWindowName().c_str());
6551 ATRACE_INT(counterName, connection.waitQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006552 }
6553}
6554
Siarhei Vishniakou5e20f272023-06-08 17:24:44 -07006555void InputDispatcher::dump(std::string& dump) const {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006556 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006557
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006558 dump += "Input Dispatcher State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08006559 dumpDispatchStateLocked(dump);
6560
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006561 if (!mLastAnrState.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006562 dump += "\nInput Dispatcher State at time of last ANR:\n";
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006563 dump += mLastAnrState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006564 }
6565}
6566
6567void InputDispatcher::monitor() {
6568 // Acquire and release the lock to ensure that the dispatcher has not deadlocked.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006569 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006570 mLooper->wake();
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006571 mDispatcherIsAlive.wait(_l);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006572}
6573
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08006574/**
6575 * Wake up the dispatcher and wait until it processes all events and commands.
6576 * The notification of mDispatcherEnteredIdle is guaranteed to happen after wake(), so
6577 * this method can be safely called from any thread, as long as you've ensured that
6578 * the work you are interested in completing has already been queued.
6579 */
Siarhei Vishniakoua66d65e2023-06-16 10:32:51 -07006580bool InputDispatcher::waitForIdle() const {
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08006581 /**
6582 * Timeout should represent the longest possible time that a device might spend processing
6583 * events and commands.
6584 */
6585 constexpr std::chrono::duration TIMEOUT = 100ms;
6586 std::unique_lock lock(mLock);
6587 mLooper->wake();
6588 std::cv_status result = mDispatcherEnteredIdle.wait_for(lock, TIMEOUT);
6589 return result == std::cv_status::no_timeout;
6590}
6591
Vishnu Naire798b472020-07-23 13:52:21 -07006592/**
6593 * Sets focus to the window identified by the token. This must be called
6594 * after updating any input window handles.
6595 *
6596 * Params:
6597 * request.token - input channel token used to identify the window that should gain focus.
6598 * request.focusedToken - the token that the caller expects currently to be focused. If the
6599 * specified token does not match the currently focused window, this request will be dropped.
6600 * If the specified focused token matches the currently focused window, the call will succeed.
6601 * Set this to "null" if this call should succeed no matter what the currently focused token is.
6602 * request.timestamp - SYSTEM_TIME_MONOTONIC timestamp in nanos set by the client (wm)
6603 * when requesting the focus change. This determines which request gets
6604 * precedence if there is a focus change request from another source such as pointer down.
6605 */
Vishnu Nair958da932020-08-21 17:12:37 -07006606void InputDispatcher::setFocusedWindow(const FocusRequest& request) {
6607 { // acquire lock
6608 std::scoped_lock _l(mLock);
Vishnu Nairc519ff72021-01-21 08:23:08 -08006609 std::optional<FocusResolver::FocusChanges> changes =
6610 mFocusResolver.setFocusedWindow(request, getWindowHandlesLocked(request.displayId));
6611 if (changes) {
6612 onFocusChangedLocked(*changes);
Vishnu Nair958da932020-08-21 17:12:37 -07006613 }
6614 } // release lock
6615 // Wake up poll loop since it may need to make new input dispatching choices.
6616 mLooper->wake();
6617}
6618
Vishnu Nairc519ff72021-01-21 08:23:08 -08006619void InputDispatcher::onFocusChangedLocked(const FocusResolver::FocusChanges& changes) {
6620 if (changes.oldFocus) {
6621 std::shared_ptr<InputChannel> focusedInputChannel = getInputChannelLocked(changes.oldFocus);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006622 if (focusedInputChannel) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00006623 CancelationOptions options(CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS,
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006624 "focus left window");
6625 synthesizeCancelationEventsForInputChannelLocked(focusedInputChannel, options);
Harry Cutts33476232023-01-30 19:57:29 +00006626 enqueueFocusEventLocked(changes.oldFocus, /*hasFocus=*/false, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006627 }
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006628 }
Vishnu Nairc519ff72021-01-21 08:23:08 -08006629 if (changes.newFocus) {
Siarhei Vishniakouc033dfb2023-10-03 10:45:16 -07006630 resetNoFocusedWindowTimeoutLocked();
Harry Cutts33476232023-01-30 19:57:29 +00006631 enqueueFocusEventLocked(changes.newFocus, /*hasFocus=*/true, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006632 }
6633
Prabir Pradhan99987712020-11-10 18:43:05 -08006634 // If a window has pointer capture, then it must have focus. We need to ensure that this
6635 // contract is upheld when pointer capture is being disabled due to a loss of window focus.
6636 // If the window loses focus before it loses pointer capture, then the window can be in a state
6637 // where it has pointer capture but not focus, violating the contract. Therefore we must
6638 // dispatch the pointer capture event before the focus event. Since focus events are added to
6639 // the front of the queue (above), we add the pointer capture event to the front of the queue
6640 // after the focus events are added. This ensures the pointer capture event ends up at the
6641 // front.
6642 disablePointerCaptureForcedLocked();
6643
Vishnu Nairc519ff72021-01-21 08:23:08 -08006644 if (mFocusedDisplayId == changes.displayId) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006645 sendFocusChangedCommandLocked(changes.oldFocus, changes.newFocus);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006646 }
6647}
Vishnu Nair958da932020-08-21 17:12:37 -07006648
Prabir Pradhan99987712020-11-10 18:43:05 -08006649void InputDispatcher::disablePointerCaptureForcedLocked() {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006650 if (!mCurrentPointerCaptureRequest.enable && !mWindowTokenWithPointerCapture) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006651 return;
6652 }
6653
6654 ALOGD_IF(DEBUG_FOCUS, "Disabling Pointer Capture because the window lost focus.");
6655
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006656 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006657 setPointerCaptureLocked(false);
6658 }
6659
6660 if (!mWindowTokenWithPointerCapture) {
6661 // No need to send capture changes because no window has capture.
6662 return;
6663 }
6664
6665 if (mPendingEvent != nullptr) {
6666 // Move the pending event to the front of the queue. This will give the chance
6667 // for the pending event to be dropped if it is a captured event.
6668 mInboundQueue.push_front(mPendingEvent);
6669 mPendingEvent = nullptr;
6670 }
6671
6672 auto entry = std::make_unique<PointerCaptureChangedEntry>(mIdGenerator.nextId(), now(),
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006673 mCurrentPointerCaptureRequest);
Prabir Pradhan99987712020-11-10 18:43:05 -08006674 mInboundQueue.push_front(std::move(entry));
6675}
6676
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006677void InputDispatcher::setPointerCaptureLocked(bool enable) {
6678 mCurrentPointerCaptureRequest.enable = enable;
6679 mCurrentPointerCaptureRequest.seq++;
6680 auto command = [this, request = mCurrentPointerCaptureRequest]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006681 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00006682 mPolicy.setPointerCapture(request);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006683 };
6684 postCommandLocked(std::move(command));
Prabir Pradhan99987712020-11-10 18:43:05 -08006685}
6686
Vishnu Nair599f1412021-06-21 10:39:58 -07006687void InputDispatcher::displayRemoved(int32_t displayId) {
6688 { // acquire lock
6689 std::scoped_lock _l(mLock);
6690 // Set an empty list to remove all handles from the specific display.
Harry Cutts101ee9b2023-07-06 18:04:14 +00006691 setInputWindowsLocked(/*windowInfoHandles=*/{}, displayId);
Vishnu Nair599f1412021-06-21 10:39:58 -07006692 setFocusedApplicationLocked(displayId, nullptr);
6693 // Call focus resolver to clean up stale requests. This must be called after input windows
6694 // have been removed for the removed display.
6695 mFocusResolver.displayRemoved(displayId);
Christine Franksb768bb42021-11-29 12:11:31 -08006696 // Reset pointer capture eligibility, regardless of previous state.
6697 std::erase(mIneligibleDisplaysForPointerCapture, displayId);
Antonio Kantek15beb512022-06-13 22:35:41 +00006698 // Remove the associated touch mode state.
6699 mTouchModePerDisplay.erase(displayId);
Siarhei Vishniakou5c02a712023-05-15 15:45:02 -07006700 mVerifiersByDisplay.erase(displayId);
Vishnu Nair599f1412021-06-21 10:39:58 -07006701 } // release lock
6702
6703 // Wake up poll loop since it may need to make new input dispatching choices.
6704 mLooper->wake();
6705}
6706
Patrick Williamsd828f302023-04-28 17:52:08 -05006707void InputDispatcher::onWindowInfosChanged(const gui::WindowInfosUpdate& update) {
chaviw15fab6f2021-06-07 14:15:52 -05006708 // The listener sends the windows as a flattened array. Separate the windows by display for
6709 // more convenient parsing.
6710 std::unordered_map<int32_t, std::vector<sp<WindowInfoHandle>>> handlesPerDisplay;
Patrick Williamsd828f302023-04-28 17:52:08 -05006711 for (const auto& info : update.windowInfos) {
chaviw15fab6f2021-06-07 14:15:52 -05006712 handlesPerDisplay.emplace(info.displayId, std::vector<sp<WindowInfoHandle>>());
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07006713 handlesPerDisplay[info.displayId].push_back(sp<WindowInfoHandle>::make(info));
chaviw15fab6f2021-06-07 14:15:52 -05006714 }
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006715
6716 { // acquire lock
6717 std::scoped_lock _l(mLock);
Prabir Pradhan814fe082022-07-22 20:22:18 +00006718
6719 // Ensure that we have an entry created for all existing displays so that if a displayId has
6720 // no windows, we can tell that the windows were removed from the display.
6721 for (const auto& [displayId, _] : mWindowHandlesByDisplay) {
6722 handlesPerDisplay[displayId];
6723 }
6724
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006725 mDisplayInfos.clear();
Patrick Williamsd828f302023-04-28 17:52:08 -05006726 for (const auto& displayInfo : update.displayInfos) {
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006727 mDisplayInfos.emplace(displayInfo.displayId, displayInfo);
6728 }
6729
6730 for (const auto& [displayId, handles] : handlesPerDisplay) {
6731 setInputWindowsLocked(handles, displayId);
6732 }
Patrick Williams9464b2c2023-05-23 11:22:04 -05006733
6734 if (update.vsyncId < mWindowInfosVsyncId) {
6735 ALOGE("Received out of order window infos update. Last update vsync id: %" PRId64
6736 ", current update vsync id: %" PRId64,
6737 mWindowInfosVsyncId, update.vsyncId);
6738 }
6739 mWindowInfosVsyncId = update.vsyncId;
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006740 }
6741 // Wake up poll loop since it may need to make new input dispatching choices.
6742 mLooper->wake();
chaviw15fab6f2021-06-07 14:15:52 -05006743}
6744
Vishnu Nair062a8672021-09-03 16:07:44 -07006745bool InputDispatcher::shouldDropInput(
6746 const EventEntry& entry, const sp<android::gui::WindowInfoHandle>& windowHandle) const {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006747 if (windowHandle->getInfo()->inputConfig.test(WindowInfo::InputConfig::DROP_INPUT) ||
6748 (windowHandle->getInfo()->inputConfig.test(
6749 WindowInfo::InputConfig::DROP_INPUT_IF_OBSCURED) &&
Vishnu Nair062a8672021-09-03 16:07:44 -07006750 isWindowObscuredLocked(windowHandle))) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006751 ALOGW("Dropping %s event targeting %s as requested by the input configuration {%s} on "
6752 "display %" PRId32 ".",
Vishnu Nair062a8672021-09-03 16:07:44 -07006753 ftl::enum_string(entry.type).c_str(), windowHandle->getName().c_str(),
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006754 windowHandle->getInfo()->inputConfig.string().c_str(),
Vishnu Nair062a8672021-09-03 16:07:44 -07006755 windowHandle->getInfo()->displayId);
6756 return true;
6757 }
6758 return false;
6759}
6760
Siarhei Vishniakou18050092021-09-01 13:32:49 -07006761void InputDispatcher::DispatcherWindowListener::onWindowInfosChanged(
Patrick Williamsd828f302023-04-28 17:52:08 -05006762 const gui::WindowInfosUpdate& update) {
6763 mDispatcher.onWindowInfosChanged(update);
Siarhei Vishniakou18050092021-09-01 13:32:49 -07006764}
6765
Arthur Hungdfd528e2021-12-08 13:23:04 +00006766void InputDispatcher::cancelCurrentTouch() {
6767 {
6768 std::scoped_lock _l(mLock);
6769 ALOGD("Canceling all ongoing pointer gestures on all displays.");
Michael Wrightfb04fd52022-11-24 22:31:11 +00006770 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
Arthur Hungdfd528e2021-12-08 13:23:04 +00006771 "cancel current touch");
6772 synthesizeCancelationEventsForAllConnectionsLocked(options);
6773
6774 mTouchStatesByDisplay.clear();
Arthur Hungdfd528e2021-12-08 13:23:04 +00006775 }
6776 // Wake up poll loop since there might be work to do.
6777 mLooper->wake();
6778}
6779
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006780void InputDispatcher::setMonitorDispatchingTimeoutForTest(std::chrono::nanoseconds timeout) {
6781 std::scoped_lock _l(mLock);
6782 mMonitorDispatchingTimeout = timeout;
6783}
6784
Arthur Hungc539dbb2022-12-08 07:45:36 +00006785void InputDispatcher::slipWallpaperTouch(ftl::Flags<InputTarget::Flags> targetFlags,
6786 const sp<WindowInfoHandle>& oldWindowHandle,
6787 const sp<WindowInfoHandle>& newWindowHandle,
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07006788 TouchState& state, int32_t deviceId, int32_t pointerId,
Siarhei Vishniakoubf880522023-05-01 11:03:22 -07006789 std::vector<InputTarget>& targets) const {
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08006790 std::bitset<MAX_POINTER_ID + 1> pointerIds;
6791 pointerIds.set(pointerId);
Arthur Hungc539dbb2022-12-08 07:45:36 +00006792 const bool oldHasWallpaper = oldWindowHandle->getInfo()->inputConfig.test(
6793 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
6794 const bool newHasWallpaper = targetFlags.test(InputTarget::Flags::FOREGROUND) &&
6795 newWindowHandle->getInfo()->inputConfig.test(
6796 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
6797 const sp<WindowInfoHandle> oldWallpaper =
6798 oldHasWallpaper ? state.getWallpaperWindow() : nullptr;
6799 const sp<WindowInfoHandle> newWallpaper =
6800 newHasWallpaper ? findWallpaperWindowBelow(newWindowHandle) : nullptr;
6801 if (oldWallpaper == newWallpaper) {
6802 return;
6803 }
6804
6805 if (oldWallpaper != nullptr) {
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08006806 const TouchedWindow& oldTouchedWindow = state.getTouchedWindow(oldWallpaper);
6807 addWindowTargetLocked(oldWallpaper,
6808 oldTouchedWindow.targetFlags |
6809 InputTarget::Flags::DISPATCH_AS_SLIPPERY_EXIT,
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07006810 pointerIds, oldTouchedWindow.getDownTimeInTarget(deviceId), targets);
6811 state.removeTouchingPointerFromWindow(deviceId, pointerId, oldWallpaper);
Arthur Hungc539dbb2022-12-08 07:45:36 +00006812 }
6813
6814 if (newWallpaper != nullptr) {
6815 state.addOrUpdateWindow(newWallpaper,
6816 InputTarget::Flags::DISPATCH_AS_SLIPPERY_ENTER |
6817 InputTarget::Flags::WINDOW_IS_OBSCURED |
6818 InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED,
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07006819 deviceId, pointerIds);
Arthur Hungc539dbb2022-12-08 07:45:36 +00006820 }
6821}
6822
6823void InputDispatcher::transferWallpaperTouch(ftl::Flags<InputTarget::Flags> oldTargetFlags,
6824 ftl::Flags<InputTarget::Flags> newTargetFlags,
6825 const sp<WindowInfoHandle> fromWindowHandle,
6826 const sp<WindowInfoHandle> toWindowHandle,
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07006827 TouchState& state, int32_t deviceId,
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08006828 std::bitset<MAX_POINTER_ID + 1> pointerIds) {
Arthur Hungc539dbb2022-12-08 07:45:36 +00006829 const bool oldHasWallpaper = oldTargetFlags.test(InputTarget::Flags::FOREGROUND) &&
6830 fromWindowHandle->getInfo()->inputConfig.test(
6831 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
6832 const bool newHasWallpaper = newTargetFlags.test(InputTarget::Flags::FOREGROUND) &&
6833 toWindowHandle->getInfo()->inputConfig.test(
6834 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
6835
6836 const sp<WindowInfoHandle> oldWallpaper =
6837 oldHasWallpaper ? state.getWallpaperWindow() : nullptr;
6838 const sp<WindowInfoHandle> newWallpaper =
6839 newHasWallpaper ? findWallpaperWindowBelow(toWindowHandle) : nullptr;
6840 if (oldWallpaper == newWallpaper) {
6841 return;
6842 }
6843
6844 if (oldWallpaper != nullptr) {
6845 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
6846 "transferring touch focus to another window");
6847 state.removeWindowByToken(oldWallpaper->getToken());
6848 synthesizeCancelationEventsForWindowLocked(oldWallpaper, options);
6849 }
6850
6851 if (newWallpaper != nullptr) {
6852 nsecs_t downTimeInTarget = now();
6853 ftl::Flags<InputTarget::Flags> wallpaperFlags =
6854 oldTargetFlags & (InputTarget::Flags::SPLIT | InputTarget::Flags::DISPATCH_AS_IS);
6855 wallpaperFlags |= InputTarget::Flags::WINDOW_IS_OBSCURED |
6856 InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED;
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07006857 state.addOrUpdateWindow(newWallpaper, wallpaperFlags, deviceId, pointerIds,
6858 downTimeInTarget);
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006859 std::shared_ptr<Connection> wallpaperConnection =
6860 getConnectionLocked(newWallpaper->getToken());
Arthur Hungc539dbb2022-12-08 07:45:36 +00006861 if (wallpaperConnection != nullptr) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006862 std::shared_ptr<Connection> toConnection =
6863 getConnectionLocked(toWindowHandle->getToken());
Arthur Hungc539dbb2022-12-08 07:45:36 +00006864 toConnection->inputState.mergePointerStateTo(wallpaperConnection->inputState);
6865 synthesizePointerDownEventsForConnectionLocked(downTimeInTarget, wallpaperConnection,
6866 wallpaperFlags);
6867 }
6868 }
6869}
6870
6871sp<WindowInfoHandle> InputDispatcher::findWallpaperWindowBelow(
6872 const sp<WindowInfoHandle>& windowHandle) const {
6873 const std::vector<sp<WindowInfoHandle>>& windowHandles =
6874 getWindowHandlesLocked(windowHandle->getInfo()->displayId);
6875 bool foundWindow = false;
6876 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
6877 if (!foundWindow && otherHandle != windowHandle) {
6878 continue;
6879 }
6880 if (windowHandle == otherHandle) {
6881 foundWindow = true;
6882 continue;
6883 }
6884
6885 if (otherHandle->getInfo()->inputConfig.test(WindowInfo::InputConfig::IS_WALLPAPER)) {
6886 return otherHandle;
6887 }
6888 }
6889 return nullptr;
6890}
6891
Nergi Rahardi730cf3c2023-04-13 12:41:17 +09006892void InputDispatcher::setKeyRepeatConfiguration(nsecs_t timeout, nsecs_t delay) {
6893 std::scoped_lock _l(mLock);
6894
6895 mConfig.keyRepeatTimeout = timeout;
6896 mConfig.keyRepeatDelay = delay;
6897}
6898
Garfield Tane84e6f92019-08-29 17:28:41 -07006899} // namespace android::inputdispatcher