blob: da7a2a412df8ab1ededce0756193997a778144b0 [file] [log] [blame]
Michael Wrightd02c5b62014-02-10 15:10:22 -08001/*
2 * Copyright (C) 2010 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#define LOG_TAG "InputDispatcher"
18#define ATRACE_TAG ATRACE_TAG_INPUT
19
John Recke0710582019-09-26 13:46:12 -070020#define LOG_NDEBUG 1
Michael Wrightd02c5b62014-02-10 15:10:22 -080021
Michael Wright2b3c3302018-03-02 17:19:13 +000022#include <android-base/chrono_utils.h>
Siarhei Vishniakoud010b012023-01-18 15:00:53 -080023#include <android-base/logging.h>
Peter Collingbourneb04b9b82021-02-08 12:09:47 -080024#include <android-base/properties.h>
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080025#include <android-base/stringprintf.h>
Siarhei Vishniakou70622952020-07-30 11:17:23 -050026#include <android/os/IInputConstants.h>
Robert Carr4e670e52018-08-15 13:26:12 -070027#include <binder/Binder.h>
Dominik Laskowski75788452021-02-09 18:51:25 -080028#include <ftl/enum.h>
Siarhei Vishniakou5c02a712023-05-15 15:45:02 -070029#include <log/log_event_list.h>
Siarhei Vishniakou31977182022-09-30 08:51:23 -070030#if defined(__ANDROID__)
chaviw15fab6f2021-06-07 14:15:52 -050031#include <gui/SurfaceComposerClient.h>
Siarhei Vishniakou31977182022-09-30 08:51:23 -070032#endif
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -080033#include <input/InputDevice.h>
Siarhei Vishniakou6e1e9872022-11-08 17:51:35 -080034#include <input/PrintTools.h>
tyiu1573a672023-02-21 22:38:32 +000035#include <openssl/mem.h>
Garfield Tan0fc2fa72019-08-29 17:22:15 -070036#include <powermanager/PowerManager.h>
Michael Wright44753b12020-07-08 13:48:11 +010037#include <unistd.h>
Garfield Tan0fc2fa72019-08-29 17:22:15 -070038#include <utils/Trace.h>
Michael Wrightd02c5b62014-02-10 15:10:22 -080039
Michael Wright44753b12020-07-08 13:48:11 +010040#include <cerrno>
41#include <cinttypes>
42#include <climits>
43#include <cstddef>
44#include <ctime>
45#include <queue>
46#include <sstream>
47
48#include "Connection.h"
Arthur Hung1a1007b2022-05-11 07:15:01 +000049#include "DebugConfig.h"
Chris Yef59a2f42020-10-16 12:55:26 -070050#include "InputDispatcher.h"
Michael Wright44753b12020-07-08 13:48:11 +010051
Michael Wrightd02c5b62014-02-10 15:10:22 -080052#define INDENT " "
53#define INDENT2 " "
54#define INDENT3 " "
55#define INDENT4 " "
56
Siarhei Vishniakou253f4642022-11-09 13:42:06 -080057using namespace android::ftl::flag_operators;
Siarhei Vishniakou23740b92023-04-21 11:30:20 -070058using android::base::Error;
Peter Collingbourneb04b9b82021-02-08 12:09:47 -080059using android::base::HwTimeoutMultiplier;
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +000060using android::base::Result;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080061using android::base::StringPrintf;
Prabir Pradhan48f8cb92021-08-26 14:05:36 -070062using android::gui::DisplayInfo;
chaviw98318de2021-05-19 16:45:23 -050063using android::gui::FocusRequest;
64using android::gui::TouchOcclusionMode;
65using android::gui::WindowInfo;
66using android::gui::WindowInfoHandle;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -080067using android::os::InputEventInjectionResult;
68using android::os::InputEventInjectionSync;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080069
Garfield Tane84e6f92019-08-29 17:28:41 -070070namespace android::inputdispatcher {
Michael Wrightd02c5b62014-02-10 15:10:22 -080071
Prabir Pradhancef936d2021-07-21 16:17:52 +000072namespace {
Prabir Pradhancef936d2021-07-21 16:17:52 +000073// Temporarily releases a held mutex for the lifetime of the instance.
74// Named to match std::scoped_lock
75class scoped_unlock {
76public:
77 explicit scoped_unlock(std::mutex& mutex) : mMutex(mutex) { mMutex.unlock(); }
78 ~scoped_unlock() { mMutex.lock(); }
79
80private:
81 std::mutex& mMutex;
82};
83
Michael Wrightd02c5b62014-02-10 15:10:22 -080084// Default input dispatching timeout if there is no focused application or paused window
85// from which to determine an appropriate dispatching timeout.
Peter Collingbourneb04b9b82021-02-08 12:09:47 -080086const std::chrono::duration DEFAULT_INPUT_DISPATCHING_TIMEOUT = std::chrono::milliseconds(
87 android::os::IInputConstants::UNMULTIPLIED_DEFAULT_DISPATCHING_TIMEOUT_MILLIS *
88 HwTimeoutMultiplier());
Michael Wrightd02c5b62014-02-10 15:10:22 -080089
90// Amount of time to allow for all pending events to be processed when an app switch
91// key is on the way. This is used to preempt input dispatch and drop input events
92// when an application takes too long to respond and the user has pressed an app switch key.
Michael Wright2b3c3302018-03-02 17:19:13 +000093constexpr nsecs_t APP_SWITCH_TIMEOUT = 500 * 1000000LL; // 0.5sec
Michael Wrightd02c5b62014-02-10 15:10:22 -080094
Siarhei Vishniakou289e9242022-02-15 14:50:16 -080095const std::chrono::duration STALE_EVENT_TIMEOUT = std::chrono::seconds(10) * HwTimeoutMultiplier();
Michael Wrightd02c5b62014-02-10 15:10:22 -080096
Michael Wrightd02c5b62014-02-10 15:10:22 -080097// Log a warning when an event takes longer than this to process, even if an ANR does not occur.
Michael Wright2b3c3302018-03-02 17:19:13 +000098constexpr nsecs_t SLOW_EVENT_PROCESSING_WARNING_TIMEOUT = 2000 * 1000000LL; // 2sec
99
100// Log a warning when an interception call takes longer than this to process.
101constexpr std::chrono::milliseconds SLOW_INTERCEPTION_THRESHOLD = 50ms;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800102
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700103// Additional key latency in case a connection is still processing some motion events.
104// This will help with the case when a user touched a button that opens a new window,
105// and gives us the chance to dispatch the key to this new window.
106constexpr std::chrono::nanoseconds KEY_WAITING_FOR_EVENTS_TIMEOUT = 500ms;
107
Michael Wrightd02c5b62014-02-10 15:10:22 -0800108// Number of recent events to keep for debugging purposes.
Michael Wright2b3c3302018-03-02 17:19:13 +0000109constexpr size_t RECENT_QUEUE_MAX_SIZE = 10;
110
Antonio Kantekea47acb2021-12-23 12:41:25 -0800111// Event log tags. See EventLogTags.logtags for reference.
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +0000112constexpr int LOGTAG_INPUT_INTERACTION = 62000;
113constexpr int LOGTAG_INPUT_FOCUS = 62001;
Arthur Hungb3307ee2021-10-14 10:57:37 +0000114constexpr int LOGTAG_INPUT_CANCEL = 62003;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +0000115
Prabir Pradhan33e3baa2022-12-06 20:30:22 +0000116const ui::Transform kIdentityTransform;
117
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000118inline nsecs_t now() {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800119 return systemTime(SYSTEM_TIME_MONOTONIC);
120}
121
Siarhei Vishniakoud38a1e02023-07-18 11:55:17 -0700122bool isEmpty(const std::stringstream& ss) {
123 return ss.rdbuf()->in_avail() == 0;
124}
125
Siarhei Vishniakou63b63612023-04-12 11:00:23 -0700126inline const std::string binderToString(const sp<IBinder>& binder) {
Bernardo Rufino49d99e42021-01-18 15:16:59 +0000127 if (binder == nullptr) {
128 return "<null>";
129 }
130 return StringPrintf("%p", binder.get());
131}
132
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +0000133static std::string uidString(const gui::Uid& uid) {
134 return uid.toString();
135}
136
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000137inline int32_t getMotionEventActionPointerIndex(int32_t action) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700138 return (action & AMOTION_EVENT_ACTION_POINTER_INDEX_MASK) >>
139 AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800140}
141
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700142Result<void> checkKeyAction(int32_t action) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800143 switch (action) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700144 case AKEY_EVENT_ACTION_DOWN:
145 case AKEY_EVENT_ACTION_UP:
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700146 return {};
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700147 default:
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700148 return Error() << "Key event has invalid action code " << action;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800149 }
150}
151
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700152Result<void> validateKeyEvent(int32_t action) {
153 return checkKeyAction(action);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800154}
155
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700156Result<void> checkMotionAction(int32_t action, int32_t actionButton, int32_t pointerCount) {
Siarhei Vishniakou2f61bdc2022-12-02 08:55:51 -0800157 switch (MotionEvent::getActionMasked(action)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700158 case AMOTION_EVENT_ACTION_DOWN:
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700159 case AMOTION_EVENT_ACTION_UP: {
160 if (pointerCount != 1) {
161 return Error() << "invalid pointer count " << pointerCount;
162 }
163 return {};
164 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700165 case AMOTION_EVENT_ACTION_MOVE:
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700166 case AMOTION_EVENT_ACTION_HOVER_ENTER:
167 case AMOTION_EVENT_ACTION_HOVER_MOVE:
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700168 case AMOTION_EVENT_ACTION_HOVER_EXIT: {
169 if (pointerCount < 1) {
170 return Error() << "invalid pointer count " << pointerCount;
171 }
172 return {};
173 }
Siarhei Vishniakou2f61bdc2022-12-02 08:55:51 -0800174 case AMOTION_EVENT_ACTION_CANCEL:
175 case AMOTION_EVENT_ACTION_OUTSIDE:
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700176 case AMOTION_EVENT_ACTION_SCROLL:
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700177 return {};
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700178 case AMOTION_EVENT_ACTION_POINTER_DOWN:
179 case AMOTION_EVENT_ACTION_POINTER_UP: {
Siarhei Vishniakou2f61bdc2022-12-02 08:55:51 -0800180 const int32_t index = MotionEvent::getActionIndex(action);
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700181 if (index < 0) {
182 return Error() << "invalid index " << index << " for "
183 << MotionEvent::actionToString(action);
184 }
185 if (index >= pointerCount) {
186 return Error() << "invalid index " << index << " for pointerCount " << pointerCount;
187 }
188 if (pointerCount <= 1) {
189 return Error() << "invalid pointer count " << pointerCount << " for "
190 << MotionEvent::actionToString(action);
191 }
192 return {};
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700193 }
194 case AMOTION_EVENT_ACTION_BUTTON_PRESS:
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700195 case AMOTION_EVENT_ACTION_BUTTON_RELEASE: {
196 if (actionButton == 0) {
197 return Error() << "action button should be nonzero for "
198 << MotionEvent::actionToString(action);
199 }
200 return {};
201 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700202 default:
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700203 return Error() << "invalid action " << action;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800204 }
205}
206
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000207int64_t millis(std::chrono::nanoseconds t) {
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -0500208 return std::chrono::duration_cast<std::chrono::milliseconds>(t).count();
209}
210
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700211Result<void> validateMotionEvent(int32_t action, int32_t actionButton, size_t pointerCount,
212 const PointerProperties* pointerProperties) {
213 Result<void> actionCheck = checkMotionAction(action, actionButton, pointerCount);
214 if (!actionCheck.ok()) {
215 return actionCheck;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800216 }
217 if (pointerCount < 1 || pointerCount > MAX_POINTERS) {
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700218 return Error() << "Motion event has invalid pointer count " << pointerCount
219 << "; value must be between 1 and " << MAX_POINTERS << ".";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800220 }
Siarhei Vishniakou8a878352023-01-30 14:05:01 -0800221 std::bitset<MAX_POINTER_ID + 1> pointerIdBits;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800222 for (size_t i = 0; i < pointerCount; i++) {
223 int32_t id = pointerProperties[i].id;
224 if (id < 0 || id > MAX_POINTER_ID) {
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700225 return Error() << "Motion event has invalid pointer id " << id
226 << "; value must be between 0 and " << MAX_POINTER_ID;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800227 }
Siarhei Vishniakou8a878352023-01-30 14:05:01 -0800228 if (pointerIdBits.test(id)) {
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700229 return Error() << "Motion event has duplicate pointer id " << id;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800230 }
Siarhei Vishniakou8a878352023-01-30 14:05:01 -0800231 pointerIdBits.set(id);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800232 }
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700233 return {};
234}
235
236Result<void> validateInputEvent(const InputEvent& event) {
237 switch (event.getType()) {
238 case InputEventType::KEY: {
239 const KeyEvent& key = static_cast<const KeyEvent&>(event);
240 const int32_t action = key.getAction();
241 return validateKeyEvent(action);
242 }
243 case InputEventType::MOTION: {
244 const MotionEvent& motion = static_cast<const MotionEvent&>(event);
245 const int32_t action = motion.getAction();
246 const size_t pointerCount = motion.getPointerCount();
247 const PointerProperties* pointerProperties = motion.getPointerProperties();
248 const int32_t actionButton = motion.getActionButton();
249 return validateMotionEvent(action, actionButton, pointerCount, pointerProperties);
250 }
251 default: {
252 return {};
253 }
254 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800255}
256
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000257std::string dumpRegion(const Region& region) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800258 if (region.isEmpty()) {
Bernardo Rufino53fc31e2020-11-03 11:01:07 +0000259 return "<empty>";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800260 }
261
Bernardo Rufino53fc31e2020-11-03 11:01:07 +0000262 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800263 bool first = true;
264 Region::const_iterator cur = region.begin();
265 Region::const_iterator const tail = region.end();
266 while (cur != tail) {
267 if (first) {
268 first = false;
269 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800270 dump += "|";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800271 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800272 dump += StringPrintf("[%d,%d][%d,%d]", cur->left, cur->top, cur->right, cur->bottom);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800273 cur++;
274 }
Bernardo Rufino53fc31e2020-11-03 11:01:07 +0000275 return dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800276}
277
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000278std::string dumpQueue(const std::deque<DispatchEntry*>& queue, nsecs_t currentTime) {
Siarhei Vishniakou14411c92020-09-18 21:15:05 -0500279 constexpr size_t maxEntries = 50; // max events to print
280 constexpr size_t skipBegin = maxEntries / 2;
281 const size_t skipEnd = queue.size() - maxEntries / 2;
282 // skip from maxEntries / 2 ... size() - maxEntries/2
283 // only print from 0 .. skipBegin and then from skipEnd .. size()
284
285 std::string dump;
286 for (size_t i = 0; i < queue.size(); i++) {
287 const DispatchEntry& entry = *queue[i];
288 if (i >= skipBegin && i < skipEnd) {
289 dump += StringPrintf(INDENT4 "<skipped %zu entries>\n", skipEnd - skipBegin);
290 i = skipEnd - 1; // it will be incremented to "skipEnd" by 'continue'
291 continue;
292 }
293 dump.append(INDENT4);
294 dump += entry.eventEntry->getDescription();
Siarhei Vishniakou253f4642022-11-09 13:42:06 -0800295 dump += StringPrintf(", seq=%" PRIu32 ", targetFlags=%s, resolvedAction=%d, age=%" PRId64
296 "ms",
297 entry.seq, entry.targetFlags.string().c_str(), entry.resolvedAction,
Siarhei Vishniakou14411c92020-09-18 21:15:05 -0500298 ns2ms(currentTime - entry.eventEntry->eventTime));
299 if (entry.deliveryTime != 0) {
300 // This entry was delivered, so add information on how long we've been waiting
301 dump += StringPrintf(", wait=%" PRId64 "ms", ns2ms(currentTime - entry.deliveryTime));
302 }
303 dump.append("\n");
304 }
305 return dump;
306}
307
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -0700308/**
309 * Find the entry in std::unordered_map by key, and return it.
310 * If the entry is not found, return a default constructed entry.
311 *
312 * Useful when the entries are vectors, since an empty vector will be returned
313 * if the entry is not found.
314 * Also useful when the entries are sp<>. If an entry is not found, nullptr is returned.
315 */
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700316template <typename K, typename V>
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000317V getValueByKey(const std::unordered_map<K, V>& map, K key) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -0700318 auto it = map.find(key);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700319 return it != map.end() ? it->second : V{};
Tiger Huang721e26f2018-07-24 22:26:19 +0800320}
321
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000322bool haveSameToken(const sp<WindowInfoHandle>& first, const sp<WindowInfoHandle>& second) {
chaviwaf87b3e2019-10-01 16:59:28 -0700323 if (first == second) {
324 return true;
325 }
326
327 if (first == nullptr || second == nullptr) {
328 return false;
329 }
330
331 return first->getToken() == second->getToken();
332}
333
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000334bool haveSameApplicationToken(const WindowInfo* first, const WindowInfo* second) {
Bernardo Rufino1ff9d592021-01-18 16:58:57 +0000335 if (first == nullptr || second == nullptr) {
336 return false;
337 }
338 return first->applicationInfo.token != nullptr &&
339 first->applicationInfo.token == second->applicationInfo.token;
340}
341
Siarhei Vishniakou8a878352023-01-30 14:05:01 -0800342template <typename T>
343size_t firstMarkedBit(T set) {
344 // TODO: replace with std::countr_zero from <bit> when that's available
345 LOG_ALWAYS_FATAL_IF(set.none());
346 size_t i = 0;
347 while (!set.test(i)) {
348 i++;
349 }
350 return i;
351}
352
Siarhei Vishniakou253f4642022-11-09 13:42:06 -0800353std::unique_ptr<DispatchEntry> createDispatchEntry(
354 const InputTarget& inputTarget, std::shared_ptr<EventEntry> eventEntry,
355 ftl::Flags<InputTarget::Flags> inputTargetFlags) {
chaviw1ff3d1e2020-07-01 15:53:47 -0700356 if (inputTarget.useDefaultPointerTransform()) {
357 const ui::Transform& transform = inputTarget.getDefaultPointerTransform();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700358 return std::make_unique<DispatchEntry>(eventEntry, inputTargetFlags, transform,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700359 inputTarget.displayTransform,
360 inputTarget.globalScaleFactor);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000361 }
362
363 ALOG_ASSERT(eventEntry->type == EventEntry::Type::MOTION);
364 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(*eventEntry);
365
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700366 std::vector<PointerCoords> pointerCoords;
367 pointerCoords.resize(motionEntry.pointerCount);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000368
369 // Use the first pointer information to normalize all other pointers. This could be any pointer
370 // as long as all other pointers are normalized to the same value and the final DispatchEntry
chaviw1ff3d1e2020-07-01 15:53:47 -0700371 // uses the transform for the normalized pointer.
372 const ui::Transform& firstPointerTransform =
Siarhei Vishniakou8a878352023-01-30 14:05:01 -0800373 inputTarget.pointerTransforms[firstMarkedBit(inputTarget.pointerIds)];
chaviw1ff3d1e2020-07-01 15:53:47 -0700374 ui::Transform inverseFirstTransform = firstPointerTransform.inverse();
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000375
376 // Iterate through all pointers in the event to normalize against the first.
377 for (uint32_t pointerIndex = 0; pointerIndex < motionEntry.pointerCount; pointerIndex++) {
378 const PointerProperties& pointerProperties = motionEntry.pointerProperties[pointerIndex];
379 uint32_t pointerId = uint32_t(pointerProperties.id);
chaviw1ff3d1e2020-07-01 15:53:47 -0700380 const ui::Transform& currTransform = inputTarget.pointerTransforms[pointerId];
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000381
382 pointerCoords[pointerIndex].copyFrom(motionEntry.pointerCoords[pointerIndex]);
chaviw1ff3d1e2020-07-01 15:53:47 -0700383 // First, apply the current pointer's transform to update the coordinates into
384 // window space.
385 pointerCoords[pointerIndex].transform(currTransform);
386 // Next, apply the inverse transform of the normalized coordinates so the
387 // current coordinates are transformed into the normalized coordinate space.
388 pointerCoords[pointerIndex].transform(inverseFirstTransform);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000389 }
390
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700391 std::unique_ptr<MotionEntry> combinedMotionEntry =
392 std::make_unique<MotionEntry>(motionEntry.id, motionEntry.eventTime,
393 motionEntry.deviceId, motionEntry.source,
394 motionEntry.displayId, motionEntry.policyFlags,
395 motionEntry.action, motionEntry.actionButton,
396 motionEntry.flags, motionEntry.metaState,
397 motionEntry.buttonState, motionEntry.classification,
398 motionEntry.edgeFlags, motionEntry.xPrecision,
399 motionEntry.yPrecision, motionEntry.xCursorPosition,
400 motionEntry.yCursorPosition, motionEntry.downTime,
401 motionEntry.pointerCount, motionEntry.pointerProperties,
Prabir Pradhan5beda762021-12-10 09:30:08 +0000402 pointerCoords.data());
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000403
404 if (motionEntry.injectionState) {
405 combinedMotionEntry->injectionState = motionEntry.injectionState;
406 combinedMotionEntry->injectionState->refCount += 1;
407 }
408
409 std::unique_ptr<DispatchEntry> dispatchEntry =
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700410 std::make_unique<DispatchEntry>(std::move(combinedMotionEntry), inputTargetFlags,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700411 firstPointerTransform, inputTarget.displayTransform,
412 inputTarget.globalScaleFactor);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000413 return dispatchEntry;
414}
415
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000416status_t openInputChannelPair(const std::string& name, std::shared_ptr<InputChannel>& serverChannel,
417 std::unique_ptr<InputChannel>& clientChannel) {
Garfield Tan15601662020-09-22 15:32:38 -0700418 std::unique_ptr<InputChannel> uniqueServerChannel;
419 status_t result = InputChannel::openInputChannelPair(name, uniqueServerChannel, clientChannel);
420
421 serverChannel = std::move(uniqueServerChannel);
422 return result;
423}
424
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -0500425template <typename T>
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000426bool sharedPointersEqual(const std::shared_ptr<T>& lhs, const std::shared_ptr<T>& rhs) {
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -0500427 if (lhs == nullptr && rhs == nullptr) {
428 return true;
429 }
430 if (lhs == nullptr || rhs == nullptr) {
431 return false;
432 }
433 return *lhs == *rhs;
434}
435
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000436KeyEvent createKeyEvent(const KeyEntry& entry) {
Siarhei Vishniakou2e2ea992020-12-15 02:57:19 +0000437 KeyEvent event;
438 event.initialize(entry.id, entry.deviceId, entry.source, entry.displayId, INVALID_HMAC,
439 entry.action, entry.flags, entry.keyCode, entry.scanCode, entry.metaState,
440 entry.repeatCount, entry.downTime, entry.eventTime);
441 return event;
442}
443
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000444bool shouldReportMetricsForConnection(const Connection& connection) {
Siarhei Vishniakouf2652122021-03-05 21:39:46 +0000445 // Do not keep track of gesture monitors. They receive every event and would disproportionately
446 // affect the statistics.
447 if (connection.monitor) {
448 return false;
449 }
450 // If the connection is experiencing ANR, let's skip it. We have separate ANR metrics
451 if (!connection.responsive) {
452 return false;
453 }
454 return true;
455}
456
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000457bool shouldReportFinishedEvent(const DispatchEntry& dispatchEntry, const Connection& connection) {
Siarhei Vishniakouf2652122021-03-05 21:39:46 +0000458 const EventEntry& eventEntry = *dispatchEntry.eventEntry;
459 const int32_t& inputEventId = eventEntry.id;
460 if (inputEventId != dispatchEntry.resolvedEventId) {
461 // Event was transmuted
462 return false;
463 }
464 if (inputEventId == android::os::IInputConstants::INVALID_INPUT_EVENT_ID) {
465 return false;
466 }
467 // Only track latency for events that originated from hardware
468 if (eventEntry.isSynthesized()) {
469 return false;
470 }
471 const EventEntry::Type& inputEventEntryType = eventEntry.type;
472 if (inputEventEntryType == EventEntry::Type::KEY) {
473 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
474 if (keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) {
475 return false;
476 }
477 } else if (inputEventEntryType == EventEntry::Type::MOTION) {
478 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
479 if (motionEntry.action == AMOTION_EVENT_ACTION_CANCEL ||
480 motionEntry.action == AMOTION_EVENT_ACTION_HOVER_EXIT) {
481 return false;
482 }
483 } else {
484 // Not a key or a motion
485 return false;
486 }
487 if (!shouldReportMetricsForConnection(connection)) {
488 return false;
489 }
490 return true;
491}
492
Prabir Pradhancef936d2021-07-21 16:17:52 +0000493/**
494 * Connection is responsive if it has no events in the waitQueue that are older than the
495 * current time.
496 */
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000497bool isConnectionResponsive(const Connection& connection) {
Prabir Pradhancef936d2021-07-21 16:17:52 +0000498 const nsecs_t currentTime = now();
499 for (const DispatchEntry* entry : connection.waitQueue) {
500 if (entry->timeoutTime < currentTime) {
501 return false;
502 }
503 }
504 return true;
505}
506
Antonio Kantekf16f2832021-09-28 04:39:20 +0000507// Returns true if the event type passed as argument represents a user activity.
508bool isUserActivityEvent(const EventEntry& eventEntry) {
509 switch (eventEntry.type) {
Josep del Riob3981622023-04-18 15:49:45 +0000510 case EventEntry::Type::CONFIGURATION_CHANGED:
511 case EventEntry::Type::DEVICE_RESET:
512 case EventEntry::Type::DRAG:
Antonio Kantekf16f2832021-09-28 04:39:20 +0000513 case EventEntry::Type::FOCUS:
514 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
Antonio Kantekf16f2832021-09-28 04:39:20 +0000515 case EventEntry::Type::SENSOR:
Josep del Riob3981622023-04-18 15:49:45 +0000516 case EventEntry::Type::TOUCH_MODE_CHANGED:
Antonio Kantekf16f2832021-09-28 04:39:20 +0000517 return false;
Antonio Kantekf16f2832021-09-28 04:39:20 +0000518 case EventEntry::Type::KEY:
519 case EventEntry::Type::MOTION:
520 return true;
521 }
522}
523
Prabir Pradhan3f90d312021-11-19 03:57:24 -0800524// Returns true if the given window can accept pointer events at the given display location.
Prabir Pradhan82e081e2022-12-06 09:50:09 +0000525bool windowAcceptsTouchAt(const WindowInfo& windowInfo, int32_t displayId, float x, float y,
Prabir Pradhan33e3baa2022-12-06 20:30:22 +0000526 bool isStylus, const ui::Transform& displayTransform) {
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -0800527 const auto inputConfig = windowInfo.inputConfig;
528 if (windowInfo.displayId != displayId ||
529 inputConfig.test(WindowInfo::InputConfig::NOT_VISIBLE)) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -0800530 return false;
531 }
Prabir Pradhand65552b2021-10-07 11:23:50 -0700532 const bool windowCanInterceptTouch = isStylus && windowInfo.interceptsStylus();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -0800533 if (inputConfig.test(WindowInfo::InputConfig::NOT_TOUCHABLE) && !windowCanInterceptTouch) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -0800534 return false;
535 }
Prabir Pradhan33e3baa2022-12-06 20:30:22 +0000536
537 // Window Manager works in the logical display coordinate space. When it specifies bounds for a
538 // window as (l, t, r, b), the range of x in [l, r) and y in [t, b) are considered to be inside
539 // the window. Points on the right and bottom edges should not be inside the window, so we need
540 // to be careful about performing a hit test when the display is rotated, since the "right" and
541 // "bottom" of the window will be different in the display (un-rotated) space compared to in the
542 // logical display in which WM determined the bounds. Perform the hit test in the logical
543 // display space to ensure these edges are considered correctly in all orientations.
544 const auto touchableRegion = displayTransform.transform(windowInfo.touchableRegion);
545 const auto p = displayTransform.transform(x, y);
546 if (!touchableRegion.contains(std::floor(p.x), std::floor(p.y))) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -0800547 return false;
548 }
549 return true;
550}
551
Prabir Pradhand65552b2021-10-07 11:23:50 -0700552bool isPointerFromStylus(const MotionEntry& entry, int32_t pointerIndex) {
553 return isFromSource(entry.source, AINPUT_SOURCE_STYLUS) &&
Prabir Pradhane5626962022-10-27 20:30:53 +0000554 isStylusToolType(entry.pointerProperties[pointerIndex].toolType);
Prabir Pradhand65552b2021-10-07 11:23:50 -0700555}
556
Siarhei Vishniakou253f4642022-11-09 13:42:06 -0800557// Determines if the given window can be targeted as InputTarget::Flags::FOREGROUND.
Prabir Pradhan6dfbf262022-03-14 15:24:30 +0000558// Foreground events are only sent to "foreground targetable" windows, but not all gestures sent to
559// such window are necessarily targeted with the flag. For example, an event with ACTION_OUTSIDE can
560// be sent to such a window, but it is not a foreground event and doesn't use
Siarhei Vishniakou253f4642022-11-09 13:42:06 -0800561// InputTarget::Flags::FOREGROUND.
Prabir Pradhan6dfbf262022-03-14 15:24:30 +0000562bool canReceiveForegroundTouches(const WindowInfo& info) {
563 // A non-touchable window can still receive touch events (e.g. in the case of
564 // STYLUS_INTERCEPTOR), so prevent such windows from receiving foreground events for touches.
565 return !info.inputConfig.test(gui::WindowInfo::InputConfig::NOT_TOUCHABLE) && !info.isSpy();
566}
567
Prabir Pradhanaeebeb42023-06-13 19:53:03 +0000568bool isWindowOwnedBy(const sp<WindowInfoHandle>& windowHandle, gui::Pid pid, gui::Uid uid) {
Antonio Kantek48710e42022-03-24 14:19:30 -0700569 if (windowHandle == nullptr) {
570 return false;
571 }
572 const WindowInfo* windowInfo = windowHandle->getInfo();
573 if (pid == windowInfo->ownerPid && uid == windowInfo->ownerUid) {
574 return true;
575 }
576 return false;
577}
578
Prabir Pradhan5735a322022-04-11 17:23:34 +0000579// Checks targeted injection using the window's owner's uid.
580// Returns an empty string if an entry can be sent to the given window, or an error message if the
581// entry is a targeted injection whose uid target doesn't match the window owner.
582std::optional<std::string> verifyTargetedInjection(const sp<WindowInfoHandle>& window,
583 const EventEntry& entry) {
584 if (entry.injectionState == nullptr || !entry.injectionState->targetUid) {
585 // The event was not injected, or the injected event does not target a window.
586 return {};
587 }
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +0000588 const auto uid = *entry.injectionState->targetUid;
Prabir Pradhan5735a322022-04-11 17:23:34 +0000589 if (window == nullptr) {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +0000590 return StringPrintf("No valid window target for injection into uid %s.",
591 uid.toString().c_str());
Prabir Pradhan5735a322022-04-11 17:23:34 +0000592 }
593 if (entry.injectionState->targetUid != window->getInfo()->ownerUid) {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +0000594 return StringPrintf("Injected event targeted at uid %s would be dispatched to window '%s' "
595 "owned by uid %s.",
596 uid.toString().c_str(), window->getName().c_str(),
597 window->getInfo()->ownerUid.toString().c_str());
Prabir Pradhan5735a322022-04-11 17:23:34 +0000598 }
599 return {};
600}
601
Prabir Pradhan82e081e2022-12-06 09:50:09 +0000602std::pair<float, float> resolveTouchedPosition(const MotionEntry& entry) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -0700603 const bool isFromMouse = isFromSource(entry.source, AINPUT_SOURCE_MOUSE);
604 // Always dispatch mouse events to cursor position.
605 if (isFromMouse) {
Prabir Pradhan82e081e2022-12-06 09:50:09 +0000606 return {entry.xCursorPosition, entry.yCursorPosition};
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -0700607 }
608
609 const int32_t pointerIndex = getMotionEventActionPointerIndex(entry.action);
Prabir Pradhan82e081e2022-12-06 09:50:09 +0000610 return {entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_X),
611 entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_Y)};
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -0700612}
613
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -0700614std::optional<nsecs_t> getDownTime(const EventEntry& eventEntry) {
615 if (eventEntry.type == EventEntry::Type::KEY) {
616 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
617 return keyEntry.downTime;
618 } else if (eventEntry.type == EventEntry::Type::MOTION) {
619 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
620 return motionEntry.downTime;
621 }
622 return std::nullopt;
623}
624
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000625/**
626 * Compare the old touch state to the new touch state, and generate the corresponding touched
627 * windows (== input targets).
628 * If a window had the hovering pointer, but now it doesn't, produce HOVER_EXIT for that window.
629 * If the pointer just entered the new window, produce HOVER_ENTER.
630 * For pointers remaining in the window, produce HOVER_MOVE.
631 */
632std::vector<TouchedWindow> getHoveringWindowsLocked(const TouchState* oldState,
633 const TouchState& newTouchState,
634 const MotionEntry& entry) {
635 std::vector<TouchedWindow> out;
636 const int32_t maskedAction = MotionEvent::getActionMasked(entry.action);
637 if (maskedAction != AMOTION_EVENT_ACTION_HOVER_ENTER &&
638 maskedAction != AMOTION_EVENT_ACTION_HOVER_MOVE &&
639 maskedAction != AMOTION_EVENT_ACTION_HOVER_EXIT) {
640 // Not a hover event - don't need to do anything
641 return out;
642 }
643
644 // We should consider all hovering pointers here. But for now, just use the first one
645 const int32_t pointerId = entry.pointerProperties[0].id;
646
647 std::set<sp<WindowInfoHandle>> oldWindows;
648 if (oldState != nullptr) {
649 oldWindows = oldState->getWindowsWithHoveringPointer(entry.deviceId, pointerId);
650 }
651
652 std::set<sp<WindowInfoHandle>> newWindows =
653 newTouchState.getWindowsWithHoveringPointer(entry.deviceId, pointerId);
654
655 // If the pointer is no longer in the new window set, send HOVER_EXIT.
656 for (const sp<WindowInfoHandle>& oldWindow : oldWindows) {
657 if (newWindows.find(oldWindow) == newWindows.end()) {
658 TouchedWindow touchedWindow;
659 touchedWindow.windowHandle = oldWindow;
660 touchedWindow.targetFlags = InputTarget::Flags::DISPATCH_AS_HOVER_EXIT;
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000661 out.push_back(touchedWindow);
662 }
663 }
664
665 for (const sp<WindowInfoHandle>& newWindow : newWindows) {
666 TouchedWindow touchedWindow;
667 touchedWindow.windowHandle = newWindow;
668 if (oldWindows.find(newWindow) == oldWindows.end()) {
669 // Any windows that have this pointer now, and didn't have it before, should get
670 // HOVER_ENTER
671 touchedWindow.targetFlags = InputTarget::Flags::DISPATCH_AS_HOVER_ENTER;
672 } else {
673 // This pointer was already sent to the window. Use ACTION_HOVER_MOVE.
Siarhei Vishniakouc2eb8502023-04-11 18:33:36 -0700674 if (CC_UNLIKELY(maskedAction != AMOTION_EVENT_ACTION_HOVER_MOVE)) {
675 LOG(FATAL) << "Expected ACTION_HOVER_MOVE instead of " << entry.getDescription();
676 }
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000677 touchedWindow.targetFlags = InputTarget::Flags::DISPATCH_AS_IS;
678 }
Siarhei Vishniakou0836a302023-05-03 13:54:30 -0700679 touchedWindow.addHoveringPointer(entry.deviceId, pointerId);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000680 if (canReceiveForegroundTouches(*newWindow->getInfo())) {
681 touchedWindow.targetFlags |= InputTarget::Flags::FOREGROUND;
682 }
683 out.push_back(touchedWindow);
684 }
685 return out;
686}
687
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -0800688template <typename T>
689std::vector<T>& operator+=(std::vector<T>& left, const std::vector<T>& right) {
690 left.insert(left.end(), right.begin(), right.end());
691 return left;
692}
693
Harry Cuttsb166c002023-05-09 13:06:05 +0000694// Filter windows in a TouchState and targets in a vector to remove untrusted windows/targets from
695// both.
696void filterUntrustedTargets(TouchState& touchState, std::vector<InputTarget>& targets) {
697 std::erase_if(touchState.windows, [&](const TouchedWindow& window) {
698 if (!window.windowHandle->getInfo()->inputConfig.test(
699 WindowInfo::InputConfig::TRUSTED_OVERLAY)) {
700 // In addition to TouchState, erase this window from the input targets! We don't have a
701 // good way to do this today except by adding a nested loop.
702 // TODO(b/282025641): simplify this code once InputTargets are being identified
703 // separately from TouchedWindows.
704 std::erase_if(targets, [&](const InputTarget& target) {
705 return target.inputChannel->getConnectionToken() == window.windowHandle->getToken();
706 });
707 return true;
708 }
709 return false;
710 });
711}
712
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000713} // namespace
714
Michael Wrightd02c5b62014-02-10 15:10:22 -0800715// --- InputDispatcher ---
716
Prabir Pradhana41d2442023-04-20 21:30:40 +0000717InputDispatcher::InputDispatcher(InputDispatcherPolicyInterface& policy)
Siarhei Vishniakou289e9242022-02-15 14:50:16 -0800718 : InputDispatcher(policy, STALE_EVENT_TIMEOUT) {}
719
Prabir Pradhana41d2442023-04-20 21:30:40 +0000720InputDispatcher::InputDispatcher(InputDispatcherPolicyInterface& policy,
Siarhei Vishniakou289e9242022-02-15 14:50:16 -0800721 std::chrono::nanoseconds staleEventTimeout)
Garfield Tan00f511d2019-06-12 16:55:40 -0700722 : mPolicy(policy),
723 mPendingEvent(nullptr),
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700724 mLastDropReason(DropReason::NOT_DROPPED),
Garfield Tanff1f1bb2020-01-28 13:24:04 -0800725 mIdGenerator(IdGenerator::Source::INPUT_DISPATCHER),
Garfield Tan00f511d2019-06-12 16:55:40 -0700726 mAppSwitchSawKeyDown(false),
Colin Cross5b799302022-10-18 21:52:41 -0700727 mAppSwitchDueTime(LLONG_MAX),
Garfield Tan00f511d2019-06-12 16:55:40 -0700728 mNextUnblockedEvent(nullptr),
Prabir Pradhan1376fcd2022-01-21 09:56:35 -0800729 mMonitorDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT),
Garfield Tan00f511d2019-06-12 16:55:40 -0700730 mDispatchEnabled(false),
731 mDispatchFrozen(false),
732 mInputFilterEnabled(false),
Bernardo Rufinoea97d182020-08-19 14:43:14 +0100733 mMaximumObscuringOpacityForTouch(1.0f),
Siarhei Vishniakou2508b872020-12-03 16:33:53 -1000734 mFocusedDisplayId(ADISPLAY_ID_DEFAULT),
Prabir Pradhan99987712020-11-10 18:43:05 -0800735 mWindowTokenWithPointerCapture(nullptr),
Siarhei Vishniakou289e9242022-02-15 14:50:16 -0800736 mStaleEventTimeout(staleEventTimeout),
Siarhei Vishniakoua04181f2021-03-26 05:56:49 +0000737 mLatencyAggregator(),
Antonio Kantek15beb512022-06-13 22:35:41 +0000738 mLatencyTracker(&mLatencyAggregator) {
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -0700739 mLooper = sp<Looper>::make(false);
Prabir Pradhanf93562f2018-11-29 12:13:37 -0800740 mReporter = createInputReporter();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800741
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -0700742 mWindowInfoListener = sp<DispatcherWindowListener>::make(*this);
Siarhei Vishniakou31977182022-09-30 08:51:23 -0700743#if defined(__ANDROID__)
Siarhei Vishniakou18050092021-09-01 13:32:49 -0700744 SurfaceComposerClient::getDefault()->addWindowInfosListener(mWindowInfoListener);
Siarhei Vishniakou31977182022-09-30 08:51:23 -0700745#endif
Yi Kong9b14ac62018-07-17 13:48:38 -0700746 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800747}
748
749InputDispatcher::~InputDispatcher() {
Prabir Pradhancef936d2021-07-21 16:17:52 +0000750 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800751
Prabir Pradhancef936d2021-07-21 16:17:52 +0000752 resetKeyRepeatLocked();
753 releasePendingEventLocked();
754 drainInboundQueueLocked();
755 mCommandQueue.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800756
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +0000757 while (!mConnectionsByToken.empty()) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -0700758 std::shared_ptr<Connection> connection = mConnectionsByToken.begin()->second;
Harry Cutts33476232023-01-30 19:57:29 +0000759 removeInputChannelLocked(connection->inputChannel->getConnectionToken(), /*notify=*/false);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800760 }
761}
762
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700763status_t InputDispatcher::start() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700764 if (mThread) {
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700765 return ALREADY_EXISTS;
766 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700767 mThread = std::make_unique<InputThread>(
768 "InputDispatcher", [this]() { dispatchOnce(); }, [this]() { mLooper->wake(); });
769 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700770}
771
772status_t InputDispatcher::stop() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700773 if (mThread && mThread->isCallingThread()) {
774 ALOGE("InputDispatcher cannot be stopped from its own thread!");
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700775 return INVALID_OPERATION;
776 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700777 mThread.reset();
778 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700779}
780
Michael Wrightd02c5b62014-02-10 15:10:22 -0800781void InputDispatcher::dispatchOnce() {
Colin Cross5b799302022-10-18 21:52:41 -0700782 nsecs_t nextWakeupTime = LLONG_MAX;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800783 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -0800784 std::scoped_lock _l(mLock);
785 mDispatcherIsAlive.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800786
787 // Run a dispatch loop if there are no pending commands.
788 // The dispatch loop might enqueue commands to run afterwards.
789 if (!haveCommandsLocked()) {
790 dispatchOnceInnerLocked(&nextWakeupTime);
791 }
792
793 // Run all pending commands if there are any.
794 // If any commands were run then force the next poll to wake up immediately.
Prabir Pradhancef936d2021-07-21 16:17:52 +0000795 if (runCommandsLockedInterruptable()) {
Colin Cross5b799302022-10-18 21:52:41 -0700796 nextWakeupTime = LLONG_MIN;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800797 }
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800798
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700799 // If we are still waiting for ack on some events,
800 // we might have to wake up earlier to check if an app is anr'ing.
801 const nsecs_t nextAnrCheck = processAnrsLocked();
802 nextWakeupTime = std::min(nextWakeupTime, nextAnrCheck);
803
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800804 // We are about to enter an infinitely long sleep, because we have no commands or
805 // pending or queued events
Colin Cross5b799302022-10-18 21:52:41 -0700806 if (nextWakeupTime == LLONG_MAX) {
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800807 mDispatcherEnteredIdle.notify_all();
808 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800809 } // release lock
810
811 // Wait for callback or timeout or wake. (make sure we round up, not down)
812 nsecs_t currentTime = now();
813 int timeoutMillis = toMillisecondTimeoutDelay(currentTime, nextWakeupTime);
814 mLooper->pollOnce(timeoutMillis);
815}
816
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700817/**
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500818 * Raise ANR if there is no focused window.
819 * Before the ANR is raised, do a final state check:
820 * 1. The currently focused application must be the same one we are waiting for.
821 * 2. Ensure we still don't have a focused window.
822 */
823void InputDispatcher::processNoFocusedWindowAnrLocked() {
824 // Check if the application that we are waiting for is still focused.
825 std::shared_ptr<InputApplicationHandle> focusedApplication =
826 getValueByKey(mFocusedApplicationHandlesByDisplay, mAwaitedApplicationDisplayId);
827 if (focusedApplication == nullptr ||
828 focusedApplication->getApplicationToken() !=
829 mAwaitedFocusedApplication->getApplicationToken()) {
830 // Unexpected because we should have reset the ANR timer when focused application changed
831 ALOGE("Waited for a focused window, but focused application has already changed to %s",
832 focusedApplication->getName().c_str());
833 return; // The focused application has changed.
834 }
835
chaviw98318de2021-05-19 16:45:23 -0500836 const sp<WindowInfoHandle>& focusedWindowHandle =
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500837 getFocusedWindowHandleLocked(mAwaitedApplicationDisplayId);
838 if (focusedWindowHandle != nullptr) {
839 return; // We now have a focused window. No need for ANR.
840 }
841 onAnrLocked(mAwaitedFocusedApplication);
842}
843
844/**
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700845 * Check if any of the connections' wait queues have events that are too old.
846 * If we waited for events to be ack'ed for more than the window timeout, raise an ANR.
847 * Return the time at which we should wake up next.
848 */
849nsecs_t InputDispatcher::processAnrsLocked() {
850 const nsecs_t currentTime = now();
Colin Cross5b799302022-10-18 21:52:41 -0700851 nsecs_t nextAnrCheck = LLONG_MAX;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700852 // Check if we are waiting for a focused window to appear. Raise ANR if waited too long
853 if (mNoFocusedWindowTimeoutTime.has_value() && mAwaitedFocusedApplication != nullptr) {
854 if (currentTime >= *mNoFocusedWindowTimeoutTime) {
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500855 processNoFocusedWindowAnrLocked();
Chris Yea209fde2020-07-22 13:54:51 -0700856 mAwaitedFocusedApplication.reset();
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500857 mNoFocusedWindowTimeoutTime = std::nullopt;
Colin Cross5b799302022-10-18 21:52:41 -0700858 return LLONG_MIN;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700859 } else {
Siarhei Vishniakou38a6d272020-10-20 20:29:33 -0500860 // Keep waiting. We will drop the event when mNoFocusedWindowTimeoutTime comes.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700861 nextAnrCheck = *mNoFocusedWindowTimeoutTime;
862 }
863 }
864
865 // Check if any connection ANRs are due
866 nextAnrCheck = std::min(nextAnrCheck, mAnrTracker.firstTimeout());
867 if (currentTime < nextAnrCheck) { // most likely scenario
868 return nextAnrCheck; // everything is normal. Let's check again at nextAnrCheck
869 }
870
871 // If we reached here, we have an unresponsive connection.
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -0700872 std::shared_ptr<Connection> connection = getConnectionLocked(mAnrTracker.firstToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700873 if (connection == nullptr) {
874 ALOGE("Could not find connection for entry %" PRId64, mAnrTracker.firstTimeout());
875 return nextAnrCheck;
876 }
877 connection->responsive = false;
878 // Stop waking up for this unresponsive connection
879 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000880 onAnrLocked(connection);
Colin Cross5b799302022-10-18 21:52:41 -0700881 return LLONG_MIN;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700882}
883
Prabir Pradhan1376fcd2022-01-21 09:56:35 -0800884std::chrono::nanoseconds InputDispatcher::getDispatchingTimeoutLocked(
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -0700885 const std::shared_ptr<Connection>& connection) {
Prabir Pradhan1376fcd2022-01-21 09:56:35 -0800886 if (connection->monitor) {
887 return mMonitorDispatchingTimeout;
888 }
889 const sp<WindowInfoHandle> window =
890 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700891 if (window != nullptr) {
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500892 return window->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700893 }
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500894 return DEFAULT_INPUT_DISPATCHING_TIMEOUT;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700895}
896
Michael Wrightd02c5b62014-02-10 15:10:22 -0800897void InputDispatcher::dispatchOnceInnerLocked(nsecs_t* nextWakeupTime) {
898 nsecs_t currentTime = now();
899
Jeff Browndc5992e2014-04-11 01:27:26 -0700900 // Reset the key repeat timer whenever normal dispatch is suspended while the
901 // device is in a non-interactive state. This is to ensure that we abort a key
902 // repeat if the device is just coming out of sleep.
903 if (!mDispatchEnabled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800904 resetKeyRepeatLocked();
905 }
906
907 // If dispatching is frozen, do not process timeouts or try to deliver any new events.
908 if (mDispatchFrozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +0100909 if (DEBUG_FOCUS) {
910 ALOGD("Dispatch frozen. Waiting some more.");
911 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800912 return;
913 }
914
915 // Optimize latency of app switches.
916 // Essentially we start a short timeout when an app switch key (HOME / ENDCALL) has
917 // been pressed. When it expires, we preempt dispatch and drop all other pending events.
918 bool isAppSwitchDue = mAppSwitchDueTime <= currentTime;
919 if (mAppSwitchDueTime < *nextWakeupTime) {
920 *nextWakeupTime = mAppSwitchDueTime;
921 }
922
923 // Ready to start a new event.
924 // If we don't already have a pending event, go grab one.
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700925 if (!mPendingEvent) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700926 if (mInboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800927 if (isAppSwitchDue) {
928 // The inbound queue is empty so the app switch key we were waiting
929 // for will never arrive. Stop waiting for it.
930 resetPendingAppSwitchLocked(false);
931 isAppSwitchDue = false;
932 }
933
934 // Synthesize a key repeat if appropriate.
935 if (mKeyRepeatState.lastKeyEntry) {
936 if (currentTime >= mKeyRepeatState.nextRepeatTime) {
937 mPendingEvent = synthesizeKeyRepeatLocked(currentTime);
938 } else {
939 if (mKeyRepeatState.nextRepeatTime < *nextWakeupTime) {
940 *nextWakeupTime = mKeyRepeatState.nextRepeatTime;
941 }
942 }
943 }
944
945 // Nothing to do if there is no pending event.
946 if (!mPendingEvent) {
947 return;
948 }
949 } else {
950 // Inbound queue has at least one entry.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700951 mPendingEvent = mInboundQueue.front();
952 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800953 traceInboundQueueLengthLocked();
954 }
955
956 // Poke user activity for this event.
957 if (mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700958 pokeUserActivityLocked(*mPendingEvent);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800959 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800960 }
961
962 // Now we have an event to dispatch.
963 // All events are eventually dequeued and processed this way, even if we intend to drop them.
Yi Kong9b14ac62018-07-17 13:48:38 -0700964 ALOG_ASSERT(mPendingEvent != nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800965 bool done = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700966 DropReason dropReason = DropReason::NOT_DROPPED;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800967 if (!(mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700968 dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800969 } else if (!mDispatchEnabled) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700970 dropReason = DropReason::DISABLED;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800971 }
972
973 if (mNextUnblockedEvent == mPendingEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -0700974 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800975 }
976
977 switch (mPendingEvent->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700978 case EventEntry::Type::CONFIGURATION_CHANGED: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700979 const ConfigurationChangedEntry& typedEntry =
980 static_cast<const ConfigurationChangedEntry&>(*mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700981 done = dispatchConfigurationChangedLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700982 dropReason = DropReason::NOT_DROPPED; // configuration changes are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700983 break;
984 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800985
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700986 case EventEntry::Type::DEVICE_RESET: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700987 const DeviceResetEntry& typedEntry =
988 static_cast<const DeviceResetEntry&>(*mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700989 done = dispatchDeviceResetLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700990 dropReason = DropReason::NOT_DROPPED; // device resets are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700991 break;
992 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800993
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100994 case EventEntry::Type::FOCUS: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700995 std::shared_ptr<FocusEntry> typedEntry =
996 std::static_pointer_cast<FocusEntry>(mPendingEvent);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100997 dispatchFocusLocked(currentTime, typedEntry);
998 done = true;
999 dropReason = DropReason::NOT_DROPPED; // focus events are never dropped
1000 break;
1001 }
1002
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001003 case EventEntry::Type::TOUCH_MODE_CHANGED: {
1004 const auto typedEntry = std::static_pointer_cast<TouchModeEntry>(mPendingEvent);
1005 dispatchTouchModeChangeLocked(currentTime, typedEntry);
1006 done = true;
1007 dropReason = DropReason::NOT_DROPPED; // touch mode events are never dropped
1008 break;
1009 }
1010
Prabir Pradhan99987712020-11-10 18:43:05 -08001011 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
1012 const auto typedEntry =
1013 std::static_pointer_cast<PointerCaptureChangedEntry>(mPendingEvent);
1014 dispatchPointerCaptureChangedLocked(currentTime, typedEntry, dropReason);
1015 done = true;
1016 break;
1017 }
1018
arthurhungb89ccb02020-12-30 16:19:01 +08001019 case EventEntry::Type::DRAG: {
1020 std::shared_ptr<DragEntry> typedEntry =
1021 std::static_pointer_cast<DragEntry>(mPendingEvent);
1022 dispatchDragLocked(currentTime, typedEntry);
1023 done = true;
1024 break;
1025 }
1026
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001027 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001028 std::shared_ptr<KeyEntry> keyEntry = std::static_pointer_cast<KeyEntry>(mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001029 if (isAppSwitchDue) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001030 if (isAppSwitchKeyEvent(*keyEntry)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001031 resetPendingAppSwitchLocked(true);
1032 isAppSwitchDue = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001033 } else if (dropReason == DropReason::NOT_DROPPED) {
1034 dropReason = DropReason::APP_SWITCH;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001035 }
1036 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001037 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *keyEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001038 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001039 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001040 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
1041 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001042 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001043 done = dispatchKeyLocked(currentTime, keyEntry, &dropReason, nextWakeupTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001044 break;
1045 }
1046
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001047 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001048 std::shared_ptr<MotionEntry> motionEntry =
1049 std::static_pointer_cast<MotionEntry>(mPendingEvent);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001050 if (dropReason == DropReason::NOT_DROPPED && isAppSwitchDue) {
1051 dropReason = DropReason::APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001052 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001053 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *motionEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001054 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001055 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001056 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
1057 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001058 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001059 done = dispatchMotionLocked(currentTime, motionEntry, &dropReason, nextWakeupTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001060 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001061 }
Chris Yef59a2f42020-10-16 12:55:26 -07001062
1063 case EventEntry::Type::SENSOR: {
1064 std::shared_ptr<SensorEntry> sensorEntry =
1065 std::static_pointer_cast<SensorEntry>(mPendingEvent);
1066 if (dropReason == DropReason::NOT_DROPPED && isAppSwitchDue) {
1067 dropReason = DropReason::APP_SWITCH;
1068 }
1069 // Sensor timestamps use SYSTEM_TIME_BOOTTIME time base, so we can't use
1070 // 'currentTime' here, get SYSTEM_TIME_BOOTTIME instead.
1071 nsecs_t bootTime = systemTime(SYSTEM_TIME_BOOTTIME);
1072 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(bootTime, *sensorEntry)) {
1073 dropReason = DropReason::STALE;
1074 }
1075 dispatchSensorLocked(currentTime, sensorEntry, &dropReason, nextWakeupTime);
1076 done = true;
1077 break;
1078 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001079 }
1080
1081 if (done) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001082 if (dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001083 dropInboundEventLocked(*mPendingEvent, dropReason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001084 }
Michael Wright3a981722015-06-10 15:26:13 +01001085 mLastDropReason = dropReason;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001086
1087 releasePendingEventLocked();
Colin Cross5b799302022-10-18 21:52:41 -07001088 *nextWakeupTime = LLONG_MIN; // force next poll to wake up immediately
Michael Wrightd02c5b62014-02-10 15:10:22 -08001089 }
1090}
1091
Siarhei Vishniakou289e9242022-02-15 14:50:16 -08001092bool InputDispatcher::isStaleEvent(nsecs_t currentTime, const EventEntry& entry) {
1093 return std::chrono::nanoseconds(currentTime - entry.eventTime) >= mStaleEventTimeout;
1094}
1095
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001096/**
1097 * Return true if the events preceding this incoming motion event should be dropped
1098 * Return false otherwise (the default behaviour)
1099 */
1100bool InputDispatcher::shouldPruneInboundQueueLocked(const MotionEntry& motionEntry) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001101 const bool isPointerDownEvent = motionEntry.action == AMOTION_EVENT_ACTION_DOWN &&
Prabir Pradhanaa561d12021-09-24 06:57:33 -07001102 isFromSource(motionEntry.source, AINPUT_SOURCE_CLASS_POINTER);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001103
1104 // Optimize case where the current application is unresponsive and the user
1105 // decides to touch a window in a different application.
1106 // If the application takes too long to catch up then we drop all events preceding
1107 // the touch into the other window.
1108 if (isPointerDownEvent && mAwaitedFocusedApplication != nullptr) {
Siarhei Vishniakou9306c382022-09-30 15:30:31 -07001109 const int32_t displayId = motionEntry.displayId;
1110 const auto [x, y] = resolveTouchedPosition(motionEntry);
Harry Cutts33476232023-01-30 19:57:29 +00001111 const bool isStylus = isPointerFromStylus(motionEntry, /*pointerIndex=*/0);
Siarhei Vishniakou9306c382022-09-30 15:30:31 -07001112
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08001113 auto [touchedWindowHandle, _] = findTouchedWindowAtLocked(displayId, x, y, isStylus);
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001114 if (touchedWindowHandle != nullptr &&
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001115 touchedWindowHandle->getApplicationToken() !=
1116 mAwaitedFocusedApplication->getApplicationToken()) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001117 // User touched a different application than the one we are waiting on.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001118 ALOGI("Pruning input queue because user touched a different application while waiting "
1119 "for %s",
1120 mAwaitedFocusedApplication->getName().c_str());
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001121 return true;
1122 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001123
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08001124 // Alternatively, maybe there's a spy window that could handle this event.
1125 const std::vector<sp<WindowInfoHandle>> touchedSpies =
1126 findTouchedSpyWindowsAtLocked(displayId, x, y, isStylus);
1127 for (const auto& windowHandle : touchedSpies) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07001128 const std::shared_ptr<Connection> connection =
1129 getConnectionLocked(windowHandle->getToken());
Siarhei Vishniakou34ed4d42020-06-18 00:43:02 +00001130 if (connection != nullptr && connection->responsive) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08001131 // This spy window could take more input. Drop all events preceding this
1132 // event, so that the spy window can get a chance to receive the stream.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001133 ALOGW("Pruning the input queue because %s is unresponsive, but we have a "
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08001134 "responsive spy window that may handle the event.",
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001135 mAwaitedFocusedApplication->getName().c_str());
1136 return true;
1137 }
1138 }
1139 }
1140
1141 // Prevent getting stuck: if we have a pending key event, and some motion events that have not
1142 // yet been processed by some connections, the dispatcher will wait for these motion
1143 // events to be processed before dispatching the key event. This is because these motion events
1144 // may cause a new window to be launched, which the user might expect to receive focus.
1145 // To prevent waiting forever for such events, just send the key to the currently focused window
1146 if (isPointerDownEvent && mKeyIsWaitingForEventsTimeout) {
1147 ALOGD("Received a new pointer down event, stop waiting for events to process and "
1148 "just send the pending key event to the focused window.");
1149 mKeyIsWaitingForEventsTimeout = now();
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001150 }
1151 return false;
1152}
1153
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001154bool InputDispatcher::enqueueInboundEventLocked(std::unique_ptr<EventEntry> newEntry) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001155 bool needWake = mInboundQueue.empty();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001156 mInboundQueue.push_back(std::move(newEntry));
1157 EventEntry& entry = *(mInboundQueue.back());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001158 traceInboundQueueLengthLocked();
1159
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001160 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001161 case EventEntry::Type::KEY: {
Prabir Pradhan5735a322022-04-11 17:23:34 +00001162 LOG_ALWAYS_FATAL_IF((entry.policyFlags & POLICY_FLAG_TRUSTED) == 0,
1163 "Unexpected untrusted event.");
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001164 // Optimize app switch latency.
1165 // If the application takes too long to catch up then we drop all events preceding
1166 // the app switch key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001167 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001168 if (isAppSwitchKeyEvent(keyEntry)) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001169 if (keyEntry.action == AKEY_EVENT_ACTION_DOWN) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001170 mAppSwitchSawKeyDown = true;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001171 } else if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001172 if (mAppSwitchSawKeyDown) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001173 if (DEBUG_APP_SWITCH) {
1174 ALOGD("App switch is pending!");
1175 }
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001176 mAppSwitchDueTime = keyEntry.eventTime + APP_SWITCH_TIMEOUT;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001177 mAppSwitchSawKeyDown = false;
1178 needWake = true;
1179 }
1180 }
1181 }
Arthur Hung2ee6d0b2022-03-03 20:19:38 +08001182
1183 // If a new up event comes in, and the pending event with same key code has been asked
1184 // to try again later because of the policy. We have to reset the intercept key wake up
1185 // time for it may have been handled in the policy and could be dropped.
1186 if (keyEntry.action == AKEY_EVENT_ACTION_UP && mPendingEvent &&
1187 mPendingEvent->type == EventEntry::Type::KEY) {
1188 KeyEntry& pendingKey = static_cast<KeyEntry&>(*mPendingEvent);
1189 if (pendingKey.keyCode == keyEntry.keyCode &&
1190 pendingKey.interceptKeyResult ==
Michael Wright5caf55a2022-11-24 22:31:42 +00001191 KeyEntry::InterceptKeyResult::TRY_AGAIN_LATER) {
1192 pendingKey.interceptKeyResult = KeyEntry::InterceptKeyResult::UNKNOWN;
Arthur Hung2ee6d0b2022-03-03 20:19:38 +08001193 pendingKey.interceptKeyWakeupTime = 0;
1194 needWake = true;
1195 }
1196 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001197 break;
1198 }
1199
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001200 case EventEntry::Type::MOTION: {
Prabir Pradhan5735a322022-04-11 17:23:34 +00001201 LOG_ALWAYS_FATAL_IF((entry.policyFlags & POLICY_FLAG_TRUSTED) == 0,
1202 "Unexpected untrusted event.");
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001203 if (shouldPruneInboundQueueLocked(static_cast<MotionEntry&>(entry))) {
1204 mNextUnblockedEvent = mInboundQueue.back();
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001205 needWake = true;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001206 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001207 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001208 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001209 case EventEntry::Type::FOCUS: {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001210 LOG_ALWAYS_FATAL("Focus events should be inserted using enqueueFocusEventLocked");
1211 break;
1212 }
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001213 case EventEntry::Type::TOUCH_MODE_CHANGED:
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001214 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08001215 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07001216 case EventEntry::Type::SENSOR:
arthurhungb89ccb02020-12-30 16:19:01 +08001217 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
1218 case EventEntry::Type::DRAG: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001219 // nothing to do
1220 break;
1221 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001222 }
1223
1224 return needWake;
1225}
1226
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001227void InputDispatcher::addRecentEventLocked(std::shared_ptr<EventEntry> entry) {
Chris Yef59a2f42020-10-16 12:55:26 -07001228 // Do not store sensor event in recent queue to avoid flooding the queue.
1229 if (entry->type != EventEntry::Type::SENSOR) {
1230 mRecentQueue.push_back(entry);
1231 }
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001232 if (mRecentQueue.size() > RECENT_QUEUE_MAX_SIZE) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001233 mRecentQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001234 }
1235}
1236
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08001237std::pair<sp<WindowInfoHandle>, std::vector<InputTarget>>
Prabir Pradhan82e081e2022-12-06 09:50:09 +00001238InputDispatcher::findTouchedWindowAtLocked(int32_t displayId, float x, float y, bool isStylus,
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08001239 bool ignoreDragWindow) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001240 // Traverse windows from front to back to find touched window.
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08001241 std::vector<InputTarget> outsideTargets;
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001242 const auto& windowHandles = getWindowHandlesLocked(displayId);
chaviw98318de2021-05-19 16:45:23 -05001243 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
arthurhung6d4bed92021-03-17 11:59:33 +08001244 if (ignoreDragWindow && haveSameToken(windowHandle, mDragState->dragWindow)) {
arthurhungb89ccb02020-12-30 16:19:01 +08001245 continue;
1246 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001247
Prabir Pradhan3f90d312021-11-19 03:57:24 -08001248 const WindowInfo& info = *windowHandle->getInfo();
Prabir Pradhan33e3baa2022-12-06 20:30:22 +00001249 if (!info.isSpy() &&
1250 windowAcceptsTouchAt(info, displayId, x, y, isStylus, getTransformLocked(displayId))) {
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08001251 return {windowHandle, outsideTargets};
Prabir Pradhan3f90d312021-11-19 03:57:24 -08001252 }
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001253
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08001254 if (info.inputConfig.test(WindowInfo::InputConfig::WATCH_OUTSIDE_TOUCH)) {
1255 addWindowTargetLocked(windowHandle, InputTarget::Flags::DISPATCH_AS_OUTSIDE,
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08001256 /*pointerIds=*/{}, /*firstDownTimeInTarget=*/std::nullopt,
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08001257 outsideTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001258 }
1259 }
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08001260 return {nullptr, {}};
Michael Wrightd02c5b62014-02-10 15:10:22 -08001261}
1262
Prabir Pradhand65552b2021-10-07 11:23:50 -07001263std::vector<sp<WindowInfoHandle>> InputDispatcher::findTouchedSpyWindowsAtLocked(
Prabir Pradhan82e081e2022-12-06 09:50:09 +00001264 int32_t displayId, float x, float y, bool isStylus) const {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001265 // Traverse windows from front to back and gather the touched spy windows.
1266 std::vector<sp<WindowInfoHandle>> spyWindows;
1267 const auto& windowHandles = getWindowHandlesLocked(displayId);
1268 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
1269 const WindowInfo& info = *windowHandle->getInfo();
1270
Prabir Pradhan33e3baa2022-12-06 20:30:22 +00001271 if (!windowAcceptsTouchAt(info, displayId, x, y, isStylus, getTransformLocked(displayId))) {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001272 continue;
1273 }
1274 if (!info.isSpy()) {
1275 // The first touched non-spy window was found, so return the spy windows touched so far.
1276 return spyWindows;
1277 }
1278 spyWindows.push_back(windowHandle);
1279 }
1280 return spyWindows;
1281}
1282
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001283void InputDispatcher::dropInboundEventLocked(const EventEntry& entry, DropReason dropReason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001284 const char* reason;
1285 switch (dropReason) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001286 case DropReason::POLICY:
Prabir Pradhan65613802023-02-22 23:36:58 +00001287 if (debugInboundEventDetails()) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001288 ALOGD("Dropped event because policy consumed it.");
1289 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001290 reason = "inbound event was dropped because the policy consumed it";
1291 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001292 case DropReason::DISABLED:
1293 if (mLastDropReason != DropReason::DISABLED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001294 ALOGI("Dropped event because input dispatch is disabled.");
1295 }
1296 reason = "inbound event was dropped because input dispatch is disabled";
1297 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001298 case DropReason::APP_SWITCH:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001299 ALOGI("Dropped event because of pending overdue app switch.");
1300 reason = "inbound event was dropped because of pending overdue app switch";
1301 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001302 case DropReason::BLOCKED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001303 ALOGI("Dropped event because the current application is not responding and the user "
1304 "has started interacting with a different application.");
1305 reason = "inbound event was dropped because the current application is not responding "
1306 "and the user has started interacting with a different application";
1307 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001308 case DropReason::STALE:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001309 ALOGI("Dropped event because it is stale.");
1310 reason = "inbound event was dropped because it is stale";
1311 break;
Prabir Pradhan99987712020-11-10 18:43:05 -08001312 case DropReason::NO_POINTER_CAPTURE:
1313 ALOGI("Dropped event because there is no window with Pointer Capture.");
1314 reason = "inbound event was dropped because there is no window with Pointer Capture";
1315 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001316 case DropReason::NOT_DROPPED: {
1317 LOG_ALWAYS_FATAL("Should not be dropping a NOT_DROPPED event");
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001318 return;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001319 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001320 }
1321
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001322 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001323 case EventEntry::Type::KEY: {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001324 CancelationOptions options(CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS, reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001325 synthesizeCancelationEventsForAllConnectionsLocked(options);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001326 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001327 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001328 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001329 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
1330 if (motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001331 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS, reason);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001332 synthesizeCancelationEventsForAllConnectionsLocked(options);
1333 } else {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001334 CancelationOptions options(CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS,
1335 reason);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001336 synthesizeCancelationEventsForAllConnectionsLocked(options);
1337 }
1338 break;
1339 }
Chris Yef59a2f42020-10-16 12:55:26 -07001340 case EventEntry::Type::SENSOR: {
1341 break;
1342 }
arthurhungb89ccb02020-12-30 16:19:01 +08001343 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
1344 case EventEntry::Type::DRAG: {
Prabir Pradhan99987712020-11-10 18:43:05 -08001345 break;
1346 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001347 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001348 case EventEntry::Type::TOUCH_MODE_CHANGED:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001349 case EventEntry::Type::CONFIGURATION_CHANGED:
1350 case EventEntry::Type::DEVICE_RESET: {
Dominik Laskowski75788452021-02-09 18:51:25 -08001351 LOG_ALWAYS_FATAL("Should not drop %s events", ftl::enum_string(entry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001352 break;
1353 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001354 }
1355}
1356
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08001357static bool isAppSwitchKeyCode(int32_t keyCode) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001358 return keyCode == AKEYCODE_HOME || keyCode == AKEYCODE_ENDCALL ||
1359 keyCode == AKEYCODE_APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001360}
1361
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001362bool InputDispatcher::isAppSwitchKeyEvent(const KeyEntry& keyEntry) {
1363 return !(keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) && isAppSwitchKeyCode(keyEntry.keyCode) &&
1364 (keyEntry.policyFlags & POLICY_FLAG_TRUSTED) &&
1365 (keyEntry.policyFlags & POLICY_FLAG_PASS_TO_USER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001366}
1367
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07001368bool InputDispatcher::isAppSwitchPendingLocked() const {
Colin Cross5b799302022-10-18 21:52:41 -07001369 return mAppSwitchDueTime != LLONG_MAX;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001370}
1371
1372void InputDispatcher::resetPendingAppSwitchLocked(bool handled) {
Colin Cross5b799302022-10-18 21:52:41 -07001373 mAppSwitchDueTime = LLONG_MAX;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001374
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001375 if (DEBUG_APP_SWITCH) {
1376 if (handled) {
1377 ALOGD("App switch has arrived.");
1378 } else {
1379 ALOGD("App switch was abandoned.");
1380 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001381 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001382}
1383
Michael Wrightd02c5b62014-02-10 15:10:22 -08001384bool InputDispatcher::haveCommandsLocked() const {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001385 return !mCommandQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001386}
1387
Prabir Pradhancef936d2021-07-21 16:17:52 +00001388bool InputDispatcher::runCommandsLockedInterruptable() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001389 if (mCommandQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001390 return false;
1391 }
1392
1393 do {
Prabir Pradhancef936d2021-07-21 16:17:52 +00001394 auto command = std::move(mCommandQueue.front());
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001395 mCommandQueue.pop_front();
Prabir Pradhancef936d2021-07-21 16:17:52 +00001396 // Commands are run with the lock held, but may release and re-acquire the lock from within.
1397 command();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001398 } while (!mCommandQueue.empty());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001399 return true;
1400}
1401
Prabir Pradhancef936d2021-07-21 16:17:52 +00001402void InputDispatcher::postCommandLocked(Command&& command) {
1403 mCommandQueue.push_back(command);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001404}
1405
1406void InputDispatcher::drainInboundQueueLocked() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001407 while (!mInboundQueue.empty()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001408 std::shared_ptr<EventEntry> entry = mInboundQueue.front();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001409 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001410 releaseInboundEventLocked(entry);
1411 }
1412 traceInboundQueueLengthLocked();
1413}
1414
1415void InputDispatcher::releasePendingEventLocked() {
1416 if (mPendingEvent) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001417 releaseInboundEventLocked(mPendingEvent);
Yi Kong9b14ac62018-07-17 13:48:38 -07001418 mPendingEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001419 }
1420}
1421
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001422void InputDispatcher::releaseInboundEventLocked(std::shared_ptr<EventEntry> entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001423 InjectionState* injectionState = entry->injectionState;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001424 if (injectionState && injectionState->injectionResult == InputEventInjectionResult::PENDING) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001425 if (DEBUG_DISPATCH_CYCLE) {
1426 ALOGD("Injected inbound event was dropped.");
1427 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001428 setInjectionResult(*entry, InputEventInjectionResult::FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001429 }
1430 if (entry == mNextUnblockedEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001431 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001432 }
1433 addRecentEventLocked(entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001434}
1435
1436void InputDispatcher::resetKeyRepeatLocked() {
1437 if (mKeyRepeatState.lastKeyEntry) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001438 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001439 }
1440}
1441
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001442std::shared_ptr<KeyEntry> InputDispatcher::synthesizeKeyRepeatLocked(nsecs_t currentTime) {
1443 std::shared_ptr<KeyEntry> entry = mKeyRepeatState.lastKeyEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001444
Michael Wright2e732952014-09-24 13:26:59 -07001445 uint32_t policyFlags = entry->policyFlags &
1446 (POLICY_FLAG_RAW_MASK | POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_TRUSTED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001447
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001448 std::shared_ptr<KeyEntry> newEntry =
1449 std::make_unique<KeyEntry>(mIdGenerator.nextId(), currentTime, entry->deviceId,
1450 entry->source, entry->displayId, policyFlags, entry->action,
1451 entry->flags, entry->keyCode, entry->scanCode,
1452 entry->metaState, entry->repeatCount + 1, entry->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001453
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001454 newEntry->syntheticRepeat = true;
1455 mKeyRepeatState.lastKeyEntry = newEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001456 mKeyRepeatState.nextRepeatTime = currentTime + mConfig.keyRepeatDelay;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001457 return newEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001458}
1459
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001460bool InputDispatcher::dispatchConfigurationChangedLocked(nsecs_t currentTime,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001461 const ConfigurationChangedEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001462 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1463 ALOGD("dispatchConfigurationChanged - eventTime=%" PRId64, entry.eventTime);
1464 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001465
1466 // Reset key repeating in case a keyboard device was added or removed or something.
1467 resetKeyRepeatLocked();
1468
1469 // Enqueue a command to run outside the lock to tell the policy that the configuration changed.
Prabir Pradhancef936d2021-07-21 16:17:52 +00001470 auto command = [this, eventTime = entry.eventTime]() REQUIRES(mLock) {
1471 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00001472 mPolicy.notifyConfigurationChanged(eventTime);
Prabir Pradhancef936d2021-07-21 16:17:52 +00001473 };
1474 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001475 return true;
1476}
1477
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001478bool InputDispatcher::dispatchDeviceResetLocked(nsecs_t currentTime,
1479 const DeviceResetEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001480 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1481 ALOGD("dispatchDeviceReset - eventTime=%" PRId64 ", deviceId=%d", entry.eventTime,
1482 entry.deviceId);
1483 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001484
liushenxiang42232912021-05-21 20:24:09 +08001485 // Reset key repeating in case a keyboard device was disabled or enabled.
1486 if (mKeyRepeatState.lastKeyEntry && mKeyRepeatState.lastKeyEntry->deviceId == entry.deviceId) {
1487 resetKeyRepeatLocked();
1488 }
1489
Michael Wrightfb04fd52022-11-24 22:31:11 +00001490 CancelationOptions options(CancelationOptions::Mode::CANCEL_ALL_EVENTS, "device was reset");
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001491 options.deviceId = entry.deviceId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001492 synthesizeCancelationEventsForAllConnectionsLocked(options);
Siarhei Vishniakou0686f0c2023-05-02 11:56:15 -07001493
1494 // Remove all active pointers from this device
1495 for (auto& [_, touchState] : mTouchStatesByDisplay) {
1496 touchState.removeAllPointersForDevice(entry.deviceId);
1497 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001498 return true;
1499}
1500
Vishnu Nairad321cd2020-08-20 16:40:21 -07001501void InputDispatcher::enqueueFocusEventLocked(const sp<IBinder>& windowToken, bool hasFocus,
Vishnu Nairc519ff72021-01-21 08:23:08 -08001502 const std::string& reason) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001503 if (mPendingEvent != nullptr) {
1504 // Move the pending event to the front of the queue. This will give the chance
1505 // for the pending event to get dispatched to the newly focused window
1506 mInboundQueue.push_front(mPendingEvent);
1507 mPendingEvent = nullptr;
1508 }
1509
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001510 std::unique_ptr<FocusEntry> focusEntry =
1511 std::make_unique<FocusEntry>(mIdGenerator.nextId(), now(), windowToken, hasFocus,
1512 reason);
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001513
1514 // This event should go to the front of the queue, but behind all other focus events
1515 // Find the last focus event, and insert right after it
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001516 std::deque<std::shared_ptr<EventEntry>>::reverse_iterator it =
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001517 std::find_if(mInboundQueue.rbegin(), mInboundQueue.rend(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001518 [](const std::shared_ptr<EventEntry>& event) {
1519 return event->type == EventEntry::Type::FOCUS;
1520 });
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001521
1522 // Maintain the order of focus events. Insert the entry after all other focus events.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001523 mInboundQueue.insert(it.base(), std::move(focusEntry));
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001524}
1525
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001526void InputDispatcher::dispatchFocusLocked(nsecs_t currentTime, std::shared_ptr<FocusEntry> entry) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05001527 std::shared_ptr<InputChannel> channel = getInputChannelLocked(entry->connectionToken);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001528 if (channel == nullptr) {
1529 return; // Window has gone away
1530 }
1531 InputTarget target;
1532 target.inputChannel = channel;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08001533 target.flags = InputTarget::Flags::DISPATCH_AS_IS;
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001534 entry->dispatchInProgress = true;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00001535 std::string message = std::string("Focus ") + (entry->hasFocus ? "entering " : "leaving ") +
1536 channel->getName();
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07001537 std::string reason = std::string("reason=").append(entry->reason);
1538 android_log_event_list(LOGTAG_INPUT_FOCUS) << message << reason << LOG_ID_EVENTS;
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001539 dispatchEventLocked(currentTime, entry, {target});
1540}
1541
Prabir Pradhan99987712020-11-10 18:43:05 -08001542void InputDispatcher::dispatchPointerCaptureChangedLocked(
1543 nsecs_t currentTime, const std::shared_ptr<PointerCaptureChangedEntry>& entry,
1544 DropReason& dropReason) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001545 dropReason = DropReason::NOT_DROPPED;
1546
Prabir Pradhan99987712020-11-10 18:43:05 -08001547 const bool haveWindowWithPointerCapture = mWindowTokenWithPointerCapture != nullptr;
Prabir Pradhan99987712020-11-10 18:43:05 -08001548 sp<IBinder> token;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001549
1550 if (entry->pointerCaptureRequest.enable) {
1551 // Enable Pointer Capture.
1552 if (haveWindowWithPointerCapture &&
1553 (entry->pointerCaptureRequest == mCurrentPointerCaptureRequest)) {
Prabir Pradhan7092e262022-05-03 16:51:09 +00001554 // This can happen if pointer capture is disabled and re-enabled before we notify the
1555 // app of the state change, so there is no need to notify the app.
1556 ALOGI("Skipping dispatch of Pointer Capture being enabled: no state change.");
1557 return;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001558 }
1559 if (!mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08001560 // This can happen if a window requests capture and immediately releases capture.
1561 ALOGW("No window requested Pointer Capture.");
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001562 dropReason = DropReason::NO_POINTER_CAPTURE;
Prabir Pradhan99987712020-11-10 18:43:05 -08001563 return;
1564 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001565 if (entry->pointerCaptureRequest.seq != mCurrentPointerCaptureRequest.seq) {
1566 ALOGI("Skipping dispatch of Pointer Capture being enabled: sequence number mismatch.");
1567 return;
1568 }
1569
Vishnu Nairc519ff72021-01-21 08:23:08 -08001570 token = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Prabir Pradhan99987712020-11-10 18:43:05 -08001571 LOG_ALWAYS_FATAL_IF(!token, "Cannot find focused window for Pointer Capture.");
1572 mWindowTokenWithPointerCapture = token;
1573 } else {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001574 // Disable Pointer Capture.
1575 // We do not check if the sequence number matches for requests to disable Pointer Capture
1576 // for two reasons:
1577 // 1. Pointer Capture can be disabled by a focus change, which means we can get two entries
1578 // to disable capture with the same sequence number: one generated by
1579 // disablePointerCaptureForcedLocked() and another as an acknowledgement of Pointer
1580 // Capture being disabled in InputReader.
1581 // 2. We respect any request to disable Pointer Capture generated by InputReader, since the
1582 // actual Pointer Capture state that affects events being generated by input devices is
1583 // in InputReader.
1584 if (!haveWindowWithPointerCapture) {
1585 // Pointer capture was already forcefully disabled because of focus change.
1586 dropReason = DropReason::NOT_DROPPED;
1587 return;
1588 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001589 token = mWindowTokenWithPointerCapture;
1590 mWindowTokenWithPointerCapture = nullptr;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001591 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan7d030382020-12-21 07:58:35 -08001592 setPointerCaptureLocked(false);
1593 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001594 }
1595
1596 auto channel = getInputChannelLocked(token);
1597 if (channel == nullptr) {
1598 // Window has gone away, clean up Pointer Capture state.
1599 mWindowTokenWithPointerCapture = nullptr;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001600 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan7d030382020-12-21 07:58:35 -08001601 setPointerCaptureLocked(false);
1602 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001603 return;
1604 }
1605 InputTarget target;
1606 target.inputChannel = channel;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08001607 target.flags = InputTarget::Flags::DISPATCH_AS_IS;
Prabir Pradhan99987712020-11-10 18:43:05 -08001608 entry->dispatchInProgress = true;
1609 dispatchEventLocked(currentTime, entry, {target});
1610
1611 dropReason = DropReason::NOT_DROPPED;
1612}
1613
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001614void InputDispatcher::dispatchTouchModeChangeLocked(nsecs_t currentTime,
1615 const std::shared_ptr<TouchModeEntry>& entry) {
1616 const std::vector<sp<WindowInfoHandle>>& windowHandles =
Antonio Kantek15beb512022-06-13 22:35:41 +00001617 getWindowHandlesLocked(entry->displayId);
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001618 if (windowHandles.empty()) {
1619 return;
1620 }
1621 const std::vector<InputTarget> inputTargets =
1622 getInputTargetsFromWindowHandlesLocked(windowHandles);
1623 if (inputTargets.empty()) {
1624 return;
1625 }
1626 entry->dispatchInProgress = true;
1627 dispatchEventLocked(currentTime, entry, inputTargets);
1628}
1629
1630std::vector<InputTarget> InputDispatcher::getInputTargetsFromWindowHandlesLocked(
1631 const std::vector<sp<WindowInfoHandle>>& windowHandles) const {
1632 std::vector<InputTarget> inputTargets;
1633 for (const sp<WindowInfoHandle>& handle : windowHandles) {
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001634 const sp<IBinder>& token = handle->getToken();
1635 if (token == nullptr) {
1636 continue;
1637 }
1638 std::shared_ptr<InputChannel> channel = getInputChannelLocked(token);
1639 if (channel == nullptr) {
1640 continue; // Window has gone away
1641 }
1642 InputTarget target;
1643 target.inputChannel = channel;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08001644 target.flags = InputTarget::Flags::DISPATCH_AS_IS;
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001645 inputTargets.push_back(target);
1646 }
1647 return inputTargets;
1648}
1649
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001650bool InputDispatcher::dispatchKeyLocked(nsecs_t currentTime, std::shared_ptr<KeyEntry> entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001651 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001652 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001653 if (!entry->dispatchInProgress) {
1654 if (entry->repeatCount == 0 && entry->action == AKEY_EVENT_ACTION_DOWN &&
1655 (entry->policyFlags & POLICY_FLAG_TRUSTED) &&
1656 (!(entry->policyFlags & POLICY_FLAG_DISABLE_KEY_REPEAT))) {
1657 if (mKeyRepeatState.lastKeyEntry &&
Chris Ye2ad95392020-09-01 13:44:44 -07001658 mKeyRepeatState.lastKeyEntry->keyCode == entry->keyCode &&
Michael Wrightd02c5b62014-02-10 15:10:22 -08001659 // We have seen two identical key downs in a row which indicates that the device
1660 // driver is automatically generating key repeats itself. We take note of the
1661 // repeat here, but we disable our own next key repeat timer since it is clear that
1662 // we will not need to synthesize key repeats ourselves.
Chris Ye2ad95392020-09-01 13:44:44 -07001663 mKeyRepeatState.lastKeyEntry->deviceId == entry->deviceId) {
1664 // Make sure we don't get key down from a different device. If a different
1665 // device Id has same key pressed down, the new device Id will replace the
1666 // current one to hold the key repeat with repeat count reset.
1667 // In the future when got a KEY_UP on the device id, drop it and do not
1668 // stop the key repeat on current device.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001669 entry->repeatCount = mKeyRepeatState.lastKeyEntry->repeatCount + 1;
1670 resetKeyRepeatLocked();
Colin Cross5b799302022-10-18 21:52:41 -07001671 mKeyRepeatState.nextRepeatTime = LLONG_MAX; // don't generate repeats ourselves
Michael Wrightd02c5b62014-02-10 15:10:22 -08001672 } else {
1673 // Not a repeat. Save key down state in case we do see a repeat later.
1674 resetKeyRepeatLocked();
1675 mKeyRepeatState.nextRepeatTime = entry->eventTime + mConfig.keyRepeatTimeout;
1676 }
1677 mKeyRepeatState.lastKeyEntry = entry;
Chris Ye2ad95392020-09-01 13:44:44 -07001678 } else if (entry->action == AKEY_EVENT_ACTION_UP && mKeyRepeatState.lastKeyEntry &&
1679 mKeyRepeatState.lastKeyEntry->deviceId != entry->deviceId) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001680 // The key on device 'deviceId' is still down, do not stop key repeat
Prabir Pradhan65613802023-02-22 23:36:58 +00001681 if (debugInboundEventDetails()) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001682 ALOGD("deviceId=%d got KEY_UP as stale", entry->deviceId);
1683 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001684 } else if (!entry->syntheticRepeat) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001685 resetKeyRepeatLocked();
1686 }
1687
1688 if (entry->repeatCount == 1) {
1689 entry->flags |= AKEY_EVENT_FLAG_LONG_PRESS;
1690 } else {
1691 entry->flags &= ~AKEY_EVENT_FLAG_LONG_PRESS;
1692 }
1693
1694 entry->dispatchInProgress = true;
1695
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001696 logOutboundKeyDetails("dispatchKey - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001697 }
1698
1699 // Handle case where the policy asked us to try again later last time.
Michael Wright5caf55a2022-11-24 22:31:42 +00001700 if (entry->interceptKeyResult == KeyEntry::InterceptKeyResult::TRY_AGAIN_LATER) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001701 if (currentTime < entry->interceptKeyWakeupTime) {
1702 if (entry->interceptKeyWakeupTime < *nextWakeupTime) {
1703 *nextWakeupTime = entry->interceptKeyWakeupTime;
1704 }
1705 return false; // wait until next wakeup
1706 }
Michael Wright5caf55a2022-11-24 22:31:42 +00001707 entry->interceptKeyResult = KeyEntry::InterceptKeyResult::UNKNOWN;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001708 entry->interceptKeyWakeupTime = 0;
1709 }
1710
1711 // Give the policy a chance to intercept the key.
Michael Wright5caf55a2022-11-24 22:31:42 +00001712 if (entry->interceptKeyResult == KeyEntry::InterceptKeyResult::UNKNOWN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001713 if (entry->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07001714 sp<IBinder> focusedWindowToken =
Vishnu Nairc519ff72021-01-21 08:23:08 -08001715 mFocusResolver.getFocusedWindowToken(getTargetDisplayId(*entry));
Prabir Pradhancef936d2021-07-21 16:17:52 +00001716
1717 auto command = [this, focusedWindowToken, entry]() REQUIRES(mLock) {
1718 doInterceptKeyBeforeDispatchingCommand(focusedWindowToken, *entry);
1719 };
1720 postCommandLocked(std::move(command));
Josep del Riob3981622023-04-18 15:49:45 +00001721 // Poke user activity for keys not passed to user
1722 pokeUserActivityLocked(*entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001723 return false; // wait for the command to run
1724 } else {
Michael Wright5caf55a2022-11-24 22:31:42 +00001725 entry->interceptKeyResult = KeyEntry::InterceptKeyResult::CONTINUE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001726 }
Michael Wright5caf55a2022-11-24 22:31:42 +00001727 } else if (entry->interceptKeyResult == KeyEntry::InterceptKeyResult::SKIP) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001728 if (*dropReason == DropReason::NOT_DROPPED) {
1729 *dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001730 }
1731 }
1732
1733 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001734 if (*dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001735 setInjectionResult(*entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001736 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
1737 : InputEventInjectionResult::FAILED);
Garfield Tan6a5a14e2020-01-28 13:24:04 -08001738 mReporter->reportDroppedKey(entry->id);
Josep del Riob3981622023-04-18 15:49:45 +00001739 // Poke user activity for undispatched keys
1740 pokeUserActivityLocked(*entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001741 return true;
1742 }
1743
1744 // Identify targets.
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001745 InputEventInjectionResult injectionResult;
1746 sp<WindowInfoHandle> focusedWindow =
1747 findFocusedWindowTargetLocked(currentTime, *entry, nextWakeupTime,
1748 /*byref*/ injectionResult);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001749 if (injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001750 return false;
1751 }
1752
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001753 setInjectionResult(*entry, injectionResult);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001754 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001755 return true;
1756 }
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001757 LOG_ALWAYS_FATAL_IF(focusedWindow == nullptr);
1758
1759 std::vector<InputTarget> inputTargets;
1760 addWindowTargetLocked(focusedWindow,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08001761 InputTarget::Flags::FOREGROUND | InputTarget::Flags::DISPATCH_AS_IS,
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08001762 /*pointerIds=*/{}, getDownTime(*entry), inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001763
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001764 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001765 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001766
1767 // Dispatch the key.
1768 dispatchEventLocked(currentTime, entry, inputTargets);
1769 return true;
1770}
1771
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001772void InputDispatcher::logOutboundKeyDetails(const char* prefix, const KeyEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001773 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1774 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32 ", "
1775 "policyFlags=0x%x, action=0x%x, flags=0x%x, keyCode=0x%x, scanCode=0x%x, "
1776 "metaState=0x%x, repeatCount=%d, downTime=%" PRId64,
1777 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId,
1778 entry.policyFlags, entry.action, entry.flags, entry.keyCode, entry.scanCode,
1779 entry.metaState, entry.repeatCount, entry.downTime);
1780 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001781}
1782
Prabir Pradhancef936d2021-07-21 16:17:52 +00001783void InputDispatcher::dispatchSensorLocked(nsecs_t currentTime,
1784 const std::shared_ptr<SensorEntry>& entry,
Chris Yef59a2f42020-10-16 12:55:26 -07001785 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001786 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1787 ALOGD("notifySensorEvent eventTime=%" PRId64 ", hwTimestamp=%" PRId64 ", deviceId=%d, "
1788 "source=0x%x, sensorType=%s",
1789 entry->eventTime, entry->hwTimestamp, entry->deviceId, entry->source,
Dominik Laskowski75788452021-02-09 18:51:25 -08001790 ftl::enum_string(entry->sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001791 }
Prabir Pradhancef936d2021-07-21 16:17:52 +00001792 auto command = [this, entry]() REQUIRES(mLock) {
1793 scoped_unlock unlock(mLock);
1794
1795 if (entry->accuracyChanged) {
Prabir Pradhana41d2442023-04-20 21:30:40 +00001796 mPolicy.notifySensorAccuracy(entry->deviceId, entry->sensorType, entry->accuracy);
Prabir Pradhancef936d2021-07-21 16:17:52 +00001797 }
Prabir Pradhana41d2442023-04-20 21:30:40 +00001798 mPolicy.notifySensorEvent(entry->deviceId, entry->sensorType, entry->accuracy,
1799 entry->hwTimestamp, entry->values);
Prabir Pradhancef936d2021-07-21 16:17:52 +00001800 };
1801 postCommandLocked(std::move(command));
Chris Yef59a2f42020-10-16 12:55:26 -07001802}
1803
1804bool InputDispatcher::flushSensor(int deviceId, InputDeviceSensorType sensorType) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001805 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1806 ALOGD("flushSensor deviceId=%d, sensorType=%s", deviceId,
Dominik Laskowski75788452021-02-09 18:51:25 -08001807 ftl::enum_string(sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001808 }
Chris Yef59a2f42020-10-16 12:55:26 -07001809 { // acquire lock
1810 std::scoped_lock _l(mLock);
1811
1812 for (auto it = mInboundQueue.begin(); it != mInboundQueue.end(); it++) {
1813 std::shared_ptr<EventEntry> entry = *it;
1814 if (entry->type == EventEntry::Type::SENSOR) {
1815 it = mInboundQueue.erase(it);
1816 releaseInboundEventLocked(entry);
1817 }
1818 }
1819 }
1820 return true;
1821}
1822
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001823bool InputDispatcher::dispatchMotionLocked(nsecs_t currentTime, std::shared_ptr<MotionEntry> entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001824 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001825 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001826 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001827 if (!entry->dispatchInProgress) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001828 entry->dispatchInProgress = true;
1829
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001830 logOutboundMotionDetails("dispatchMotion - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001831 }
1832
1833 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001834 if (*dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001835 setInjectionResult(*entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001836 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
1837 : InputEventInjectionResult::FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001838 return true;
1839 }
1840
Prabir Pradhanaa561d12021-09-24 06:57:33 -07001841 const bool isPointerEvent = isFromSource(entry->source, AINPUT_SOURCE_CLASS_POINTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001842
1843 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001844 std::vector<InputTarget> inputTargets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001845
1846 bool conflictingPointerActions = false;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001847 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001848 if (isPointerEvent) {
1849 // Pointer event. (eg. touchscreen)
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00001850
1851 if (mDragState &&
1852 (entry->action & AMOTION_EVENT_ACTION_MASK) == AMOTION_EVENT_ACTION_POINTER_DOWN) {
1853 // If drag and drop ongoing and pointer down occur: pilfer drag window pointers
1854 pilferPointersLocked(mDragState->dragWindow->getToken());
1855 }
1856
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08001857 inputTargets =
Siarhei Vishniakou4fe57392022-10-25 13:44:30 -07001858 findTouchedWindowTargetsLocked(currentTime, *entry, &conflictingPointerActions,
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001859 /*byref*/ injectionResult);
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08001860 LOG_ALWAYS_FATAL_IF(injectionResult != InputEventInjectionResult::SUCCEEDED &&
1861 !inputTargets.empty());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001862 } else {
1863 // Non touch event. (eg. trackball)
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001864 sp<WindowInfoHandle> focusedWindow =
1865 findFocusedWindowTargetLocked(currentTime, *entry, nextWakeupTime, injectionResult);
1866 if (injectionResult == InputEventInjectionResult::SUCCEEDED) {
1867 LOG_ALWAYS_FATAL_IF(focusedWindow == nullptr);
1868 addWindowTargetLocked(focusedWindow,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08001869 InputTarget::Flags::FOREGROUND |
1870 InputTarget::Flags::DISPATCH_AS_IS,
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08001871 /*pointerIds=*/{}, getDownTime(*entry), inputTargets);
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001872 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001873 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001874 if (injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001875 return false;
1876 }
1877
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001878 setInjectionResult(*entry, injectionResult);
Prabir Pradhan5735a322022-04-11 17:23:34 +00001879 if (injectionResult == InputEventInjectionResult::TARGET_MISMATCH) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001880 return true;
1881 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001882 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001883 CancelationOptions::Mode mode(
1884 isPointerEvent ? CancelationOptions::Mode::CANCEL_POINTER_EVENTS
1885 : CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS);
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001886 CancelationOptions options(mode, "input event injection failed");
1887 synthesizeCancelationEventsForMonitorsLocked(options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001888 return true;
1889 }
1890
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001891 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001892 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001893
1894 // Dispatch the motion.
1895 if (conflictingPointerActions) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001896 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001897 "conflicting pointer actions");
Michael Wrightd02c5b62014-02-10 15:10:22 -08001898 synthesizeCancelationEventsForAllConnectionsLocked(options);
1899 }
1900 dispatchEventLocked(currentTime, entry, inputTargets);
1901 return true;
1902}
1903
chaviw98318de2021-05-19 16:45:23 -05001904void InputDispatcher::enqueueDragEventLocked(const sp<WindowInfoHandle>& windowHandle,
Arthur Hung54745652022-04-20 07:17:41 +00001905 bool isExiting, const int32_t rawX,
1906 const int32_t rawY) {
1907 const vec2 xy = windowHandle->getInfo()->transform.transform(vec2(rawX, rawY));
arthurhungb89ccb02020-12-30 16:19:01 +08001908 std::unique_ptr<DragEntry> dragEntry =
Arthur Hung54745652022-04-20 07:17:41 +00001909 std::make_unique<DragEntry>(mIdGenerator.nextId(), now(), windowHandle->getToken(),
1910 isExiting, xy.x, xy.y);
arthurhungb89ccb02020-12-30 16:19:01 +08001911
1912 enqueueInboundEventLocked(std::move(dragEntry));
1913}
1914
1915void InputDispatcher::dispatchDragLocked(nsecs_t currentTime, std::shared_ptr<DragEntry> entry) {
1916 std::shared_ptr<InputChannel> channel = getInputChannelLocked(entry->connectionToken);
1917 if (channel == nullptr) {
1918 return; // Window has gone away
1919 }
1920 InputTarget target;
1921 target.inputChannel = channel;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08001922 target.flags = InputTarget::Flags::DISPATCH_AS_IS;
arthurhungb89ccb02020-12-30 16:19:01 +08001923 entry->dispatchInProgress = true;
1924 dispatchEventLocked(currentTime, entry, {target});
1925}
1926
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001927void InputDispatcher::logOutboundMotionDetails(const char* prefix, const MotionEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001928 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -08001929 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=%s, displayId=%" PRId32
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001930 ", policyFlags=0x%x, "
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001931 "action=%s, actionButton=0x%x, flags=0x%x, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001932 "metaState=0x%x, buttonState=0x%x,"
1933 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%" PRId64,
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -08001934 prefix, entry.eventTime, entry.deviceId,
1935 inputEventSourceToString(entry.source).c_str(), entry.displayId, entry.policyFlags,
1936 MotionEvent::actionToString(entry.action).c_str(), entry.actionButton, entry.flags,
1937 entry.metaState, entry.buttonState, entry.edgeFlags, entry.xPrecision,
1938 entry.yPrecision, entry.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001939
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001940 for (uint32_t i = 0; i < entry.pointerCount; i++) {
Siarhei Vishniakou09a8fe42022-07-21 17:27:03 -07001941 ALOGD(" Pointer %d: id=%d, toolType=%s, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001942 "x=%f, y=%f, pressure=%f, size=%f, "
1943 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
1944 "orientation=%f",
Siarhei Vishniakou09a8fe42022-07-21 17:27:03 -07001945 i, entry.pointerProperties[i].id,
1946 ftl::enum_string(entry.pointerProperties[i].toolType).c_str(),
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001947 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
1948 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
1949 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
1950 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
1951 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
1952 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
1953 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
1954 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
1955 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
1956 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001957 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001958}
1959
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001960void InputDispatcher::dispatchEventLocked(nsecs_t currentTime,
1961 std::shared_ptr<EventEntry> eventEntry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001962 const std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001963 ATRACE_CALL();
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001964 if (DEBUG_DISPATCH_CYCLE) {
1965 ALOGD("dispatchEventToCurrentInputTargets");
1966 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001967
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00001968 processInteractionsLocked(*eventEntry, inputTargets);
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00001969
Michael Wrightd02c5b62014-02-10 15:10:22 -08001970 ALOG_ASSERT(eventEntry->dispatchInProgress); // should already have been set to true
1971
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001972 pokeUserActivityLocked(*eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001973
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001974 for (const InputTarget& inputTarget : inputTargets) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07001975 std::shared_ptr<Connection> connection =
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07001976 getConnectionLocked(inputTarget.inputChannel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07001977 if (connection != nullptr) {
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08001978 prepareDispatchCycleLocked(currentTime, connection, eventEntry, inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001979 } else {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001980 if (DEBUG_FOCUS) {
1981 ALOGD("Dropping event delivery to target with channel '%s' because it "
1982 "is no longer registered with the input dispatcher.",
1983 inputTarget.inputChannel->getName().c_str());
1984 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001985 }
1986 }
1987}
1988
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07001989void InputDispatcher::cancelEventsForAnrLocked(const std::shared_ptr<Connection>& connection) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001990 // We will not be breaking any connections here, even if the policy wants us to abort dispatch.
1991 // If the policy decides to close the app, we will get a channel removal event via
1992 // unregisterInputChannel, and will clean up the connection that way. We are already not
1993 // sending new pointers to the connection when it blocked, but focused events will continue to
1994 // pile up.
1995 ALOGW("Canceling events for %s because it is unresponsive",
1996 connection->inputChannel->getName().c_str());
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08001997 if (connection->status == Connection::Status::NORMAL) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001998 CancelationOptions options(CancelationOptions::Mode::CANCEL_ALL_EVENTS,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001999 "application not responding");
2000 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002001 }
2002}
2003
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002004void InputDispatcher::resetNoFocusedWindowTimeoutLocked() {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002005 if (DEBUG_FOCUS) {
2006 ALOGD("Resetting ANR timeouts.");
2007 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002008
2009 // Reset input target wait timeout.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002010 mNoFocusedWindowTimeoutTime = std::nullopt;
Chris Yea209fde2020-07-22 13:54:51 -07002011 mAwaitedFocusedApplication.reset();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002012}
2013
Tiger Huang721e26f2018-07-24 22:26:19 +08002014/**
2015 * Get the display id that the given event should go to. If this event specifies a valid display id,
2016 * then it should be dispatched to that display. Otherwise, the event goes to the focused display.
2017 * Focused display is the display that the user most recently interacted with.
2018 */
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002019int32_t InputDispatcher::getTargetDisplayId(const EventEntry& entry) {
Tiger Huang721e26f2018-07-24 22:26:19 +08002020 int32_t displayId;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002021 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002022 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002023 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
2024 displayId = keyEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002025 break;
2026 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002027 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002028 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
2029 displayId = motionEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002030 break;
2031 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00002032 case EventEntry::Type::TOUCH_MODE_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08002033 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002034 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002035 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07002036 case EventEntry::Type::DEVICE_RESET:
arthurhungb89ccb02020-12-30 16:19:01 +08002037 case EventEntry::Type::SENSOR:
2038 case EventEntry::Type::DRAG: {
Dominik Laskowski75788452021-02-09 18:51:25 -08002039 ALOGE("%s events do not have a target display", ftl::enum_string(entry.type).c_str());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002040 return ADISPLAY_ID_NONE;
2041 }
Tiger Huang721e26f2018-07-24 22:26:19 +08002042 }
2043 return displayId == ADISPLAY_ID_NONE ? mFocusedDisplayId : displayId;
2044}
2045
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002046bool InputDispatcher::shouldWaitToSendKeyLocked(nsecs_t currentTime,
2047 const char* focusedWindowName) {
2048 if (mAnrTracker.empty()) {
2049 // already processed all events that we waited for
2050 mKeyIsWaitingForEventsTimeout = std::nullopt;
2051 return false;
2052 }
2053
2054 if (!mKeyIsWaitingForEventsTimeout.has_value()) {
2055 // Start the timer
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00002056 // Wait to send key because there are unprocessed events that may cause focus to change
Siarhei Vishniakou70622952020-07-30 11:17:23 -05002057 mKeyIsWaitingForEventsTimeout = currentTime +
2058 std::chrono::duration_cast<std::chrono::nanoseconds>(KEY_WAITING_FOR_EVENTS_TIMEOUT)
2059 .count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002060 return true;
2061 }
2062
2063 // We still have pending events, and already started the timer
2064 if (currentTime < *mKeyIsWaitingForEventsTimeout) {
2065 return true; // Still waiting
2066 }
2067
2068 // Waited too long, and some connection still hasn't processed all motions
2069 // Just send the key to the focused window
2070 ALOGW("Dispatching key to %s even though there are other unprocessed events",
2071 focusedWindowName);
2072 mKeyIsWaitingForEventsTimeout = std::nullopt;
2073 return false;
2074}
2075
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002076sp<WindowInfoHandle> InputDispatcher::findFocusedWindowTargetLocked(
2077 nsecs_t currentTime, const EventEntry& entry, nsecs_t* nextWakeupTime,
2078 InputEventInjectionResult& outInjectionResult) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002079 std::string reason;
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002080 outInjectionResult = InputEventInjectionResult::FAILED; // Default result
Michael Wrightd02c5b62014-02-10 15:10:22 -08002081
Tiger Huang721e26f2018-07-24 22:26:19 +08002082 int32_t displayId = getTargetDisplayId(entry);
chaviw98318de2021-05-19 16:45:23 -05002083 sp<WindowInfoHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Chris Yea209fde2020-07-22 13:54:51 -07002084 std::shared_ptr<InputApplicationHandle> focusedApplicationHandle =
Tiger Huang721e26f2018-07-24 22:26:19 +08002085 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
2086
Michael Wrightd02c5b62014-02-10 15:10:22 -08002087 // If there is no currently focused window and no focused application
2088 // then drop the event.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002089 if (focusedWindowHandle == nullptr && focusedApplicationHandle == nullptr) {
2090 ALOGI("Dropping %s event because there is no focused window or focused application in "
2091 "display %" PRId32 ".",
Dominik Laskowski75788452021-02-09 18:51:25 -08002092 ftl::enum_string(entry.type).c_str(), displayId);
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002093 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002094 }
2095
Vishnu Nair062a8672021-09-03 16:07:44 -07002096 // Drop key events if requested by input feature
2097 if (focusedWindowHandle != nullptr && shouldDropInput(entry, focusedWindowHandle)) {
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002098 return nullptr;
Vishnu Nair062a8672021-09-03 16:07:44 -07002099 }
2100
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002101 // Compatibility behavior: raise ANR if there is a focused application, but no focused window.
2102 // Only start counting when we have a focused event to dispatch. The ANR is canceled if we
2103 // start interacting with another application via touch (app switch). This code can be removed
2104 // if the "no focused window ANR" is moved to the policy. Input doesn't know whether
2105 // an app is expected to have a focused window.
2106 if (focusedWindowHandle == nullptr && focusedApplicationHandle != nullptr) {
2107 if (!mNoFocusedWindowTimeoutTime.has_value()) {
2108 // We just discovered that there's no focused window. Start the ANR timer
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05002109 std::chrono::nanoseconds timeout = focusedApplicationHandle->getDispatchingTimeout(
2110 DEFAULT_INPUT_DISPATCHING_TIMEOUT);
2111 mNoFocusedWindowTimeoutTime = currentTime + timeout.count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002112 mAwaitedFocusedApplication = focusedApplicationHandle;
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05002113 mAwaitedApplicationDisplayId = displayId;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002114 ALOGW("Waiting because no window has focus but %s may eventually add a "
2115 "window when it finishes starting up. Will wait for %" PRId64 "ms",
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05002116 mAwaitedFocusedApplication->getName().c_str(), millis(timeout));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002117 *nextWakeupTime = *mNoFocusedWindowTimeoutTime;
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002118 outInjectionResult = InputEventInjectionResult::PENDING;
2119 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002120 } else if (currentTime > *mNoFocusedWindowTimeoutTime) {
2121 // Already raised ANR. Drop the event
2122 ALOGE("Dropping %s event because there is no focused window",
Dominik Laskowski75788452021-02-09 18:51:25 -08002123 ftl::enum_string(entry.type).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002124 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002125 } else {
2126 // Still waiting for the focused window
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002127 outInjectionResult = InputEventInjectionResult::PENDING;
2128 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002129 }
2130 }
2131
2132 // we have a valid, non-null focused window
2133 resetNoFocusedWindowTimeoutLocked();
2134
Prabir Pradhan5735a322022-04-11 17:23:34 +00002135 // Verify targeted injection.
2136 if (const auto err = verifyTargetedInjection(focusedWindowHandle, entry); err) {
2137 ALOGW("Dropping injected event: %s", (*err).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002138 outInjectionResult = InputEventInjectionResult::TARGET_MISMATCH;
2139 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002140 }
2141
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002142 if (focusedWindowHandle->getInfo()->inputConfig.test(
2143 WindowInfo::InputConfig::PAUSE_DISPATCHING)) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002144 ALOGI("Waiting because %s is paused", focusedWindowHandle->getName().c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002145 outInjectionResult = InputEventInjectionResult::PENDING;
2146 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002147 }
2148
2149 // If the event is a key event, then we must wait for all previous events to
2150 // complete before delivering it because previous events may have the
2151 // side-effect of transferring focus to a different window and we want to
2152 // ensure that the following keys are sent to the new window.
2153 //
2154 // Suppose the user touches a button in a window then immediately presses "A".
2155 // If the button causes a pop-up window to appear then we want to ensure that
2156 // the "A" key is delivered to the new pop-up window. This is because users
2157 // often anticipate pending UI changes when typing on a keyboard.
2158 // To obtain this behavior, we must serialize key events with respect to all
2159 // prior input events.
2160 if (entry.type == EventEntry::Type::KEY) {
2161 if (shouldWaitToSendKeyLocked(currentTime, focusedWindowHandle->getName().c_str())) {
2162 *nextWakeupTime = *mKeyIsWaitingForEventsTimeout;
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002163 outInjectionResult = InputEventInjectionResult::PENDING;
2164 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002165 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002166 }
2167
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002168 outInjectionResult = InputEventInjectionResult::SUCCEEDED;
2169 return focusedWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002170}
2171
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002172/**
2173 * Given a list of monitors, remove the ones we cannot find a connection for, and the ones
2174 * that are currently unresponsive.
2175 */
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002176std::vector<Monitor> InputDispatcher::selectResponsiveMonitorsLocked(
2177 const std::vector<Monitor>& monitors) const {
2178 std::vector<Monitor> responsiveMonitors;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002179 std::copy_if(monitors.begin(), monitors.end(), std::back_inserter(responsiveMonitors),
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002180 [this](const Monitor& monitor) REQUIRES(mLock) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07002181 std::shared_ptr<Connection> connection =
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002182 getConnectionLocked(monitor.inputChannel->getConnectionToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002183 if (connection == nullptr) {
2184 ALOGE("Could not find connection for monitor %s",
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002185 monitor.inputChannel->getName().c_str());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002186 return false;
2187 }
2188 if (!connection->responsive) {
2189 ALOGW("Unresponsive monitor %s will not get the new gesture",
2190 connection->inputChannel->getName().c_str());
2191 return false;
2192 }
2193 return true;
2194 });
2195 return responsiveMonitors;
2196}
2197
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07002198/**
2199 * In general, touch should be always split between windows. Some exceptions:
2200 * 1. Don't split touch is if we have an active pointer down, and a new pointer is going down that's
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002201 * from the same device, *and* the window that's receiving the current pointer does not support
2202 * split touch.
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07002203 * 2. Don't split mouse events
2204 */
2205bool InputDispatcher::shouldSplitTouch(const TouchState& touchState,
2206 const MotionEntry& entry) const {
2207 if (isFromSource(entry.source, AINPUT_SOURCE_MOUSE)) {
2208 // We should never split mouse events
2209 return false;
2210 }
2211 for (const TouchedWindow& touchedWindow : touchState.windows) {
2212 if (touchedWindow.windowHandle->getInfo()->isSpy()) {
2213 // Spy windows should not affect whether or not touch is split.
2214 continue;
2215 }
2216 if (touchedWindow.windowHandle->getInfo()->supportsSplitTouch()) {
2217 continue;
2218 }
Arthur Hungc539dbb2022-12-08 07:45:36 +00002219 if (touchedWindow.windowHandle->getInfo()->inputConfig.test(
2220 gui::WindowInfo::InputConfig::IS_WALLPAPER)) {
2221 // Wallpaper window should not affect whether or not touch is split
2222 continue;
2223 }
2224
Siarhei Vishniakou45504fe2023-05-05 16:05:10 -07002225 if (touchedWindow.hasTouchingPointers(entry.deviceId)) {
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07002226 return false;
2227 }
2228 }
2229 return true;
2230}
2231
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002232std::vector<InputTarget> InputDispatcher::findTouchedWindowTargetsLocked(
Siarhei Vishniakou4fe57392022-10-25 13:44:30 -07002233 nsecs_t currentTime, const MotionEntry& entry, bool* outConflictingPointerActions,
2234 InputEventInjectionResult& outInjectionResult) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002235 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002236
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002237 std::vector<InputTarget> targets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002238 // For security reasons, we defer updating the touch state until we are sure that
2239 // event injection will be allowed.
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002240 const int32_t displayId = entry.displayId;
2241 const int32_t action = entry.action;
Siarhei Vishniakoubf880522023-05-01 11:03:22 -07002242 const int32_t maskedAction = MotionEvent::getActionMasked(action);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002243
2244 // Update the touch state as needed based on the properties of the touch event.
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002245 outInjectionResult = InputEventInjectionResult::PENDING;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002246
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002247 // Copy current touch state into tempTouchState.
2248 // This state will be used to update mTouchStatesByDisplay at the end of this function.
2249 // If no state for the specified display exists, then our initial state will be empty.
Yi Kong9b14ac62018-07-17 13:48:38 -07002250 const TouchState* oldState = nullptr;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002251 TouchState tempTouchState;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002252 if (const auto it = mTouchStatesByDisplay.find(displayId); it != mTouchStatesByDisplay.end()) {
2253 oldState = &(it->second);
Prabir Pradhane680f9b2022-02-04 04:24:00 -08002254 tempTouchState = *oldState;
Jeff Brownf086ddb2014-02-11 14:28:48 -08002255 }
2256
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07002257 bool isSplit = shouldSplitTouch(tempTouchState, entry);
Siarhei Vishniakou45504fe2023-05-05 16:05:10 -07002258 bool switchedDevice = false;
2259 if (oldState != nullptr) {
2260 std::set<int32_t> oldActiveDevices = oldState->getActiveDeviceIds();
2261 const bool anotherDeviceIsActive =
2262 oldActiveDevices.count(entry.deviceId) == 0 && !oldActiveDevices.empty();
2263 switchedDevice |= anotherDeviceIsActive;
Siarhei Vishniakou45504fe2023-05-05 16:05:10 -07002264 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002265
2266 const bool isHoverAction = (maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE ||
2267 maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2268 maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT);
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002269 // A DOWN could be generated from POINTER_DOWN if the initial pointers did not land into any
2270 // touchable windows.
2271 const bool wasDown = oldState != nullptr && oldState->isDown();
2272 const bool isDown = (maskedAction == AMOTION_EVENT_ACTION_DOWN) ||
2273 (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN && !wasDown);
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07002274 const bool newGesture = isDown || maskedAction == AMOTION_EVENT_ACTION_SCROLL ||
2275 maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2276 maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE;
Prabir Pradhanaa561d12021-09-24 06:57:33 -07002277 const bool isFromMouse = isFromSource(entry.source, AINPUT_SOURCE_MOUSE);
Siarhei Vishniakou5cee1e32022-11-29 12:35:39 -08002278
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002279 // If pointers are already down, let's finish the current gesture and ignore the new events
2280 // from another device. However, if the new event is a down event, let's cancel the current
2281 // touch and let the new one take over.
2282 if (switchedDevice && wasDown && !isDown) {
Siarhei Vishniakou45504fe2023-05-05 16:05:10 -07002283 LOG(INFO) << "Dropping event because a pointer for another device "
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002284 << " is already down in display " << displayId << ": " << entry.getDescription();
2285 // TODO(b/211379801): test multiple simultaneous input streams.
2286 outInjectionResult = InputEventInjectionResult::FAILED;
2287 return {}; // wrong device
2288 }
2289
Michael Wrightd02c5b62014-02-10 15:10:22 -08002290 if (newGesture) {
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002291 // If a new gesture is starting, clear the touch state completely.
2292 tempTouchState.reset();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002293 isSplit = false;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04002294 } else if (switchedDevice && maskedAction == AMOTION_EVENT_ACTION_MOVE) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07002295 ALOGI("Dropping move event because a pointer for a different device is already active "
2296 "in display %" PRId32,
2297 displayId);
Siarhei Vishniakou16e4fa02023-02-16 17:48:56 -08002298 // TODO(b/211379801): test multiple simultaneous input streams.
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002299 outInjectionResult = InputEventInjectionResult::FAILED;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002300 return {}; // wrong device
Michael Wrightd02c5b62014-02-10 15:10:22 -08002301 }
2302
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002303 if (isHoverAction) {
2304 // For hover actions, we will treat 'tempTouchState' as a new state, so let's erase
2305 // all of the existing hovering pointers and recompute.
2306 tempTouchState.clearHoveringPointers();
2307 }
2308
Michael Wrightd02c5b62014-02-10 15:10:22 -08002309 if (newGesture || (isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN)) {
2310 /* Case 1: New splittable pointer going down, or need target for hover or scroll. */
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07002311 const auto [x, y] = resolveTouchedPosition(entry);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002312 const int32_t pointerIndex = getMotionEventActionPointerIndex(action);
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002313 // Outside targets should be added upon first dispatched DOWN event. That means, this should
2314 // be a pointer that would generate ACTION_DOWN, *and* touch should not already be down.
Prabir Pradhand65552b2021-10-07 11:23:50 -07002315 const bool isStylus = isPointerFromStylus(entry, pointerIndex);
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002316 auto [newTouchedWindowHandle, outsideTargets] =
2317 findTouchedWindowAtLocked(displayId, x, y, isStylus);
Michael Wright3dd60e22019-03-27 22:06:44 +00002318
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002319 if (isDown) {
2320 targets += outsideTargets;
2321 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002322 // Handle the case where we did not find a window.
Yi Kong9b14ac62018-07-17 13:48:38 -07002323 if (newTouchedWindowHandle == nullptr) {
Prabir Pradhan82e081e2022-12-06 09:50:09 +00002324 ALOGD("No new touched window at (%.1f, %.1f) in display %" PRId32, x, y, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002325 // Try to assign the pointer to the first foreground window we find, if there is one.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002326 newTouchedWindowHandle = tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002327 }
2328
Prabir Pradhan5735a322022-04-11 17:23:34 +00002329 // Verify targeted injection.
2330 if (const auto err = verifyTargetedInjection(newTouchedWindowHandle, entry); err) {
2331 ALOGW("Dropping injected touch event: %s", (*err).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002332 outInjectionResult = os::InputEventInjectionResult::TARGET_MISMATCH;
Prabir Pradhan5735a322022-04-11 17:23:34 +00002333 newTouchedWindowHandle = nullptr;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002334 return {};
Prabir Pradhan5735a322022-04-11 17:23:34 +00002335 }
2336
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002337 // Figure out whether splitting will be allowed for this window.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002338 if (newTouchedWindowHandle != nullptr) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002339 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
2340 // New window supports splitting, but we should never split mouse events.
2341 isSplit = !isFromMouse;
2342 } else if (isSplit) {
2343 // New window does not support splitting but we have already split events.
2344 // Ignore the new window.
Siarhei Vishniakou25537f82023-07-18 14:35:47 -07002345 LOG(INFO) << "Skipping " << newTouchedWindowHandle->getName()
2346 << " because it doesn't support split touch";
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002347 newTouchedWindowHandle = nullptr;
2348 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002349 } else {
2350 // No window is touched, so set split to true. This will allow the next pointer down to
Prabir Pradhan713bb3e2021-12-20 02:07:40 -08002351 // be delivered to a new window which supports split touch. Pointers from a mouse device
2352 // should never be split.
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07002353 isSplit = !isFromMouse;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002354 }
2355
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002356 std::vector<sp<WindowInfoHandle>> newTouchedWindows =
Prabir Pradhand65552b2021-10-07 11:23:50 -07002357 findTouchedSpyWindowsAtLocked(displayId, x, y, isStylus);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002358 if (newTouchedWindowHandle != nullptr) {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002359 // Process the foreground window first so that it is the first to receive the event.
2360 newTouchedWindows.insert(newTouchedWindows.begin(), newTouchedWindowHandle);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002361 }
2362
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002363 if (newTouchedWindows.empty()) {
Prabir Pradhan82e081e2022-12-06 09:50:09 +00002364 ALOGI("Dropping event because there is no touchable window at (%.1f, %.1f) on display "
2365 "%d.",
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002366 x, y, displayId);
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002367 outInjectionResult = InputEventInjectionResult::FAILED;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002368 return {};
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002369 }
2370
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002371 for (const sp<WindowInfoHandle>& windowHandle : newTouchedWindows) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07002372 if (!canWindowReceiveMotionLocked(windowHandle, entry)) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002373 continue;
2374 }
2375
Siarhei Vishniakoub681c202023-05-01 11:22:33 -07002376 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2377 maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE) {
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002378 const int32_t pointerId = entry.pointerProperties[0].id;
Siarhei Vishniakoub681c202023-05-01 11:22:33 -07002379 // The "windowHandle" is the target of this hovering pointer.
2380 tempTouchState.addHoveringPointerToWindow(windowHandle, entry.deviceId, pointerId);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002381 }
2382
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002383 // Set target flags.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002384 ftl::Flags<InputTarget::Flags> targetFlags = InputTarget::Flags::DISPATCH_AS_IS;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002385
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002386 if (canReceiveForegroundTouches(*windowHandle->getInfo())) {
2387 // There should only be one touched window that can be "foreground" for the pointer.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002388 targetFlags |= InputTarget::Flags::FOREGROUND;
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002389 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002390
2391 if (isSplit) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002392 targetFlags |= InputTarget::Flags::SPLIT;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002393 }
2394 if (isWindowObscuredAtPointLocked(windowHandle, x, y)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002395 targetFlags |= InputTarget::Flags::WINDOW_IS_OBSCURED;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002396 } else if (isWindowObscuredLocked(windowHandle)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002397 targetFlags |= InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002398 }
Michael Wright3dd60e22019-03-27 22:06:44 +00002399
2400 // Update the temporary touch state.
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08002401 std::bitset<MAX_POINTER_ID + 1> pointerIds;
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002402 if (!isHoverAction) {
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08002403 pointerIds.set(entry.pointerProperties[pointerIndex].id);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002404 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002405
Siarhei Vishniakoue0431e42023-01-28 17:01:39 -08002406 const bool isDownOrPointerDown = maskedAction == AMOTION_EVENT_ACTION_DOWN ||
2407 maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN;
2408
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002409 // TODO(b/211379801): Currently, even if pointerIds are empty (hover case), we would
2410 // still add a window to the touch state. We should avoid doing that, but some of the
2411 // later checks ("at least one foreground window") rely on this in order to dispatch
2412 // the event properly, so that needs to be updated, possibly by looking at InputTargets.
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002413 tempTouchState.addOrUpdateWindow(windowHandle, targetFlags, entry.deviceId, pointerIds,
Siarhei Vishniakoue0431e42023-01-28 17:01:39 -08002414 isDownOrPointerDown
2415 ? std::make_optional(entry.eventTime)
2416 : std::nullopt);
Arthur Hungc539dbb2022-12-08 07:45:36 +00002417
2418 // If this is the pointer going down and the touched window has a wallpaper
2419 // then also add the touched wallpaper windows so they are locked in for the duration
2420 // of the touch gesture.
2421 // We do not collect wallpapers during HOVER_MOVE or SCROLL because the wallpaper
2422 // engine only supports touch events. We would need to add a mechanism similar
2423 // to View.onGenericMotionEvent to enable wallpapers to handle these events.
Siarhei Vishniakoue0431e42023-01-28 17:01:39 -08002424 if (isDownOrPointerDown) {
Arthur Hungc539dbb2022-12-08 07:45:36 +00002425 if (targetFlags.test(InputTarget::Flags::FOREGROUND) &&
2426 windowHandle->getInfo()->inputConfig.test(
2427 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER)) {
2428 sp<WindowInfoHandle> wallpaper = findWallpaperWindowBelow(windowHandle);
2429 if (wallpaper != nullptr) {
2430 ftl::Flags<InputTarget::Flags> wallpaperFlags =
2431 InputTarget::Flags::WINDOW_IS_OBSCURED |
2432 InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED |
2433 InputTarget::Flags::DISPATCH_AS_IS;
2434 if (isSplit) {
2435 wallpaperFlags |= InputTarget::Flags::SPLIT;
2436 }
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002437 tempTouchState.addOrUpdateWindow(wallpaper, wallpaperFlags, entry.deviceId,
2438 pointerIds, entry.eventTime);
Arthur Hungc539dbb2022-12-08 07:45:36 +00002439 }
2440 }
2441 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002442 }
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00002443
Siarhei Vishniakou060f82b2023-01-27 06:39:14 -08002444 // If a window is already pilfering some pointers, give it this new pointer as well and
2445 // make it pilfering. This will prevent other non-spy windows from getting this pointer,
2446 // which is a specific behaviour that we want.
2447 const int32_t pointerId = entry.pointerProperties[pointerIndex].id;
2448 for (TouchedWindow& touchedWindow : tempTouchState.windows) {
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002449 if (touchedWindow.hasTouchingPointer(entry.deviceId, pointerId) &&
2450 touchedWindow.hasPilferingPointers(entry.deviceId)) {
Siarhei Vishniakou060f82b2023-01-27 06:39:14 -08002451 // This window is already pilfering some pointers, and this new pointer is also
2452 // going to it. Therefore, take over this pointer and don't give it to anyone
2453 // else.
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002454 touchedWindow.addPilferingPointer(entry.deviceId, pointerId);
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00002455 }
2456 }
Siarhei Vishniakou060f82b2023-01-27 06:39:14 -08002457
2458 // Restrict all pilfered pointers to the pilfering windows.
2459 tempTouchState.cancelPointersForNonPilferingWindows();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002460 } else {
2461 /* Case 2: Pointer move, up, cancel or non-splittable pointer down. */
2462
2463 // If the pointer is not currently down, then ignore the event.
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07002464 if (!tempTouchState.isDown() && maskedAction != AMOTION_EVENT_ACTION_HOVER_EXIT) {
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002465 LOG(INFO) << "Dropping event because the pointer is not down or we previously "
2466 "dropped the pointer down event in display "
2467 << displayId << ": " << entry.getDescription();
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002468 outInjectionResult = InputEventInjectionResult::FAILED;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002469 return {};
Michael Wrightd02c5b62014-02-10 15:10:22 -08002470 }
2471
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07002472 // If the pointer is not currently hovering, then ignore the event.
2473 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT) {
2474 const int32_t pointerId = entry.pointerProperties[0].id;
2475 if (oldState == nullptr ||
2476 oldState->getWindowsWithHoveringPointer(entry.deviceId, pointerId).empty()) {
2477 LOG(INFO) << "Dropping event because the hovering pointer is not in any windows in "
2478 "display "
2479 << displayId << ": " << entry.getDescription();
2480 outInjectionResult = InputEventInjectionResult::FAILED;
2481 return {};
2482 }
2483 tempTouchState.removeHoveringPointer(entry.deviceId, pointerId);
2484 }
2485
arthurhung6d4bed92021-03-17 11:59:33 +08002486 addDragEventLocked(entry);
arthurhungb89ccb02020-12-30 16:19:01 +08002487
Michael Wrightd02c5b62014-02-10 15:10:22 -08002488 // Check whether touches should slip outside of the current foreground window.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002489 if (maskedAction == AMOTION_EVENT_ACTION_MOVE && entry.pointerCount == 1 &&
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002490 tempTouchState.isSlippery()) {
Siarhei Vishniakou9306c382022-09-30 15:30:31 -07002491 const auto [x, y] = resolveTouchedPosition(entry);
Harry Cutts33476232023-01-30 19:57:29 +00002492 const bool isStylus = isPointerFromStylus(entry, /*pointerIndex=*/0);
chaviw98318de2021-05-19 16:45:23 -05002493 sp<WindowInfoHandle> oldTouchedWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002494 tempTouchState.getFirstForegroundWindowHandle();
Siarhei Vishniakou0f6558d2023-04-21 12:05:13 -07002495 LOG_ALWAYS_FATAL_IF(oldTouchedWindowHandle == nullptr);
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002496 auto [newTouchedWindowHandle, _] = findTouchedWindowAtLocked(displayId, x, y, isStylus);
Vishnu Nair062a8672021-09-03 16:07:44 -07002497
Prabir Pradhan5735a322022-04-11 17:23:34 +00002498 // Verify targeted injection.
2499 if (const auto err = verifyTargetedInjection(newTouchedWindowHandle, entry); err) {
2500 ALOGW("Dropping injected event: %s", (*err).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002501 outInjectionResult = os::InputEventInjectionResult::TARGET_MISMATCH;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002502 return {};
Prabir Pradhan5735a322022-04-11 17:23:34 +00002503 }
2504
Vishnu Nair062a8672021-09-03 16:07:44 -07002505 // Drop touch events if requested by input feature
2506 if (newTouchedWindowHandle != nullptr &&
2507 shouldDropInput(entry, newTouchedWindowHandle)) {
2508 newTouchedWindowHandle = nullptr;
2509 }
2510
Siarhei Vishniakouafa08cc2023-05-08 22:35:50 -07002511 if (newTouchedWindowHandle != nullptr &&
2512 !haveSameToken(oldTouchedWindowHandle, newTouchedWindowHandle)) {
Siarhei Vishniakou0f6558d2023-04-21 12:05:13 -07002513 ALOGD("Touch is slipping out of window %s into window %s in display %" PRId32,
2514 oldTouchedWindowHandle->getName().c_str(),
2515 newTouchedWindowHandle->getName().c_str(), displayId);
2516
Michael Wrightd02c5b62014-02-10 15:10:22 -08002517 // Make a slippery exit from the old window.
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08002518 std::bitset<MAX_POINTER_ID + 1> pointerIds;
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002519 const int32_t pointerId = entry.pointerProperties[0].id;
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08002520 pointerIds.set(pointerId);
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002521
2522 const TouchedWindow& touchedWindow =
2523 tempTouchState.getTouchedWindow(oldTouchedWindowHandle);
2524 addWindowTargetLocked(oldTouchedWindowHandle,
2525 InputTarget::Flags::DISPATCH_AS_SLIPPERY_EXIT, pointerIds,
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002526 touchedWindow.getDownTimeInTarget(entry.deviceId), targets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002527
2528 // Make a slippery entrance into the new window.
2529 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
Prabir Pradhan713bb3e2021-12-20 02:07:40 -08002530 isSplit = !isFromMouse;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002531 }
2532
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002533 ftl::Flags<InputTarget::Flags> targetFlags =
2534 InputTarget::Flags::DISPATCH_AS_SLIPPERY_ENTER;
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002535 if (canReceiveForegroundTouches(*newTouchedWindowHandle->getInfo())) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002536 targetFlags |= InputTarget::Flags::FOREGROUND;
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002537 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002538 if (isSplit) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002539 targetFlags |= InputTarget::Flags::SPLIT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002540 }
2541 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002542 targetFlags |= InputTarget::Flags::WINDOW_IS_OBSCURED;
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002543 } else if (isWindowObscuredLocked(newTouchedWindowHandle)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002544 targetFlags |= InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002545 }
2546
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002547 tempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags,
2548 entry.deviceId, pointerIds, entry.eventTime);
Arthur Hungc539dbb2022-12-08 07:45:36 +00002549
2550 // Check if the wallpaper window should deliver the corresponding event.
2551 slipWallpaperTouch(targetFlags, oldTouchedWindowHandle, newTouchedWindowHandle,
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002552 tempTouchState, entry.deviceId, pointerId, targets);
2553 tempTouchState.removeTouchingPointerFromWindow(entry.deviceId, pointerId,
2554 oldTouchedWindowHandle);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002555 }
2556 }
Arthur Hung96483742022-11-15 03:30:48 +00002557
2558 // Update the pointerIds for non-splittable when it received pointer down.
2559 if (!isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN) {
2560 // If no split, we suppose all touched windows should receive pointer down.
2561 const int32_t pointerIndex = getMotionEventActionPointerIndex(action);
2562 for (size_t i = 0; i < tempTouchState.windows.size(); i++) {
2563 TouchedWindow& touchedWindow = tempTouchState.windows[i];
2564 // Ignore drag window for it should just track one pointer.
2565 if (mDragState && mDragState->dragWindow == touchedWindow.windowHandle) {
2566 continue;
2567 }
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002568 touchedWindow.addTouchingPointer(entry.deviceId,
2569 entry.pointerProperties[pointerIndex].id);
Arthur Hung96483742022-11-15 03:30:48 +00002570 }
2571 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002572 }
2573
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002574 // Update dispatching for hover enter and exit.
Sam Dubeyf886dec2023-01-27 13:28:19 +00002575 {
2576 std::vector<TouchedWindow> hoveringWindows =
2577 getHoveringWindowsLocked(oldState, tempTouchState, entry);
2578 for (const TouchedWindow& touchedWindow : hoveringWindows) {
Siarhei Vishniakoud5876ba2023-05-15 17:58:34 -07002579 std::optional<InputTarget> target =
2580 createInputTargetLocked(touchedWindow.windowHandle, touchedWindow.targetFlags,
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002581 touchedWindow.getDownTimeInTarget(entry.deviceId));
Siarhei Vishniakoud5876ba2023-05-15 17:58:34 -07002582 if (!target) {
2583 continue;
2584 }
2585 // Hardcode to single hovering pointer for now.
2586 std::bitset<MAX_POINTER_ID + 1> pointerIds;
2587 pointerIds.set(entry.pointerProperties[0].id);
2588 target->addPointers(pointerIds, touchedWindow.windowHandle->getInfo()->transform);
2589 targets.push_back(*target);
Sam Dubeyf886dec2023-01-27 13:28:19 +00002590 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002591 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002592
Prabir Pradhan5735a322022-04-11 17:23:34 +00002593 // Ensure that all touched windows are valid for injection.
2594 if (entry.injectionState != nullptr) {
2595 std::string errs;
2596 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Prabir Pradhan5735a322022-04-11 17:23:34 +00002597 const auto err = verifyTargetedInjection(touchedWindow.windowHandle, entry);
2598 if (err) errs += "\n - " + *err;
2599 }
2600 if (!errs.empty()) {
2601 ALOGW("Dropping targeted injection: At least one touched window is not owned by uid "
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00002602 "%s:%s",
2603 entry.injectionState->targetUid->toString().c_str(), errs.c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002604 outInjectionResult = InputEventInjectionResult::TARGET_MISMATCH;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002605 return {};
Prabir Pradhan5735a322022-04-11 17:23:34 +00002606 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002607 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002608
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002609 // Check whether windows listening for outside touches are owned by the same UID. If the owner
2610 // has a different UID, then we will not reveal coordinate information to this window.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002611 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
chaviw98318de2021-05-19 16:45:23 -05002612 sp<WindowInfoHandle> foregroundWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002613 tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002614 if (foregroundWindowHandle) {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00002615 const auto foregroundWindowUid = foregroundWindowHandle->getInfo()->ownerUid;
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002616 for (InputTarget& target : targets) {
2617 if (target.flags.test(InputTarget::Flags::DISPATCH_AS_OUTSIDE)) {
2618 sp<WindowInfoHandle> targetWindow =
2619 getWindowHandleLocked(target.inputChannel->getConnectionToken());
2620 if (targetWindow->getInfo()->ownerUid != foregroundWindowUid) {
2621 target.flags |= InputTarget::Flags::ZERO_COORDS;
Michael Wright3dd60e22019-03-27 22:06:44 +00002622 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002623 }
2624 }
2625 }
2626 }
2627
Harry Cuttsb166c002023-05-09 13:06:05 +00002628 // If this is a touchpad navigation gesture, it needs to only be sent to trusted targets, as we
2629 // only want the system UI to handle these gestures.
2630 const bool isTouchpadNavGesture = isFromSource(entry.source, AINPUT_SOURCE_MOUSE) &&
2631 entry.classification == MotionClassification::MULTI_FINGER_SWIPE;
2632 if (isTouchpadNavGesture) {
2633 filterUntrustedTargets(/* byref */ tempTouchState, /* byref */ targets);
2634 }
2635
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07002636 // Output targets from the touch state.
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002637 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002638 if (!touchedWindow.hasTouchingPointers(entry.deviceId) &&
2639 !touchedWindow.hasHoveringPointers(entry.deviceId)) {
Siarhei Vishniakoue0431e42023-01-28 17:01:39 -08002640 // Windows with hovering pointers are getting persisted inside TouchState.
2641 // Do not send this event to those windows.
2642 continue;
2643 }
Harry Cuttsb166c002023-05-09 13:06:05 +00002644
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002645 addWindowTargetLocked(touchedWindow.windowHandle, touchedWindow.targetFlags,
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002646 touchedWindow.getTouchingPointers(entry.deviceId),
2647 touchedWindow.getDownTimeInTarget(entry.deviceId), targets);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002648 }
Sam Dubey39d37cf2022-12-07 18:05:35 +00002649
Siarhei Vishniakou580fb3a2023-05-05 15:02:20 -07002650 // During targeted injection, only allow owned targets to receive events
2651 std::erase_if(targets, [&](const InputTarget& target) {
2652 LOG_ALWAYS_FATAL_IF(target.windowHandle == nullptr);
2653 const auto err = verifyTargetedInjection(target.windowHandle, entry);
2654 if (err) {
2655 LOG(WARNING) << "Dropping injected event from " << target.windowHandle->getName()
2656 << ": " << (*err);
2657 return true;
2658 }
2659 return false;
2660 });
2661
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07002662 if (targets.empty()) {
2663 LOG(INFO) << "Dropping event because no targets were found: " << entry.getDescription();
2664 outInjectionResult = InputEventInjectionResult::FAILED;
2665 return {};
2666 }
2667
2668 // If we only have windows getting ACTION_OUTSIDE, then drop the event, because there is no
2669 // window that is actually receiving the entire gesture.
2670 if (std::all_of(targets.begin(), targets.end(), [](const InputTarget& target) {
2671 return target.flags.test(InputTarget::Flags::DISPATCH_AS_OUTSIDE);
2672 })) {
2673 LOG(INFO) << "Dropping event because all windows would just receive ACTION_OUTSIDE: "
2674 << entry.getDescription();
2675 outInjectionResult = InputEventInjectionResult::FAILED;
2676 return {};
2677 }
2678
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002679 outInjectionResult = InputEventInjectionResult::SUCCEEDED;
Sam Dubeyf886dec2023-01-27 13:28:19 +00002680 // Drop the outside or hover touch windows since we will not care about them
2681 // in the next iteration.
2682 tempTouchState.filterNonAsIsTouchWindows();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002683
Michael Wrightd02c5b62014-02-10 15:10:22 -08002684 // Update final pieces of touch state if the injector had permission.
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002685 if (switchedDevice) {
2686 if (DEBUG_FOCUS) {
2687 ALOGD("Conflicting pointer actions: Switched to a different device.");
2688 }
2689 *outConflictingPointerActions = true;
2690 }
2691
2692 if (isHoverAction) {
2693 // Started hovering, therefore no longer down.
Siarhei Vishniakou3ad385b2022-11-04 10:09:53 -07002694 if (oldState && oldState->isDown()) {
Siarhei Vishniakou6e1e9872022-11-08 17:51:35 -08002695 ALOGD_IF(DEBUG_FOCUS,
2696 "Conflicting pointer actions: Hover received while pointer was down.");
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002697 *outConflictingPointerActions = true;
2698 }
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002699 } else if (maskedAction == AMOTION_EVENT_ACTION_UP) {
2700 // Pointer went up.
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002701 tempTouchState.removeTouchingPointer(entry.deviceId, entry.pointerProperties[0].id);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002702 } else if (maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002703 // All pointers up or canceled.
2704 tempTouchState.reset();
2705 } else if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
2706 // First pointer went down.
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002707 if (oldState && (oldState->isDown() || oldState->hasHoveringPointers())) {
2708 ALOGD("Conflicting pointer actions: Down received while already down or hovering.");
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002709 *outConflictingPointerActions = true;
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002710 }
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002711 } else if (maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
2712 // One pointer went up.
2713 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
2714 uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002715
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002716 for (size_t i = 0; i < tempTouchState.windows.size();) {
2717 TouchedWindow& touchedWindow = tempTouchState.windows[i];
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002718 touchedWindow.removeTouchingPointer(entry.deviceId, pointerId);
2719 if (!touchedWindow.hasTouchingPointers(entry.deviceId)) {
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002720 tempTouchState.windows.erase(tempTouchState.windows.begin() + i);
2721 continue;
2722 }
2723 i += 1;
2724 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002725 }
2726
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002727 // Save changes unless the action was scroll in which case the temporary touch
2728 // state was only valid for this one action.
2729 if (maskedAction != AMOTION_EVENT_ACTION_SCROLL) {
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07002730 if (displayId >= 0) {
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002731 tempTouchState.clearWindowsWithoutPointers();
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002732 mTouchStatesByDisplay[displayId] = tempTouchState;
2733 } else {
2734 mTouchStatesByDisplay.erase(displayId);
2735 }
2736 }
2737
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -08002738 if (tempTouchState.windows.empty()) {
2739 mTouchStatesByDisplay.erase(displayId);
2740 }
2741
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002742 return targets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002743}
2744
arthurhung6d4bed92021-03-17 11:59:33 +08002745void InputDispatcher::finishDragAndDrop(int32_t displayId, float x, float y) {
Prabir Pradhand65552b2021-10-07 11:23:50 -07002746 // Prevent stylus interceptor windows from affecting drag and drop behavior for now, until we
2747 // have an explicit reason to support it.
2748 constexpr bool isStylus = false;
2749
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002750 auto [dropWindow, _] =
Harry Cutts33476232023-01-30 19:57:29 +00002751 findTouchedWindowAtLocked(displayId, x, y, isStylus, /*ignoreDragWindow=*/true);
arthurhung6d4bed92021-03-17 11:59:33 +08002752 if (dropWindow) {
2753 vec2 local = dropWindow->getInfo()->transform.transform(x, y);
Prabir Pradhancef936d2021-07-21 16:17:52 +00002754 sendDropWindowCommandLocked(dropWindow->getToken(), local.x, local.y);
Arthur Hung6d0571e2021-04-09 20:18:16 +08002755 } else {
Arthur Hung54745652022-04-20 07:17:41 +00002756 ALOGW("No window found when drop.");
Prabir Pradhancef936d2021-07-21 16:17:52 +00002757 sendDropWindowCommandLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08002758 }
2759 mDragState.reset();
2760}
2761
2762void InputDispatcher::addDragEventLocked(const MotionEntry& entry) {
Arthur Hung3915c1f2022-05-31 07:17:17 +00002763 if (!mDragState || mDragState->dragWindow->getInfo()->displayId != entry.displayId) {
arthurhungb89ccb02020-12-30 16:19:01 +08002764 return;
2765 }
2766
arthurhung6d4bed92021-03-17 11:59:33 +08002767 if (!mDragState->isStartDrag) {
2768 mDragState->isStartDrag = true;
2769 mDragState->isStylusButtonDownAtStart =
2770 (entry.buttonState & AMOTION_EVENT_BUTTON_STYLUS_PRIMARY) != 0;
2771 }
2772
Arthur Hung54745652022-04-20 07:17:41 +00002773 // Find the pointer index by id.
2774 int32_t pointerIndex = 0;
2775 for (; static_cast<uint32_t>(pointerIndex) < entry.pointerCount; pointerIndex++) {
2776 const PointerProperties& pointerProperties = entry.pointerProperties[pointerIndex];
2777 if (pointerProperties.id == mDragState->pointerId) {
2778 break;
arthurhung6d4bed92021-03-17 11:59:33 +08002779 }
Arthur Hung54745652022-04-20 07:17:41 +00002780 }
arthurhung6d4bed92021-03-17 11:59:33 +08002781
Arthur Hung54745652022-04-20 07:17:41 +00002782 if (uint32_t(pointerIndex) == entry.pointerCount) {
2783 LOG_ALWAYS_FATAL("Should find a valid pointer index by id %d", mDragState->pointerId);
Arthur Hung54745652022-04-20 07:17:41 +00002784 }
2785
2786 const int32_t maskedAction = entry.action & AMOTION_EVENT_ACTION_MASK;
2787 const int32_t x = entry.pointerCoords[pointerIndex].getX();
2788 const int32_t y = entry.pointerCoords[pointerIndex].getY();
2789
2790 switch (maskedAction) {
2791 case AMOTION_EVENT_ACTION_MOVE: {
2792 // Handle the special case : stylus button no longer pressed.
2793 bool isStylusButtonDown =
2794 (entry.buttonState & AMOTION_EVENT_BUTTON_STYLUS_PRIMARY) != 0;
2795 if (mDragState->isStylusButtonDownAtStart && !isStylusButtonDown) {
2796 finishDragAndDrop(entry.displayId, x, y);
2797 return;
2798 }
2799
2800 // Prevent stylus interceptor windows from affecting drag and drop behavior for now,
2801 // until we have an explicit reason to support it.
2802 constexpr bool isStylus = false;
2803
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002804 auto [hoverWindowHandle, _] = findTouchedWindowAtLocked(entry.displayId, x, y, isStylus,
Harry Cutts33476232023-01-30 19:57:29 +00002805 /*ignoreDragWindow=*/true);
Arthur Hung54745652022-04-20 07:17:41 +00002806 // enqueue drag exit if needed.
2807 if (hoverWindowHandle != mDragState->dragHoverWindowHandle &&
2808 !haveSameToken(hoverWindowHandle, mDragState->dragHoverWindowHandle)) {
2809 if (mDragState->dragHoverWindowHandle != nullptr) {
Harry Cutts33476232023-01-30 19:57:29 +00002810 enqueueDragEventLocked(mDragState->dragHoverWindowHandle, /*isExiting=*/true, x,
Arthur Hung54745652022-04-20 07:17:41 +00002811 y);
2812 }
2813 mDragState->dragHoverWindowHandle = hoverWindowHandle;
2814 }
2815 // enqueue drag location if needed.
2816 if (hoverWindowHandle != nullptr) {
Harry Cutts33476232023-01-30 19:57:29 +00002817 enqueueDragEventLocked(hoverWindowHandle, /*isExiting=*/false, x, y);
Arthur Hung54745652022-04-20 07:17:41 +00002818 }
2819 break;
2820 }
2821
2822 case AMOTION_EVENT_ACTION_POINTER_UP:
2823 if (getMotionEventActionPointerIndex(entry.action) != pointerIndex) {
2824 break;
2825 }
2826 // The drag pointer is up.
2827 [[fallthrough]];
2828 case AMOTION_EVENT_ACTION_UP:
2829 finishDragAndDrop(entry.displayId, x, y);
2830 break;
2831 case AMOTION_EVENT_ACTION_CANCEL: {
2832 ALOGD("Receiving cancel when drag and drop.");
2833 sendDropWindowCommandLocked(nullptr, 0, 0);
2834 mDragState.reset();
2835 break;
2836 }
arthurhungb89ccb02020-12-30 16:19:01 +08002837 }
2838}
2839
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002840std::optional<InputTarget> InputDispatcher::createInputTargetLocked(
2841 const sp<android::gui::WindowInfoHandle>& windowHandle,
2842 ftl::Flags<InputTarget::Flags> targetFlags,
2843 std::optional<nsecs_t> firstDownTimeInTarget) const {
2844 std::shared_ptr<InputChannel> inputChannel = getInputChannelLocked(windowHandle->getToken());
2845 if (inputChannel == nullptr) {
2846 ALOGW("Not creating InputTarget for %s, no input channel", windowHandle->getName().c_str());
2847 return {};
2848 }
2849 InputTarget inputTarget;
2850 inputTarget.inputChannel = inputChannel;
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00002851 inputTarget.windowHandle = windowHandle;
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002852 inputTarget.flags = targetFlags;
2853 inputTarget.globalScaleFactor = windowHandle->getInfo()->globalScaleFactor;
2854 inputTarget.firstDownTimeInTarget = firstDownTimeInTarget;
2855 const auto& displayInfoIt = mDisplayInfos.find(windowHandle->getInfo()->displayId);
2856 if (displayInfoIt != mDisplayInfos.end()) {
2857 inputTarget.displayTransform = displayInfoIt->second.transform;
2858 } else {
Siarhei Vishniakou580fb3a2023-05-05 15:02:20 -07002859 // DisplayInfo not found for this window on display windowHandle->getInfo()->displayId.
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002860 // TODO(b/198444055): Make this an error message after 'setInputWindows' API is removed.
2861 }
2862 return inputTarget;
2863}
2864
chaviw98318de2021-05-19 16:45:23 -05002865void InputDispatcher::addWindowTargetLocked(const sp<WindowInfoHandle>& windowHandle,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002866 ftl::Flags<InputTarget::Flags> targetFlags,
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08002867 std::bitset<MAX_POINTER_ID + 1> pointerIds,
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002868 std::optional<nsecs_t> firstDownTimeInTarget,
Siarhei Vishniakouf75cddb2022-10-25 10:42:16 -07002869 std::vector<InputTarget>& inputTargets) const {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002870 std::vector<InputTarget>::iterator it =
2871 std::find_if(inputTargets.begin(), inputTargets.end(),
2872 [&windowHandle](const InputTarget& inputTarget) {
2873 return inputTarget.inputChannel->getConnectionToken() ==
2874 windowHandle->getToken();
2875 });
Chavi Weingarten97b8eec2020-01-09 18:09:08 +00002876
chaviw98318de2021-05-19 16:45:23 -05002877 const WindowInfo* windowInfo = windowHandle->getInfo();
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002878
2879 if (it == inputTargets.end()) {
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002880 std::optional<InputTarget> target =
2881 createInputTargetLocked(windowHandle, targetFlags, firstDownTimeInTarget);
2882 if (!target) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002883 return;
2884 }
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002885 inputTargets.push_back(*target);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002886 it = inputTargets.end() - 1;
2887 }
2888
2889 ALOG_ASSERT(it->flags == targetFlags);
2890 ALOG_ASSERT(it->globalScaleFactor == windowInfo->globalScaleFactor);
2891
chaviw1ff3d1e2020-07-01 15:53:47 -07002892 it->addPointers(pointerIds, windowInfo->transform);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002893}
2894
Michael Wright3dd60e22019-03-27 22:06:44 +00002895void InputDispatcher::addGlobalMonitoringTargetsLocked(std::vector<InputTarget>& inputTargets,
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002896 int32_t displayId) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002897 auto monitorsIt = mGlobalMonitorsByDisplay.find(displayId);
2898 if (monitorsIt == mGlobalMonitorsByDisplay.end()) return;
Michael Wright3dd60e22019-03-27 22:06:44 +00002899
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002900 for (const Monitor& monitor : selectResponsiveMonitorsLocked(monitorsIt->second)) {
2901 InputTarget target;
2902 target.inputChannel = monitor.inputChannel;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002903 target.flags = InputTarget::Flags::DISPATCH_AS_IS;
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002904 // target.firstDownTimeInTarget is not set for global monitors. It is only required in split
2905 // touch and global monitoring works as intended even without setting firstDownTimeInTarget
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002906 if (const auto& it = mDisplayInfos.find(displayId); it != mDisplayInfos.end()) {
2907 target.displayTransform = it->second.transform;
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002908 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002909 target.setDefaultPointerTransform(target.displayTransform);
2910 inputTargets.push_back(target);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002911 }
2912}
2913
Robert Carrc9bf1d32020-04-13 17:21:08 -07002914/**
2915 * Indicate whether one window handle should be considered as obscuring
2916 * another window handle. We only check a few preconditions. Actually
2917 * checking the bounds is left to the caller.
2918 */
chaviw98318de2021-05-19 16:45:23 -05002919static bool canBeObscuredBy(const sp<WindowInfoHandle>& windowHandle,
2920 const sp<WindowInfoHandle>& otherHandle) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002921 // Compare by token so cloned layers aren't counted
2922 if (haveSameToken(windowHandle, otherHandle)) {
2923 return false;
2924 }
2925 auto info = windowHandle->getInfo();
2926 auto otherInfo = otherHandle->getInfo();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002927 if (otherInfo->inputConfig.test(WindowInfo::InputConfig::NOT_VISIBLE)) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002928 return false;
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002929 } else if (otherInfo->alpha == 0 &&
2930 otherInfo->inputConfig.test(WindowInfo::InputConfig::NOT_TOUCHABLE)) {
Bernardo Rufino653d2e02020-10-20 17:32:40 +00002931 // Those act as if they were invisible, so we don't need to flag them.
2932 // We do want to potentially flag touchable windows even if they have 0
2933 // opacity, since they can consume touches and alter the effects of the
2934 // user interaction (eg. apps that rely on
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002935 // Flags::WINDOW_IS_PARTIALLY_OBSCURED should still be told about those
Bernardo Rufino653d2e02020-10-20 17:32:40 +00002936 // windows), hence we also check for FLAG_NOT_TOUCHABLE.
2937 return false;
Bernardo Rufino8007daf2020-09-22 09:40:01 +00002938 } else if (info->ownerUid == otherInfo->ownerUid) {
2939 // If ownerUid is the same we don't generate occlusion events as there
2940 // is no security boundary within an uid.
Robert Carrc9bf1d32020-04-13 17:21:08 -07002941 return false;
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002942 } else if (otherInfo->inputConfig.test(gui::WindowInfo::InputConfig::TRUSTED_OVERLAY)) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002943 return false;
2944 } else if (otherInfo->displayId != info->displayId) {
2945 return false;
2946 }
2947 return true;
2948}
2949
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002950/**
2951 * Returns touch occlusion information in the form of TouchOcclusionInfo. To check if the touch is
2952 * untrusted, one should check:
2953 *
2954 * 1. If result.hasBlockingOcclusion is true.
2955 * If it's, it means the touch should be blocked due to a window with occlusion mode of
2956 * BLOCK_UNTRUSTED.
2957 *
2958 * 2. If result.obscuringOpacity > mMaximumObscuringOpacityForTouch.
2959 * If it is (and 1 is false), then the touch should be blocked because a stack of windows
2960 * (possibly only one) with occlusion mode of USE_OPACITY from one UID resulted in a composed
2961 * obscuring opacity above the threshold. Note that if there was no window of occlusion mode
2962 * USE_OPACITY, result.obscuringOpacity would've been 0 and since
2963 * mMaximumObscuringOpacityForTouch >= 0, the condition above would never be true.
2964 *
2965 * If neither of those is true, then it means the touch can be allowed.
2966 */
2967InputDispatcher::TouchOcclusionInfo InputDispatcher::computeTouchOcclusionInfoLocked(
chaviw98318de2021-05-19 16:45:23 -05002968 const sp<WindowInfoHandle>& windowHandle, int32_t x, int32_t y) const {
2969 const WindowInfo* windowInfo = windowHandle->getInfo();
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002970 int32_t displayId = windowInfo->displayId;
chaviw98318de2021-05-19 16:45:23 -05002971 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002972 TouchOcclusionInfo info;
2973 info.hasBlockingOcclusion = false;
2974 info.obscuringOpacity = 0;
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00002975 info.obscuringUid = gui::Uid::INVALID;
2976 std::map<gui::Uid, float> opacityByUid;
chaviw98318de2021-05-19 16:45:23 -05002977 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002978 if (windowHandle == otherHandle) {
2979 break; // All future windows are below us. Exit early.
2980 }
chaviw98318de2021-05-19 16:45:23 -05002981 const WindowInfo* otherInfo = otherHandle->getInfo();
Bernardo Rufino1ff9d592021-01-18 16:58:57 +00002982 if (canBeObscuredBy(windowHandle, otherHandle) && otherInfo->frameContainsPoint(x, y) &&
2983 !haveSameApplicationToken(windowInfo, otherInfo)) {
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002984 if (DEBUG_TOUCH_OCCLUSION) {
2985 info.debugInfo.push_back(
Harry Cutts101ee9b2023-07-06 18:04:14 +00002986 dumpWindowForTouchOcclusion(otherInfo, /*isTouchedWindow=*/false));
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002987 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002988 // canBeObscuredBy() has returned true above, which means this window is untrusted, so
2989 // we perform the checks below to see if the touch can be propagated or not based on the
2990 // window's touch occlusion mode
2991 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::BLOCK_UNTRUSTED) {
2992 info.hasBlockingOcclusion = true;
2993 info.obscuringUid = otherInfo->ownerUid;
2994 info.obscuringPackage = otherInfo->packageName;
2995 break;
2996 }
2997 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::USE_OPACITY) {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00002998 const auto uid = otherInfo->ownerUid;
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002999 float opacity =
3000 (opacityByUid.find(uid) == opacityByUid.end()) ? 0 : opacityByUid[uid];
3001 // Given windows A and B:
3002 // opacity(A, B) = 1 - [1 - opacity(A)] * [1 - opacity(B)]
3003 opacity = 1 - (1 - opacity) * (1 - otherInfo->alpha);
3004 opacityByUid[uid] = opacity;
3005 if (opacity > info.obscuringOpacity) {
3006 info.obscuringOpacity = opacity;
3007 info.obscuringUid = uid;
3008 info.obscuringPackage = otherInfo->packageName;
3009 }
3010 }
3011 }
3012 }
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00003013 if (DEBUG_TOUCH_OCCLUSION) {
Harry Cutts101ee9b2023-07-06 18:04:14 +00003014 info.debugInfo.push_back(dumpWindowForTouchOcclusion(windowInfo, /*isTouchedWindow=*/true));
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00003015 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003016 return info;
3017}
3018
chaviw98318de2021-05-19 16:45:23 -05003019std::string InputDispatcher::dumpWindowForTouchOcclusion(const WindowInfo* info,
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00003020 bool isTouchedWindow) const {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003021 return StringPrintf(INDENT2 "* %spackage=%s/%s, id=%" PRId32 ", mode=%s, alpha=%.2f, "
Prabir Pradhan51e7db02022-02-07 06:02:57 -08003022 "frame=[%" PRId32 ",%" PRId32 "][%" PRId32 ",%" PRId32
3023 "], touchableRegion=%s, window={%s}, inputConfig={%s}, "
3024 "hasToken=%s, applicationInfo.name=%s, applicationInfo.token=%s\n",
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08003025 isTouchedWindow ? "[TOUCHED] " : "", info->packageName.c_str(),
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003026 info->ownerUid.toString().c_str(), info->id,
3027 toString(info->touchOcclusionMode).c_str(), info->alpha, info->frameLeft,
3028 info->frameTop, info->frameRight, info->frameBottom,
3029 dumpRegion(info->touchableRegion).c_str(), info->name.c_str(),
3030 info->inputConfig.string().c_str(), toString(info->token != nullptr),
3031 info->applicationInfo.name.c_str(),
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07003032 binderToString(info->applicationInfo.token).c_str());
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00003033}
3034
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003035bool InputDispatcher::isTouchTrustedLocked(const TouchOcclusionInfo& occlusionInfo) const {
3036 if (occlusionInfo.hasBlockingOcclusion) {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003037 ALOGW("Untrusted touch due to occlusion by %s/%s", occlusionInfo.obscuringPackage.c_str(),
3038 occlusionInfo.obscuringUid.toString().c_str());
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003039 return false;
3040 }
3041 if (occlusionInfo.obscuringOpacity > mMaximumObscuringOpacityForTouch) {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003042 ALOGW("Untrusted touch due to occlusion by %s/%s (obscuring opacity = "
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003043 "%.2f, maximum allowed = %.2f)",
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003044 occlusionInfo.obscuringPackage.c_str(), occlusionInfo.obscuringUid.toString().c_str(),
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003045 occlusionInfo.obscuringOpacity, mMaximumObscuringOpacityForTouch);
3046 return false;
3047 }
3048 return true;
3049}
3050
chaviw98318de2021-05-19 16:45:23 -05003051bool InputDispatcher::isWindowObscuredAtPointLocked(const sp<WindowInfoHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003052 int32_t x, int32_t y) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003053 int32_t displayId = windowHandle->getInfo()->displayId;
chaviw98318de2021-05-19 16:45:23 -05003054 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
3055 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07003056 if (windowHandle == otherHandle) {
3057 break; // All future windows are below us. Exit early.
Michael Wrightd02c5b62014-02-10 15:10:22 -08003058 }
chaviw98318de2021-05-19 16:45:23 -05003059 const WindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07003060 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08003061 otherInfo->frameContainsPoint(x, y)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003062 return true;
3063 }
3064 }
3065 return false;
3066}
3067
chaviw98318de2021-05-19 16:45:23 -05003068bool InputDispatcher::isWindowObscuredLocked(const sp<WindowInfoHandle>& windowHandle) const {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07003069 int32_t displayId = windowHandle->getInfo()->displayId;
chaviw98318de2021-05-19 16:45:23 -05003070 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
3071 const WindowInfo* windowInfo = windowHandle->getInfo();
3072 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07003073 if (windowHandle == otherHandle) {
3074 break; // All future windows are below us. Exit early.
Michael Wrightcdcd8f22016-03-22 16:52:13 -07003075 }
chaviw98318de2021-05-19 16:45:23 -05003076 const WindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07003077 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08003078 otherInfo->overlaps(windowInfo)) {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07003079 return true;
3080 }
3081 }
3082 return false;
3083}
3084
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08003085std::string InputDispatcher::getApplicationWindowLabel(
chaviw98318de2021-05-19 16:45:23 -05003086 const InputApplicationHandle* applicationHandle, const sp<WindowInfoHandle>& windowHandle) {
Yi Kong9b14ac62018-07-17 13:48:38 -07003087 if (applicationHandle != nullptr) {
3088 if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07003089 return applicationHandle->getName() + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003090 } else {
3091 return applicationHandle->getName();
3092 }
Yi Kong9b14ac62018-07-17 13:48:38 -07003093 } else if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07003094 return windowHandle->getInfo()->applicationInfo.name + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003095 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003096 return "<unknown application or window>";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003097 }
3098}
3099
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003100void InputDispatcher::pokeUserActivityLocked(const EventEntry& eventEntry) {
Antonio Kantekf16f2832021-09-28 04:39:20 +00003101 if (!isUserActivityEvent(eventEntry)) {
3102 // Not poking user activity if the event type does not represent a user activity
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003103 return;
3104 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003105 int32_t displayId = getTargetDisplayId(eventEntry);
chaviw98318de2021-05-19 16:45:23 -05003106 sp<WindowInfoHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Josep del Riob3981622023-04-18 15:49:45 +00003107 const WindowInfo* windowDisablingUserActivityInfo = nullptr;
Tiger Huang721e26f2018-07-24 22:26:19 +08003108 if (focusedWindowHandle != nullptr) {
chaviw98318de2021-05-19 16:45:23 -05003109 const WindowInfo* info = focusedWindowHandle->getInfo();
Prabir Pradhan51e7db02022-02-07 06:02:57 -08003110 if (info->inputConfig.test(WindowInfo::InputConfig::DISABLE_USER_ACTIVITY)) {
Josep del Riob3981622023-04-18 15:49:45 +00003111 windowDisablingUserActivityInfo = info;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003112 }
3113 }
3114
3115 int32_t eventType = USER_ACTIVITY_EVENT_OTHER;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003116 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003117 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003118 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
3119 if (motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003120 return;
3121 }
Josep del Riob3981622023-04-18 15:49:45 +00003122 if (windowDisablingUserActivityInfo != nullptr) {
3123 if (DEBUG_DISPATCH_CYCLE) {
3124 ALOGD("Not poking user activity: disabled by window '%s'.",
3125 windowDisablingUserActivityInfo->name.c_str());
3126 }
3127 return;
3128 }
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003129 if (MotionEvent::isTouchEvent(motionEntry.source, motionEntry.action)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003130 eventType = USER_ACTIVITY_EVENT_TOUCH;
3131 }
3132 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003133 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003134 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003135 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
3136 if (keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003137 return;
3138 }
Josep del Riob3981622023-04-18 15:49:45 +00003139 // If the key code is unknown, we don't consider it user activity
3140 if (keyEntry.keyCode == AKEYCODE_UNKNOWN) {
3141 return;
3142 }
3143 // Don't inhibit events that were intercepted or are not passed to
3144 // the apps, like system shortcuts
3145 if (windowDisablingUserActivityInfo != nullptr &&
3146 keyEntry.interceptKeyResult != KeyEntry::InterceptKeyResult::SKIP &&
3147 keyEntry.policyFlags & POLICY_FLAG_PASS_TO_USER) {
3148 if (DEBUG_DISPATCH_CYCLE) {
3149 ALOGD("Not poking user activity: disabled by window '%s'.",
3150 windowDisablingUserActivityInfo->name.c_str());
3151 }
3152 return;
3153 }
3154
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003155 eventType = USER_ACTIVITY_EVENT_BUTTON;
3156 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003157 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00003158 default: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003159 LOG_ALWAYS_FATAL("%s events are not user activity",
Dominik Laskowski75788452021-02-09 18:51:25 -08003160 ftl::enum_string(eventEntry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003161 break;
3162 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003163 }
3164
Prabir Pradhancef936d2021-07-21 16:17:52 +00003165 auto command = [this, eventTime = eventEntry.eventTime, eventType, displayId]()
3166 REQUIRES(mLock) {
3167 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00003168 mPolicy.pokeUserActivity(eventTime, eventType, displayId);
Prabir Pradhancef936d2021-07-21 16:17:52 +00003169 };
3170 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003171}
3172
3173void InputDispatcher::prepareDispatchCycleLocked(nsecs_t currentTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003174 const std::shared_ptr<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003175 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003176 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003177 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003178 std::string message =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003179 StringPrintf("prepareDispatchCycleLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003180 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00003181 ATRACE_NAME(message.c_str());
3182 }
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003183 if (DEBUG_DISPATCH_CYCLE) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003184 ALOGD("channel '%s' ~ prepareDispatchCycle - flags=%s, "
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08003185 "globalScaleFactor=%f, pointerIds=%s %s",
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003186 connection->getInputChannelName().c_str(), inputTarget.flags.string().c_str(),
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08003187 inputTarget.globalScaleFactor, bitsetToString(inputTarget.pointerIds).c_str(),
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003188 inputTarget.getPointerInfoString().c_str());
3189 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003190
3191 // Skip this event if the connection status is not normal.
3192 // We don't want to enqueue additional outbound events if the connection is broken.
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003193 if (connection->status != Connection::Status::NORMAL) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003194 if (DEBUG_DISPATCH_CYCLE) {
3195 ALOGD("channel '%s' ~ Dropping event because the channel status is %s",
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003196 connection->getInputChannelName().c_str(),
3197 ftl::enum_string(connection->status).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003198 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003199 return;
3200 }
3201
3202 // Split a motion event if needed.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003203 if (inputTarget.flags.test(InputTarget::Flags::SPLIT)) {
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003204 LOG_ALWAYS_FATAL_IF(eventEntry->type != EventEntry::Type::MOTION,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003205 "Entry type %s should not have Flags::SPLIT",
Dominik Laskowski75788452021-02-09 18:51:25 -08003206 ftl::enum_string(eventEntry->type).c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003207
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003208 const MotionEntry& originalMotionEntry = static_cast<const MotionEntry&>(*eventEntry);
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003209 if (inputTarget.pointerIds.count() != originalMotionEntry.pointerCount) {
Siarhei Vishniakou16e4fa02023-02-16 17:48:56 -08003210 if (!inputTarget.firstDownTimeInTarget.has_value()) {
3211 logDispatchStateLocked();
3212 LOG(FATAL) << "Splitting motion events requires a down time to be set for the "
3213 "target on connection "
3214 << connection->getInputChannelName() << " for "
3215 << originalMotionEntry.getDescription();
3216 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003217 std::unique_ptr<MotionEntry> splitMotionEntry =
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00003218 splitMotionEvent(originalMotionEntry, inputTarget.pointerIds,
3219 inputTarget.firstDownTimeInTarget.value());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003220 if (!splitMotionEntry) {
3221 return; // split event was dropped
3222 }
Arthur Hungb3307ee2021-10-14 10:57:37 +00003223 if (splitMotionEntry->action == AMOTION_EVENT_ACTION_CANCEL) {
3224 std::string reason = std::string("reason=pointer cancel on split window");
3225 android_log_event_list(LOGTAG_INPUT_CANCEL)
3226 << connection->getInputChannelName().c_str() << reason << LOG_ID_EVENTS;
3227 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003228 if (DEBUG_FOCUS) {
3229 ALOGD("channel '%s' ~ Split motion event.",
3230 connection->getInputChannelName().c_str());
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003231 logOutboundMotionDetails(" ", *splitMotionEntry);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003232 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003233 enqueueDispatchEntriesLocked(currentTime, connection, std::move(splitMotionEntry),
3234 inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003235 return;
3236 }
3237 }
3238
3239 // Not splitting. Enqueue dispatch entries for the event as is.
3240 enqueueDispatchEntriesLocked(currentTime, connection, eventEntry, inputTarget);
3241}
3242
3243void InputDispatcher::enqueueDispatchEntriesLocked(nsecs_t currentTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003244 const std::shared_ptr<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003245 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003246 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003247 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003248 std::string message =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003249 StringPrintf("enqueueDispatchEntriesLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003250 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00003251 ATRACE_NAME(message.c_str());
3252 }
Siarhei Vishniakou5cee1e32022-11-29 12:35:39 -08003253 LOG_ALWAYS_FATAL_IF(!inputTarget.flags.any(InputTarget::DISPATCH_MASK),
3254 "No dispatch flags are set for %s", eventEntry->getDescription().c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00003255
hongzuo liu95785e22022-09-06 02:51:35 +00003256 const bool wasEmpty = connection->outboundQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003257
3258 // Enqueue dispatch entries for the requested modes.
chaviw8c9cf542019-03-25 13:02:48 -07003259 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003260 InputTarget::Flags::DISPATCH_AS_HOVER_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07003261 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003262 InputTarget::Flags::DISPATCH_AS_OUTSIDE);
chaviw8c9cf542019-03-25 13:02:48 -07003263 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003264 InputTarget::Flags::DISPATCH_AS_HOVER_ENTER);
chaviw8c9cf542019-03-25 13:02:48 -07003265 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003266 InputTarget::Flags::DISPATCH_AS_IS);
chaviw8c9cf542019-03-25 13:02:48 -07003267 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003268 InputTarget::Flags::DISPATCH_AS_SLIPPERY_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07003269 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003270 InputTarget::Flags::DISPATCH_AS_SLIPPERY_ENTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003271
3272 // If the outbound queue was previously empty, start the dispatch cycle going.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003273 if (wasEmpty && !connection->outboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003274 startDispatchCycleLocked(currentTime, connection);
3275 }
3276}
3277
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003278void InputDispatcher::enqueueDispatchEntryLocked(const std::shared_ptr<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003279 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003280 const InputTarget& inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003281 ftl::Flags<InputTarget::Flags> dispatchMode) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003282 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003283 std::string message = StringPrintf("enqueueDispatchEntry(inputChannel=%s, dispatchMode=%s)",
3284 connection->getInputChannelName().c_str(),
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003285 dispatchMode.string().c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00003286 ATRACE_NAME(message.c_str());
3287 }
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003288 ftl::Flags<InputTarget::Flags> inputTargetFlags = inputTarget.flags;
3289 if (!inputTargetFlags.any(dispatchMode)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003290 return;
3291 }
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003292
3293 inputTargetFlags.clear(InputTarget::DISPATCH_MASK);
3294 inputTargetFlags |= dispatchMode;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003295
3296 // This is a new event.
3297 // Enqueue a new dispatch entry onto the outbound queue for this connection.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003298 std::unique_ptr<DispatchEntry> dispatchEntry =
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003299 createDispatchEntry(inputTarget, eventEntry, inputTargetFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003300
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003301 // Use the eventEntry from dispatchEntry since the entry may have changed and can now be a
3302 // different EventEntry than what was passed in.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003303 EventEntry& newEntry = *(dispatchEntry->eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003304 // Apply target flags and update the connection's input state.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003305 switch (newEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003306 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003307 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(newEntry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003308 if (!connection->inputState.trackKey(keyEntry, dispatchEntry->resolvedAction,
3309 dispatchEntry->resolvedFlags)) {
Siarhei Vishniakouc94dafe2023-05-26 10:24:19 -07003310 LOG(WARNING) << "channel " << connection->getInputChannelName()
3311 << "~ dropping inconsistent event: " << *dispatchEntry;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003312 return; // skip the inconsistent event
3313 }
3314 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003315 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003316
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003317 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003318 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003319 // Assign a default value to dispatchEntry that will never be generated by InputReader,
3320 // and assign a InputDispatcher value if it doesn't change in the if-else chain below.
3321 constexpr int32_t DEFAULT_RESOLVED_EVENT_ID =
3322 static_cast<int32_t>(IdGenerator::Source::OTHER);
3323 dispatchEntry->resolvedEventId = DEFAULT_RESOLVED_EVENT_ID;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003324 if (dispatchMode.test(InputTarget::Flags::DISPATCH_AS_OUTSIDE)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003325 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_OUTSIDE;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003326 } else if (dispatchMode.test(InputTarget::Flags::DISPATCH_AS_HOVER_EXIT)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003327 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_EXIT;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003328 } else if (dispatchMode.test(InputTarget::Flags::DISPATCH_AS_HOVER_ENTER)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003329 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003330 } else if (dispatchMode.test(InputTarget::Flags::DISPATCH_AS_SLIPPERY_EXIT)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003331 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_CANCEL;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003332 } else if (dispatchMode.test(InputTarget::Flags::DISPATCH_AS_SLIPPERY_ENTER)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003333 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_DOWN;
3334 } else {
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003335 dispatchEntry->resolvedEventId = motionEntry.id;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003336 }
3337 if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_HOVER_MOVE &&
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003338 !connection->inputState.isHovering(motionEntry.deviceId, motionEntry.source,
3339 motionEntry.displayId)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003340 if (DEBUG_DISPATCH_CYCLE) {
3341 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: filling in missing hover "
3342 "enter event",
3343 connection->getInputChannelName().c_str());
3344 }
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00003345 // We keep the 'resolvedEventId' here equal to the original 'motionEntry.id' because
3346 // this is a one-to-one event conversion.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003347 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
3348 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003349
Siarhei Vishniakou1ae72f12023-01-29 12:55:30 -08003350 if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_CANCEL) {
3351 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_CANCELED;
3352 }
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003353 if (dispatchEntry->targetFlags.test(InputTarget::Flags::WINDOW_IS_OBSCURED)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003354 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED;
3355 }
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003356 if (dispatchEntry->targetFlags.test(InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003357 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
3358 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003359
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003360 if (!connection->inputState.trackMotion(motionEntry, dispatchEntry->resolvedAction,
3361 dispatchEntry->resolvedFlags)) {
Siarhei Vishniakouc94dafe2023-05-26 10:24:19 -07003362 LOG(WARNING) << "channel " << connection->getInputChannelName()
3363 << "~ dropping inconsistent event: " << *dispatchEntry;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003364 return; // skip the inconsistent event
3365 }
3366
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003367 dispatchEntry->resolvedEventId =
3368 dispatchEntry->resolvedEventId == DEFAULT_RESOLVED_EVENT_ID
3369 ? mIdGenerator.nextId()
3370 : motionEntry.id;
3371 if (ATRACE_ENABLED() && dispatchEntry->resolvedEventId != motionEntry.id) {
3372 std::string message = StringPrintf("Transmute MotionEvent(id=0x%" PRIx32
3373 ") to MotionEvent(id=0x%" PRIx32 ").",
3374 motionEntry.id, dispatchEntry->resolvedEventId);
3375 ATRACE_NAME(message.c_str());
3376 }
3377
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08003378 if ((motionEntry.flags & AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE) &&
3379 (motionEntry.policyFlags & POLICY_FLAG_TRUSTED)) {
3380 // Skip reporting pointer down outside focus to the policy.
3381 break;
3382 }
3383
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003384 dispatchPointerDownOutsideFocus(motionEntry.source, dispatchEntry->resolvedAction,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003385 inputTarget.inputChannel->getConnectionToken());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003386
3387 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003388 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003389 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003390 case EventEntry::Type::TOUCH_MODE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08003391 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
3392 case EventEntry::Type::DRAG: {
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003393 break;
3394 }
Chris Yef59a2f42020-10-16 12:55:26 -07003395 case EventEntry::Type::SENSOR: {
3396 LOG_ALWAYS_FATAL("SENSOR events should not go to apps via input channel");
3397 break;
3398 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003399 case EventEntry::Type::CONFIGURATION_CHANGED:
3400 case EventEntry::Type::DEVICE_RESET: {
3401 LOG_ALWAYS_FATAL("%s events should not go to apps",
Dominik Laskowski75788452021-02-09 18:51:25 -08003402 ftl::enum_string(newEntry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003403 break;
3404 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003405 }
3406
3407 // Remember that we are waiting for this dispatch to complete.
3408 if (dispatchEntry->hasForegroundTarget()) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003409 incrementPendingForegroundDispatches(newEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003410 }
3411
3412 // Enqueue the dispatch entry.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003413 connection->outboundQueue.push_back(dispatchEntry.release());
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003414 traceOutboundQueueLength(*connection);
chaviw8c9cf542019-03-25 13:02:48 -07003415}
3416
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003417/**
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003418 * This function is for debugging and metrics collection. It has two roles.
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003419 *
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003420 * The first role is to log input interaction with windows, which helps determine what the user was
3421 * interacting with. For example, if user is touching launcher, we will see an input_interaction log
3422 * that user started interacting with launcher window, as well as any other window that received
3423 * that gesture, such as the wallpaper or other spy windows. A new input_interaction is only logged
3424 * when the set of tokens that received the event changes. It is not logged again as long as the
3425 * user is interacting with the same windows.
3426 *
3427 * The second role is to track input device activity for metrics collection. For each input event,
3428 * we report the set of UIDs that the input device interacted with to the policy. Unlike for the
3429 * input_interaction logs, the device interaction is reported even when the set of interaction
3430 * tokens do not change.
3431 *
3432 * For these purposes, we do not count ACTION_OUTSIDE, ACTION_UP and ACTION_CANCEL actions as
3433 * interaction. This includes up and cancel events for both keys and motions.
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003434 */
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003435void InputDispatcher::processInteractionsLocked(const EventEntry& entry,
3436 const std::vector<InputTarget>& targets) {
3437 int32_t deviceId;
3438 nsecs_t eventTime;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003439 // Skip ACTION_UP events, and all events other than keys and motions
3440 if (entry.type == EventEntry::Type::KEY) {
3441 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
3442 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
3443 return;
3444 }
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003445 deviceId = keyEntry.deviceId;
3446 eventTime = keyEntry.eventTime;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003447 } else if (entry.type == EventEntry::Type::MOTION) {
3448 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
3449 if (motionEntry.action == AMOTION_EVENT_ACTION_UP ||
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003450 motionEntry.action == AMOTION_EVENT_ACTION_CANCEL ||
3451 MotionEvent::getActionMasked(motionEntry.action) == AMOTION_EVENT_ACTION_POINTER_UP) {
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003452 return;
3453 }
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003454 deviceId = motionEntry.deviceId;
3455 eventTime = motionEntry.eventTime;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003456 } else {
3457 return; // Not a key or a motion
3458 }
3459
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003460 std::set<gui::Uid> interactionUids;
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07003461 std::unordered_set<sp<IBinder>, StrongPointerHash<IBinder>> newConnectionTokens;
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003462 std::vector<std::shared_ptr<Connection>> newConnections;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003463 for (const InputTarget& target : targets) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003464 if (target.flags.test(InputTarget::Flags::DISPATCH_AS_OUTSIDE)) {
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003465 continue; // Skip windows that receive ACTION_OUTSIDE
3466 }
3467
3468 sp<IBinder> token = target.inputChannel->getConnectionToken();
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003469 std::shared_ptr<Connection> connection = getConnectionLocked(token);
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003470 if (connection == nullptr) {
3471 continue;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003472 }
3473 newConnectionTokens.insert(std::move(token));
3474 newConnections.emplace_back(connection);
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003475 if (target.windowHandle) {
3476 interactionUids.emplace(target.windowHandle->getInfo()->ownerUid);
3477 }
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003478 }
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003479
3480 auto command = [this, deviceId, eventTime, uids = std::move(interactionUids)]()
3481 REQUIRES(mLock) {
3482 scoped_unlock unlock(mLock);
3483 mPolicy.notifyDeviceInteraction(deviceId, eventTime, uids);
3484 };
3485 postCommandLocked(std::move(command));
3486
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003487 if (newConnectionTokens == mInteractionConnectionTokens) {
3488 return; // no change
3489 }
3490 mInteractionConnectionTokens = newConnectionTokens;
3491
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003492 std::string targetList;
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003493 for (const std::shared_ptr<Connection>& connection : newConnections) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003494 targetList += connection->getWindowName() + ", ";
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003495 }
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003496 std::string message = "Interaction with: " + targetList;
3497 if (targetList.empty()) {
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003498 message += "<none>";
3499 }
3500 android_log_event_list(LOGTAG_INPUT_INTERACTION) << message << LOG_ID_EVENTS;
3501}
3502
chaviwfd6d3512019-03-25 13:23:49 -07003503void InputDispatcher::dispatchPointerDownOutsideFocus(uint32_t source, int32_t action,
Vishnu Nairad321cd2020-08-20 16:40:21 -07003504 const sp<IBinder>& token) {
chaviw8c9cf542019-03-25 13:02:48 -07003505 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
chaviwfd6d3512019-03-25 13:23:49 -07003506 uint32_t maskedSource = source & AINPUT_SOURCE_CLASS_MASK;
3507 if (maskedSource != AINPUT_SOURCE_CLASS_POINTER || maskedAction != AMOTION_EVENT_ACTION_DOWN) {
chaviw8c9cf542019-03-25 13:02:48 -07003508 return;
3509 }
3510
Vishnu Nairc519ff72021-01-21 08:23:08 -08003511 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07003512 if (focusedToken == token) {
3513 // ignore since token is focused
chaviw8c9cf542019-03-25 13:02:48 -07003514 return;
3515 }
3516
Prabir Pradhancef936d2021-07-21 16:17:52 +00003517 auto command = [this, token]() REQUIRES(mLock) {
3518 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00003519 mPolicy.onPointerDownOutsideFocus(token);
Prabir Pradhancef936d2021-07-21 16:17:52 +00003520 };
3521 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003522}
3523
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003524status_t InputDispatcher::publishMotionEvent(Connection& connection,
3525 DispatchEntry& dispatchEntry) const {
3526 const EventEntry& eventEntry = *(dispatchEntry.eventEntry);
3527 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
3528
3529 PointerCoords scaledCoords[MAX_POINTERS];
3530 const PointerCoords* usingCoords = motionEntry.pointerCoords;
3531
3532 // Set the X and Y offset and X and Y scale depending on the input source.
3533 if ((motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) &&
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003534 !(dispatchEntry.targetFlags.test(InputTarget::Flags::ZERO_COORDS))) {
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003535 float globalScaleFactor = dispatchEntry.globalScaleFactor;
3536 if (globalScaleFactor != 1.0f) {
3537 for (uint32_t i = 0; i < motionEntry.pointerCount; i++) {
3538 scaledCoords[i] = motionEntry.pointerCoords[i];
3539 // Don't apply window scale here since we don't want scale to affect raw
3540 // coordinates. The scale will be sent back to the client and applied
3541 // later when requesting relative coordinates.
Harry Cutts33476232023-01-30 19:57:29 +00003542 scaledCoords[i].scale(globalScaleFactor, /*windowXScale=*/1, /*windowYScale=*/1);
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003543 }
3544 usingCoords = scaledCoords;
3545 }
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003546 } else if (dispatchEntry.targetFlags.test(InputTarget::Flags::ZERO_COORDS)) {
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003547 // We don't want the dispatch target to know the coordinates
3548 for (uint32_t i = 0; i < motionEntry.pointerCount; i++) {
3549 scaledCoords[i].clear();
3550 }
3551 usingCoords = scaledCoords;
3552 }
3553
3554 std::array<uint8_t, 32> hmac = getSignature(motionEntry, dispatchEntry);
3555
3556 // Publish the motion event.
3557 return connection.inputPublisher
3558 .publishMotionEvent(dispatchEntry.seq, dispatchEntry.resolvedEventId,
3559 motionEntry.deviceId, motionEntry.source, motionEntry.displayId,
3560 std::move(hmac), dispatchEntry.resolvedAction,
3561 motionEntry.actionButton, dispatchEntry.resolvedFlags,
3562 motionEntry.edgeFlags, motionEntry.metaState,
3563 motionEntry.buttonState, motionEntry.classification,
3564 dispatchEntry.transform, motionEntry.xPrecision,
3565 motionEntry.yPrecision, motionEntry.xCursorPosition,
3566 motionEntry.yCursorPosition, dispatchEntry.rawTransform,
3567 motionEntry.downTime, motionEntry.eventTime,
3568 motionEntry.pointerCount, motionEntry.pointerProperties,
3569 usingCoords);
3570}
3571
Michael Wrightd02c5b62014-02-10 15:10:22 -08003572void InputDispatcher::startDispatchCycleLocked(nsecs_t currentTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003573 const std::shared_ptr<Connection>& connection) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003574 if (ATRACE_ENABLED()) {
3575 std::string message = StringPrintf("startDispatchCycleLocked(inputChannel=%s)",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003576 connection->getInputChannelName().c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00003577 ATRACE_NAME(message.c_str());
3578 }
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003579 if (DEBUG_DISPATCH_CYCLE) {
3580 ALOGD("channel '%s' ~ startDispatchCycle", connection->getInputChannelName().c_str());
3581 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003582
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003583 while (connection->status == Connection::Status::NORMAL && !connection->outboundQueue.empty()) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003584 DispatchEntry* dispatchEntry = connection->outboundQueue.front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003585 dispatchEntry->deliveryTime = currentTime;
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003586 const std::chrono::nanoseconds timeout = getDispatchingTimeoutLocked(connection);
Siarhei Vishniakou70622952020-07-30 11:17:23 -05003587 dispatchEntry->timeoutTime = currentTime + timeout.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003588
3589 // Publish the event.
3590 status_t status;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003591 const EventEntry& eventEntry = *(dispatchEntry->eventEntry);
3592 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003593 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003594 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
3595 std::array<uint8_t, 32> hmac = getSignature(keyEntry, *dispatchEntry);
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08003596 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
3597 LOG(DEBUG) << "Publishing " << *dispatchEntry << " to "
3598 << connection->getInputChannelName();
3599 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003600
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003601 // Publish the key event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003602 status = connection->inputPublisher
3603 .publishKeyEvent(dispatchEntry->seq,
3604 dispatchEntry->resolvedEventId, keyEntry.deviceId,
3605 keyEntry.source, keyEntry.displayId,
3606 std::move(hmac), dispatchEntry->resolvedAction,
3607 dispatchEntry->resolvedFlags, keyEntry.keyCode,
3608 keyEntry.scanCode, keyEntry.metaState,
3609 keyEntry.repeatCount, keyEntry.downTime,
3610 keyEntry.eventTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003611 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003612 }
3613
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003614 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08003615 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
3616 LOG(DEBUG) << "Publishing " << *dispatchEntry << " to "
3617 << connection->getInputChannelName();
3618 }
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003619 status = publishMotionEvent(*connection, *dispatchEntry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003620 break;
3621 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003622
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003623 case EventEntry::Type::FOCUS: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003624 const FocusEntry& focusEntry = static_cast<const FocusEntry&>(eventEntry);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003625 status = connection->inputPublisher.publishFocusEvent(dispatchEntry->seq,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003626 focusEntry.id,
Antonio Kantek3cfec7b2021-11-05 18:26:17 -07003627 focusEntry.hasFocus);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003628 break;
3629 }
3630
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003631 case EventEntry::Type::TOUCH_MODE_CHANGED: {
3632 const TouchModeEntry& touchModeEntry =
3633 static_cast<const TouchModeEntry&>(eventEntry);
3634 status = connection->inputPublisher
3635 .publishTouchModeEvent(dispatchEntry->seq, touchModeEntry.id,
3636 touchModeEntry.inTouchMode);
3637
3638 break;
3639 }
3640
Prabir Pradhan99987712020-11-10 18:43:05 -08003641 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
3642 const auto& captureEntry =
3643 static_cast<const PointerCaptureChangedEntry&>(eventEntry);
3644 status = connection->inputPublisher
3645 .publishCaptureEvent(dispatchEntry->seq, captureEntry.id,
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00003646 captureEntry.pointerCaptureRequest.enable);
Prabir Pradhan99987712020-11-10 18:43:05 -08003647 break;
3648 }
3649
arthurhungb89ccb02020-12-30 16:19:01 +08003650 case EventEntry::Type::DRAG: {
3651 const DragEntry& dragEntry = static_cast<const DragEntry&>(eventEntry);
3652 status = connection->inputPublisher.publishDragEvent(dispatchEntry->seq,
3653 dragEntry.id, dragEntry.x,
3654 dragEntry.y,
3655 dragEntry.isExiting);
3656 break;
3657 }
3658
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003659 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07003660 case EventEntry::Type::DEVICE_RESET:
3661 case EventEntry::Type::SENSOR: {
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003662 LOG_ALWAYS_FATAL("Should never start dispatch cycles for %s events",
Dominik Laskowski75788452021-02-09 18:51:25 -08003663 ftl::enum_string(eventEntry.type).c_str());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003664 return;
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003665 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003666 }
3667
3668 // Check the result.
3669 if (status) {
3670 if (status == WOULD_BLOCK) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003671 if (connection->waitQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003672 ALOGE("channel '%s' ~ Could not publish event because the pipe is full. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003673 "This is unexpected because the wait queue is empty, so the pipe "
3674 "should be empty and we shouldn't have any problems writing an "
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +00003675 "event to it, status=%s(%d)",
3676 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3677 status);
Harry Cutts33476232023-01-30 19:57:29 +00003678 abortBrokenDispatchCycleLocked(currentTime, connection, /*notify=*/true);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003679 } else {
3680 // Pipe is full and we are waiting for the app to finish process some events
3681 // before sending more events to it.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003682 if (DEBUG_DISPATCH_CYCLE) {
3683 ALOGD("channel '%s' ~ Could not publish event because the pipe is full, "
3684 "waiting for the application to catch up",
3685 connection->getInputChannelName().c_str());
3686 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003687 }
3688 } else {
3689 ALOGE("channel '%s' ~ Could not publish event due to an unexpected error, "
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +00003690 "status=%s(%d)",
3691 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3692 status);
Harry Cutts33476232023-01-30 19:57:29 +00003693 abortBrokenDispatchCycleLocked(currentTime, connection, /*notify=*/true);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003694 }
3695 return;
3696 }
3697
3698 // Re-enqueue the event on the wait queue.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003699 connection->outboundQueue.erase(std::remove(connection->outboundQueue.begin(),
3700 connection->outboundQueue.end(),
3701 dispatchEntry));
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003702 traceOutboundQueueLength(*connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003703 connection->waitQueue.push_back(dispatchEntry);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003704 if (connection->responsive) {
3705 mAnrTracker.insert(dispatchEntry->timeoutTime,
3706 connection->inputChannel->getConnectionToken());
3707 }
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003708 traceWaitQueueLength(*connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003709 }
3710}
3711
chaviw09c8d2d2020-08-24 15:48:26 -07003712std::array<uint8_t, 32> InputDispatcher::sign(const VerifiedInputEvent& event) const {
3713 size_t size;
3714 switch (event.type) {
3715 case VerifiedInputEvent::Type::KEY: {
3716 size = sizeof(VerifiedKeyEvent);
3717 break;
3718 }
3719 case VerifiedInputEvent::Type::MOTION: {
3720 size = sizeof(VerifiedMotionEvent);
3721 break;
3722 }
3723 }
3724 const uint8_t* start = reinterpret_cast<const uint8_t*>(&event);
3725 return mHmacKeyManager.sign(start, size);
3726}
3727
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003728const std::array<uint8_t, 32> InputDispatcher::getSignature(
3729 const MotionEntry& motionEntry, const DispatchEntry& dispatchEntry) const {
Siarhei Vishniakoubf880522023-05-01 11:03:22 -07003730 const int32_t actionMasked = MotionEvent::getActionMasked(dispatchEntry.resolvedAction);
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003731 if (actionMasked != AMOTION_EVENT_ACTION_UP && actionMasked != AMOTION_EVENT_ACTION_DOWN) {
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003732 // Only sign events up and down events as the purely move events
3733 // are tied to their up/down counterparts so signing would be redundant.
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003734 return INVALID_HMAC;
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003735 }
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003736
3737 VerifiedMotionEvent verifiedEvent =
3738 verifiedMotionEventFromMotionEntry(motionEntry, dispatchEntry.rawTransform);
3739 verifiedEvent.actionMasked = actionMasked;
3740 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_MOTION_EVENT_FLAGS;
3741 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003742}
3743
3744const std::array<uint8_t, 32> InputDispatcher::getSignature(
3745 const KeyEntry& keyEntry, const DispatchEntry& dispatchEntry) const {
3746 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEntry(keyEntry);
3747 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_KEY_EVENT_FLAGS;
3748 verifiedEvent.action = dispatchEntry.resolvedAction;
chaviw09c8d2d2020-08-24 15:48:26 -07003749 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003750}
3751
Michael Wrightd02c5b62014-02-10 15:10:22 -08003752void InputDispatcher::finishDispatchCycleLocked(nsecs_t currentTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003753 const std::shared_ptr<Connection>& connection,
3754 uint32_t seq, bool handled, nsecs_t consumeTime) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003755 if (DEBUG_DISPATCH_CYCLE) {
3756 ALOGD("channel '%s' ~ finishDispatchCycle - seq=%u, handled=%s",
3757 connection->getInputChannelName().c_str(), seq, toString(handled));
3758 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003759
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003760 if (connection->status == Connection::Status::BROKEN ||
3761 connection->status == Connection::Status::ZOMBIE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003762 return;
3763 }
3764
3765 // Notify other system components and prepare to start the next dispatch cycle.
Prabir Pradhancef936d2021-07-21 16:17:52 +00003766 auto command = [this, currentTime, connection, seq, handled, consumeTime]() REQUIRES(mLock) {
3767 doDispatchCycleFinishedCommand(currentTime, connection, seq, handled, consumeTime);
3768 };
3769 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003770}
3771
3772void InputDispatcher::abortBrokenDispatchCycleLocked(nsecs_t currentTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003773 const std::shared_ptr<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003774 bool notify) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003775 if (DEBUG_DISPATCH_CYCLE) {
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07003776 LOG(DEBUG) << "channel '" << connection->getInputChannelName() << "'~ " << __func__
3777 << " - notify=" << toString(notify);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003778 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003779
3780 // Clear the dispatch queues.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003781 drainDispatchQueue(connection->outboundQueue);
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003782 traceOutboundQueueLength(*connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003783 drainDispatchQueue(connection->waitQueue);
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003784 traceWaitQueueLength(*connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003785
3786 // The connection appears to be unrecoverably broken.
3787 // Ignore already broken or zombie connections.
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003788 if (connection->status == Connection::Status::NORMAL) {
3789 connection->status = Connection::Status::BROKEN;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003790
3791 if (notify) {
3792 // Notify other system components.
Prabir Pradhancef936d2021-07-21 16:17:52 +00003793 ALOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
3794 connection->getInputChannelName().c_str());
3795
3796 auto command = [this, connection]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00003797 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00003798 mPolicy.notifyInputChannelBroken(connection->inputChannel->getConnectionToken());
Prabir Pradhancef936d2021-07-21 16:17:52 +00003799 };
3800 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003801 }
3802 }
3803}
3804
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003805void InputDispatcher::drainDispatchQueue(std::deque<DispatchEntry*>& queue) {
3806 while (!queue.empty()) {
3807 DispatchEntry* dispatchEntry = queue.front();
3808 queue.pop_front();
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003809 releaseDispatchEntry(dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003810 }
3811}
3812
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003813void InputDispatcher::releaseDispatchEntry(DispatchEntry* dispatchEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003814 if (dispatchEntry->hasForegroundTarget()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003815 decrementPendingForegroundDispatches(*(dispatchEntry->eventEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003816 }
3817 delete dispatchEntry;
3818}
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
Svet Ganov5d3bc372020-01-26 23:11:07 -08003947 InputTarget target;
chaviw98318de2021-05-19 16:45:23 -05003948 sp<WindowInfoHandle> windowHandle =
Svet Ganov5d3bc372020-01-26 23:11:07 -08003949 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
3950 if (windowHandle != nullptr) {
chaviw98318de2021-05-19 16:45:23 -05003951 const WindowInfo* windowInfo = windowHandle->getInfo();
chaviw1ff3d1e2020-07-01 15:53:47 -07003952 target.setDefaultPointerTransform(windowInfo->transform);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003953 target.globalScaleFactor = windowInfo->globalScaleFactor;
3954 }
3955 target.inputChannel = connection->inputChannel;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003956 target.flags = InputTarget::Flags::DISPATCH_AS_IS;
Svet Ganov5d3bc372020-01-26 23:11:07 -08003957
hongzuo liu95785e22022-09-06 02:51:35 +00003958 const bool wasEmpty = connection->outboundQueue.empty();
3959
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003960 for (size_t i = 0; i < cancelationEvents.size(); i++) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003961 std::unique_ptr<EventEntry> cancelationEventEntry = std::move(cancelationEvents[i]);
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003962 switch (cancelationEventEntry->type) {
3963 case EventEntry::Type::KEY: {
3964 logOutboundKeyDetails("cancel - ",
3965 static_cast<const KeyEntry&>(*cancelationEventEntry));
3966 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003967 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003968 case EventEntry::Type::MOTION: {
3969 logOutboundMotionDetails("cancel - ",
3970 static_cast<const MotionEntry&>(*cancelationEventEntry));
3971 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003972 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003973 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003974 case EventEntry::Type::TOUCH_MODE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08003975 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
3976 case EventEntry::Type::DRAG: {
Prabir Pradhan99987712020-11-10 18:43:05 -08003977 LOG_ALWAYS_FATAL("Canceling %s events is not supported",
Dominik Laskowski75788452021-02-09 18:51:25 -08003978 ftl::enum_string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003979 break;
3980 }
3981 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07003982 case EventEntry::Type::DEVICE_RESET:
3983 case EventEntry::Type::SENSOR: {
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003984 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Dominik Laskowski75788452021-02-09 18:51:25 -08003985 ftl::enum_string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003986 break;
3987 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003988 }
3989
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003990 enqueueDispatchEntryLocked(connection, std::move(cancelationEventEntry), target,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003991 InputTarget::Flags::DISPATCH_AS_IS);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003992 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003993
hongzuo liu95785e22022-09-06 02:51:35 +00003994 // If the outbound queue was previously empty, start the dispatch cycle going.
3995 if (wasEmpty && !connection->outboundQueue.empty()) {
3996 startDispatchCycleLocked(currentTime, connection);
3997 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003998}
3999
Svet Ganov5d3bc372020-01-26 23:11:07 -08004000void InputDispatcher::synthesizePointerDownEventsForConnectionLocked(
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07004001 const nsecs_t downTime, const std::shared_ptr<Connection>& connection,
Arthur Hungc539dbb2022-12-08 07:45:36 +00004002 ftl::Flags<InputTarget::Flags> targetFlags) {
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08004003 if (connection->status == Connection::Status::BROKEN) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08004004 return;
4005 }
4006
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004007 std::vector<std::unique_ptr<EventEntry>> downEvents =
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00004008 connection->inputState.synthesizePointerDownEvents(downTime);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004009
4010 if (downEvents.empty()) {
4011 return;
4012 }
4013
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004014 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08004015 ALOGD("channel '%s' ~ Synthesized %zu down events to ensure consistent event stream.",
4016 connection->getInputChannelName().c_str(), downEvents.size());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004017 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08004018
4019 InputTarget target;
chaviw98318de2021-05-19 16:45:23 -05004020 sp<WindowInfoHandle> windowHandle =
Svet Ganov5d3bc372020-01-26 23:11:07 -08004021 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
4022 if (windowHandle != nullptr) {
chaviw98318de2021-05-19 16:45:23 -05004023 const WindowInfo* windowInfo = windowHandle->getInfo();
chaviw1ff3d1e2020-07-01 15:53:47 -07004024 target.setDefaultPointerTransform(windowInfo->transform);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004025 target.globalScaleFactor = windowInfo->globalScaleFactor;
4026 }
4027 target.inputChannel = connection->inputChannel;
Arthur Hungc539dbb2022-12-08 07:45:36 +00004028 target.flags = targetFlags;
Svet Ganov5d3bc372020-01-26 23:11:07 -08004029
hongzuo liu95785e22022-09-06 02:51:35 +00004030 const bool wasEmpty = connection->outboundQueue.empty();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004031 for (std::unique_ptr<EventEntry>& downEventEntry : downEvents) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08004032 switch (downEventEntry->type) {
4033 case EventEntry::Type::MOTION: {
4034 logOutboundMotionDetails("down - ",
4035 static_cast<const MotionEntry&>(*downEventEntry));
4036 break;
4037 }
4038
4039 case EventEntry::Type::KEY:
4040 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07004041 case EventEntry::Type::TOUCH_MODE_CHANGED:
Svet Ganov5d3bc372020-01-26 23:11:07 -08004042 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08004043 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07004044 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08004045 case EventEntry::Type::SENSOR:
4046 case EventEntry::Type::DRAG: {
Svet Ganov5d3bc372020-01-26 23:11:07 -08004047 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Dominik Laskowski75788452021-02-09 18:51:25 -08004048 ftl::enum_string(downEventEntry->type).c_str());
Svet Ganov5d3bc372020-01-26 23:11:07 -08004049 break;
4050 }
4051 }
4052
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004053 enqueueDispatchEntryLocked(connection, std::move(downEventEntry), target,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08004054 InputTarget::Flags::DISPATCH_AS_IS);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004055 }
4056
hongzuo liu95785e22022-09-06 02:51:35 +00004057 // If the outbound queue was previously empty, start the dispatch cycle going.
4058 if (wasEmpty && !connection->outboundQueue.empty()) {
4059 startDispatchCycleLocked(downTime, connection);
4060 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08004061}
4062
Arthur Hungc539dbb2022-12-08 07:45:36 +00004063void InputDispatcher::synthesizeCancelationEventsForWindowLocked(
4064 const sp<WindowInfoHandle>& windowHandle, const CancelationOptions& options) {
4065 if (windowHandle != nullptr) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07004066 std::shared_ptr<Connection> wallpaperConnection =
4067 getConnectionLocked(windowHandle->getToken());
Arthur Hungc539dbb2022-12-08 07:45:36 +00004068 if (wallpaperConnection != nullptr) {
4069 synthesizeCancelationEventsForConnectionLocked(wallpaperConnection, options);
4070 }
4071 }
4072}
4073
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004074std::unique_ptr<MotionEntry> InputDispatcher::splitMotionEvent(
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08004075 const MotionEntry& originalMotionEntry, std::bitset<MAX_POINTER_ID + 1> pointerIds,
4076 nsecs_t splitDownTime) {
4077 ALOG_ASSERT(pointerIds.any());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004078
4079 uint32_t splitPointerIndexMap[MAX_POINTERS];
4080 PointerProperties splitPointerProperties[MAX_POINTERS];
4081 PointerCoords splitPointerCoords[MAX_POINTERS];
4082
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07004083 uint32_t originalPointerCount = originalMotionEntry.pointerCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004084 uint32_t splitPointerCount = 0;
4085
4086 for (uint32_t originalPointerIndex = 0; originalPointerIndex < originalPointerCount;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004087 originalPointerIndex++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004088 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07004089 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08004090 uint32_t pointerId = uint32_t(pointerProperties.id);
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08004091 if (pointerIds.test(pointerId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004092 splitPointerIndexMap[splitPointerCount] = originalPointerIndex;
Siarhei Vishniakou73e6d372023-07-06 18:07:21 -07004093 splitPointerProperties[splitPointerCount] = pointerProperties;
4094 splitPointerCoords[splitPointerCount] =
4095 originalMotionEntry.pointerCoords[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08004096 splitPointerCount += 1;
4097 }
4098 }
4099
4100 if (splitPointerCount != pointerIds.count()) {
4101 // This is bad. We are missing some of the pointers that we expected to deliver.
4102 // Most likely this indicates that we received an ACTION_MOVE events that has
4103 // different pointer ids than we expected based on the previous ACTION_DOWN
4104 // or ACTION_POINTER_DOWN events that caused us to decide to split the pointers
4105 // in this way.
4106 ALOGW("Dropping split motion event because the pointer count is %d but "
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08004107 "we expected there to be %zu pointers. This probably means we received "
Siarhei Vishniakou16e4fa02023-02-16 17:48:56 -08004108 "a broken sequence of pointer ids from the input device: %s",
4109 splitPointerCount, pointerIds.count(), originalMotionEntry.getDescription().c_str());
Yi Kong9b14ac62018-07-17 13:48:38 -07004110 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004111 }
4112
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07004113 int32_t action = originalMotionEntry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004114 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004115 if (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN ||
4116 maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004117 int32_t originalPointerIndex = getMotionEventActionPointerIndex(action);
4118 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07004119 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08004120 uint32_t pointerId = uint32_t(pointerProperties.id);
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08004121 if (pointerIds.test(pointerId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004122 if (pointerIds.count() == 1) {
4123 // The first/last pointer went down/up.
4124 action = maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004125 ? AMOTION_EVENT_ACTION_DOWN
arthurhungea3f4fc2020-12-21 23:18:53 +08004126 : (originalMotionEntry.flags & AMOTION_EVENT_FLAG_CANCELED) != 0
4127 ? AMOTION_EVENT_ACTION_CANCEL
4128 : AMOTION_EVENT_ACTION_UP;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004129 } else {
4130 // A secondary pointer went down/up.
4131 uint32_t splitPointerIndex = 0;
4132 while (pointerId != uint32_t(splitPointerProperties[splitPointerIndex].id)) {
4133 splitPointerIndex += 1;
4134 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004135 action = maskedAction |
4136 (splitPointerIndex << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004137 }
4138 } else {
4139 // An unrelated pointer changed.
4140 action = AMOTION_EVENT_ACTION_MOVE;
4141 }
4142 }
4143
Siarhei Vishniakou59e302b2023-06-05 08:04:53 -07004144 if (action == AMOTION_EVENT_ACTION_DOWN && splitDownTime != originalMotionEntry.eventTime) {
4145 logDispatchStateLocked();
4146 LOG_ALWAYS_FATAL("Split motion event has mismatching downTime and eventTime for "
4147 "ACTION_DOWN, motionEntry=%s, splitDownTime=%" PRId64,
4148 originalMotionEntry.getDescription().c_str(), splitDownTime);
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00004149 }
4150
Garfield Tanff1f1bb2020-01-28 13:24:04 -08004151 int32_t newId = mIdGenerator.nextId();
4152 if (ATRACE_ENABLED()) {
4153 std::string message = StringPrintf("Split MotionEvent(id=0x%" PRIx32
4154 ") to MotionEvent(id=0x%" PRIx32 ").",
4155 originalMotionEntry.id, newId);
4156 ATRACE_NAME(message.c_str());
4157 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004158 std::unique_ptr<MotionEntry> splitMotionEntry =
4159 std::make_unique<MotionEntry>(newId, originalMotionEntry.eventTime,
4160 originalMotionEntry.deviceId, originalMotionEntry.source,
4161 originalMotionEntry.displayId,
4162 originalMotionEntry.policyFlags, action,
4163 originalMotionEntry.actionButton,
4164 originalMotionEntry.flags, originalMotionEntry.metaState,
4165 originalMotionEntry.buttonState,
4166 originalMotionEntry.classification,
4167 originalMotionEntry.edgeFlags,
4168 originalMotionEntry.xPrecision,
4169 originalMotionEntry.yPrecision,
4170 originalMotionEntry.xCursorPosition,
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00004171 originalMotionEntry.yCursorPosition, splitDownTime,
4172 splitPointerCount, splitPointerProperties,
4173 splitPointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004174
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07004175 if (originalMotionEntry.injectionState) {
4176 splitMotionEntry->injectionState = originalMotionEntry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004177 splitMotionEntry->injectionState->refCount += 1;
4178 }
4179
4180 return splitMotionEntry;
4181}
4182
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004183void InputDispatcher::notifyConfigurationChanged(const NotifyConfigurationChangedArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004184 if (debugInboundEventDetails()) {
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004185 ALOGD("notifyConfigurationChanged - eventTime=%" PRId64, args.eventTime);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004186 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004187
Antonio Kantekf16f2832021-09-28 04:39:20 +00004188 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004189 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004190 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004191
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004192 std::unique_ptr<ConfigurationChangedEntry> newEntry =
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004193 std::make_unique<ConfigurationChangedEntry>(args.id, args.eventTime);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004194 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004195 } // release lock
4196
4197 if (needWake) {
4198 mLooper->wake();
4199 }
4200}
4201
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05004202/**
4203 * If one of the meta shortcuts is detected, process them here:
Vaibhav Devmurari34cd5b02023-02-23 14:51:18 +00004204 * Meta + Backspace; Meta + Grave; Meta + Left arrow -> generate BACK
4205 * Most System shortcuts are handled in PhoneWindowManager.java except 'Back' shortcuts. Unlike
4206 * Back, other shortcuts DO NOT need to be sent to applications and are fully handled by the system.
4207 * But for Back key and Back shortcuts, we need to send KEYCODE_BACK to applications which can
4208 * potentially handle the back key presses.
4209 * Note: We don't send any Meta based KeyEvents to applications, so we need to convert to a KeyEvent
4210 * where meta modifier is off before sending. Currently only use case is 'Back'.
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05004211 */
4212void InputDispatcher::accelerateMetaShortcuts(const int32_t deviceId, const int32_t action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004213 int32_t& keyCode, int32_t& metaState) {
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05004214 if (metaState & AMETA_META_ON && action == AKEY_EVENT_ACTION_DOWN) {
4215 int32_t newKeyCode = AKEYCODE_UNKNOWN;
Vaibhav Devmurari34cd5b02023-02-23 14:51:18 +00004216 if (keyCode == AKEYCODE_DEL || keyCode == AKEYCODE_GRAVE || keyCode == AKEYCODE_DPAD_LEFT) {
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05004217 newKeyCode = AKEYCODE_BACK;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05004218 }
4219 if (newKeyCode != AKEYCODE_UNKNOWN) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004220 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05004221 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004222 mReplacedKeys[replacement] = newKeyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05004223 keyCode = newKeyCode;
4224 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
4225 }
4226 } else if (action == AKEY_EVENT_ACTION_UP) {
4227 // In order to maintain a consistent stream of up and down events, check to see if the key
4228 // going up is one we've replaced in a down event and haven't yet replaced in an up event,
4229 // even if the modifier was released between the down and the up events.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004230 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05004231 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004232 auto replacementIt = mReplacedKeys.find(replacement);
4233 if (replacementIt != mReplacedKeys.end()) {
4234 keyCode = replacementIt->second;
4235 mReplacedKeys.erase(replacementIt);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05004236 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
4237 }
4238 }
4239}
4240
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004241void InputDispatcher::notifyKey(const NotifyKeyArgs& args) {
Prabir Pradhan96282b02023-02-24 22:36:17 +00004242 ALOGD_IF(debugInboundEventDetails(),
4243 "notifyKey - id=%" PRIx32 ", eventTime=%" PRId64
4244 ", deviceId=%d, source=%s, displayId=%" PRId32
4245 "policyFlags=0x%x, action=%s, flags=0x%x, keyCode=%s, scanCode=0x%x, metaState=0x%x, "
4246 "downTime=%" PRId64,
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004247 args.id, args.eventTime, args.deviceId, inputEventSourceToString(args.source).c_str(),
4248 args.displayId, args.policyFlags, KeyEvent::actionToString(args.action), args.flags,
4249 KeyEvent::getLabel(args.keyCode), args.scanCode, args.metaState, args.downTime);
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004250 Result<void> keyCheck = validateKeyEvent(args.action);
4251 if (!keyCheck.ok()) {
4252 LOG(ERROR) << "invalid key event: " << keyCheck.error();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004253 return;
4254 }
4255
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004256 uint32_t policyFlags = args.policyFlags;
4257 int32_t flags = args.flags;
4258 int32_t metaState = args.metaState;
Siarhei Vishniakou622bd322018-10-29 18:02:27 -07004259 // InputDispatcher tracks and generates key repeats on behalf of
4260 // whatever notifies it, so repeatCount should always be set to 0
4261 constexpr int32_t repeatCount = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004262 if ((policyFlags & POLICY_FLAG_VIRTUAL) || (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY)) {
4263 policyFlags |= POLICY_FLAG_VIRTUAL;
4264 flags |= AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
4265 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004266 if (policyFlags & POLICY_FLAG_FUNCTION) {
4267 metaState |= AMETA_FUNCTION_ON;
4268 }
4269
4270 policyFlags |= POLICY_FLAG_TRUSTED;
4271
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004272 int32_t keyCode = args.keyCode;
4273 accelerateMetaShortcuts(args.deviceId, args.action, keyCode, metaState);
Michael Wright78f24442014-08-06 15:55:28 -07004274
Michael Wrightd02c5b62014-02-10 15:10:22 -08004275 KeyEvent event;
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004276 event.initialize(args.id, args.deviceId, args.source, args.displayId, INVALID_HMAC, args.action,
4277 flags, keyCode, args.scanCode, metaState, repeatCount, args.downTime,
4278 args.eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004279
Michael Wright2b3c3302018-03-02 17:19:13 +00004280 android::base::Timer t;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004281 mPolicy.interceptKeyBeforeQueueing(event, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00004282 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4283 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004284 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00004285 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004286
Antonio Kantekf16f2832021-09-28 04:39:20 +00004287 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004288 { // acquire lock
4289 mLock.lock();
4290
4291 if (shouldSendKeyToInputFilterLocked(args)) {
4292 mLock.unlock();
4293
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004294 policyFlags |= POLICY_FLAG_FILTERED;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004295 if (!mPolicy.filterInputEvent(event, policyFlags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004296 return; // event was consumed by the filter
4297 }
4298
4299 mLock.lock();
4300 }
4301
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004302 std::unique_ptr<KeyEntry> newEntry =
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004303 std::make_unique<KeyEntry>(args.id, args.eventTime, args.deviceId, args.source,
4304 args.displayId, policyFlags, args.action, flags, keyCode,
4305 args.scanCode, metaState, repeatCount, args.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004306
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004307 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004308 mLock.unlock();
4309 } // release lock
4310
4311 if (needWake) {
4312 mLooper->wake();
4313 }
4314}
4315
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004316bool InputDispatcher::shouldSendKeyToInputFilterLocked(const NotifyKeyArgs& args) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004317 return mInputFilterEnabled;
4318}
4319
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004320void InputDispatcher::notifyMotion(const NotifyMotionArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004321 if (debugInboundEventDetails()) {
Prabir Pradhan96282b02023-02-24 22:36:17 +00004322 ALOGD("notifyMotion - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=%s, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004323 "displayId=%" PRId32 ", policyFlags=0x%x, "
Siarhei Vishniakou6ebd0692022-10-20 15:05:45 -07004324 "action=%s, actionButton=0x%x, flags=0x%x, metaState=0x%x, buttonState=0x%x, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004325 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, xCursorPosition=%f, "
4326 "yCursorPosition=%f, downTime=%" PRId64,
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004327 args.id, args.eventTime, args.deviceId, inputEventSourceToString(args.source).c_str(),
4328 args.displayId, args.policyFlags, MotionEvent::actionToString(args.action).c_str(),
4329 args.actionButton, args.flags, args.metaState, args.buttonState, args.edgeFlags,
4330 args.xPrecision, args.yPrecision, args.xCursorPosition, args.yCursorPosition,
4331 args.downTime);
Siarhei Vishniakou3218fc02023-06-15 20:41:02 -07004332 for (uint32_t i = 0; i < args.getPointerCount(); i++) {
Prabir Pradhan96282b02023-02-24 22:36:17 +00004333 ALOGD(" Pointer %d: id=%d, toolType=%s, x=%f, y=%f, pressure=%f, size=%f, "
4334 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, orientation=%f",
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004335 i, args.pointerProperties[i].id,
4336 ftl::enum_string(args.pointerProperties[i].toolType).c_str(),
4337 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
4338 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
4339 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
4340 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
4341 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
4342 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
4343 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
4344 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
4345 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004346 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004347 }
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004348
Siarhei Vishniakou3218fc02023-06-15 20:41:02 -07004349 Result<void> motionCheck =
4350 validateMotionEvent(args.action, args.actionButton, args.getPointerCount(),
4351 args.pointerProperties.data());
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004352 if (!motionCheck.ok()) {
4353 LOG(FATAL) << "Invalid event: " << args.dump() << "; reason: " << motionCheck.error();
4354 return;
4355 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004356
Siarhei Vishniakou5c02a712023-05-15 15:45:02 -07004357 if (DEBUG_VERIFY_EVENTS) {
4358 auto [it, _] =
4359 mVerifiersByDisplay.try_emplace(args.displayId,
4360 StringPrintf("display %" PRId32, args.displayId));
4361 Result<void> result =
Siarhei Vishniakou3218fc02023-06-15 20:41:02 -07004362 it->second.processMovement(args.deviceId, args.action, args.getPointerCount(),
4363 args.pointerProperties.data(), args.pointerCoords.data(),
4364 args.flags);
Siarhei Vishniakou5c02a712023-05-15 15:45:02 -07004365 if (!result.ok()) {
4366 LOG(FATAL) << "Bad stream: " << result.error() << " caused by " << args.dump();
4367 }
4368 }
4369
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004370 uint32_t policyFlags = args.policyFlags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004371 policyFlags |= POLICY_FLAG_TRUSTED;
Michael Wright2b3c3302018-03-02 17:19:13 +00004372
4373 android::base::Timer t;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004374 mPolicy.interceptMotionBeforeQueueing(args.displayId, args.eventTime, policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00004375 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4376 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004377 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00004378 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004379
Antonio Kantekf16f2832021-09-28 04:39:20 +00004380 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004381 { // acquire lock
4382 mLock.lock();
Siarhei Vishniakou5bf25d92023-02-08 15:43:38 -08004383 if (!(policyFlags & POLICY_FLAG_PASS_TO_USER)) {
4384 // Set the flag anyway if we already have an ongoing gesture. That would allow us to
4385 // complete the processing of the current stroke.
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004386 const auto touchStateIt = mTouchStatesByDisplay.find(args.displayId);
Siarhei Vishniakou5bf25d92023-02-08 15:43:38 -08004387 if (touchStateIt != mTouchStatesByDisplay.end()) {
4388 const TouchState& touchState = touchStateIt->second;
Siarhei Vishniakou45504fe2023-05-05 16:05:10 -07004389 if (touchState.hasTouchingPointers(args.deviceId)) {
Siarhei Vishniakou5bf25d92023-02-08 15:43:38 -08004390 policyFlags |= POLICY_FLAG_PASS_TO_USER;
4391 }
4392 }
4393 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004394
4395 if (shouldSendMotionToInputFilterLocked(args)) {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004396 ui::Transform displayTransform;
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004397 if (const auto it = mDisplayInfos.find(args.displayId); it != mDisplayInfos.end()) {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004398 displayTransform = it->second.transform;
4399 }
4400
Michael Wrightd02c5b62014-02-10 15:10:22 -08004401 mLock.unlock();
4402
4403 MotionEvent event;
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004404 event.initialize(args.id, args.deviceId, args.source, args.displayId, INVALID_HMAC,
4405 args.action, args.actionButton, args.flags, args.edgeFlags,
4406 args.metaState, args.buttonState, args.classification,
4407 displayTransform, args.xPrecision, args.yPrecision,
4408 args.xCursorPosition, args.yCursorPosition, displayTransform,
Siarhei Vishniakou3218fc02023-06-15 20:41:02 -07004409 args.downTime, args.eventTime, args.getPointerCount(),
4410 args.pointerProperties.data(), args.pointerCoords.data());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004411
4412 policyFlags |= POLICY_FLAG_FILTERED;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004413 if (!mPolicy.filterInputEvent(event, policyFlags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004414 return; // event was consumed by the filter
4415 }
4416
4417 mLock.lock();
4418 }
4419
4420 // Just enqueue a new motion event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004421 std::unique_ptr<MotionEntry> newEntry =
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004422 std::make_unique<MotionEntry>(args.id, args.eventTime, args.deviceId, args.source,
4423 args.displayId, policyFlags, args.action,
4424 args.actionButton, args.flags, args.metaState,
4425 args.buttonState, args.classification, args.edgeFlags,
4426 args.xPrecision, args.yPrecision,
4427 args.xCursorPosition, args.yCursorPosition,
Siarhei Vishniakou3218fc02023-06-15 20:41:02 -07004428 args.downTime, args.getPointerCount(),
4429 args.pointerProperties.data(),
4430 args.pointerCoords.data());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004431
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004432 if (args.id != android::os::IInputConstants::INVALID_INPUT_EVENT_ID &&
4433 IdGenerator::getSource(args.id) == IdGenerator::Source::INPUT_READER &&
Siarhei Vishniakou363e7292021-07-09 03:22:42 +00004434 !mInputFilterEnabled) {
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004435 const bool isDown = args.action == AMOTION_EVENT_ACTION_DOWN;
4436 mLatencyTracker.trackListener(args.id, isDown, args.eventTime, args.readTime);
Siarhei Vishniakou363e7292021-07-09 03:22:42 +00004437 }
4438
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004439 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004440 mLock.unlock();
4441 } // release lock
4442
4443 if (needWake) {
4444 mLooper->wake();
4445 }
4446}
4447
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004448void InputDispatcher::notifySensor(const NotifySensorArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004449 if (debugInboundEventDetails()) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004450 ALOGD("notifySensor - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=0x%x, "
4451 " sensorType=%s",
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004452 args.id, args.eventTime, args.deviceId, args.source,
4453 ftl::enum_string(args.sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004454 }
Chris Yef59a2f42020-10-16 12:55:26 -07004455
Antonio Kantekf16f2832021-09-28 04:39:20 +00004456 bool needWake = false;
Chris Yef59a2f42020-10-16 12:55:26 -07004457 { // acquire lock
4458 mLock.lock();
4459
4460 // Just enqueue a new sensor event.
4461 std::unique_ptr<SensorEntry> newEntry =
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004462 std::make_unique<SensorEntry>(args.id, args.eventTime, args.deviceId, args.source,
4463 /* policyFlags=*/0, args.hwTimestamp, args.sensorType,
4464 args.accuracy, args.accuracyChanged, args.values);
Chris Yef59a2f42020-10-16 12:55:26 -07004465
4466 needWake = enqueueInboundEventLocked(std::move(newEntry));
4467 mLock.unlock();
4468 } // release lock
4469
4470 if (needWake) {
4471 mLooper->wake();
4472 }
4473}
4474
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004475void InputDispatcher::notifyVibratorState(const NotifyVibratorStateArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004476 if (debugInboundEventDetails()) {
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004477 ALOGD("notifyVibratorState - eventTime=%" PRId64 ", device=%d, isOn=%d", args.eventTime,
4478 args.deviceId, args.isOn);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004479 }
Prabir Pradhana41d2442023-04-20 21:30:40 +00004480 mPolicy.notifyVibratorState(args.deviceId, args.isOn);
Chris Yefb552902021-02-03 17:18:37 -08004481}
4482
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004483bool InputDispatcher::shouldSendMotionToInputFilterLocked(const NotifyMotionArgs& args) {
Jackal Guof9696682018-10-05 12:23:23 +08004484 return mInputFilterEnabled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004485}
4486
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004487void InputDispatcher::notifySwitch(const NotifySwitchArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004488 if (debugInboundEventDetails()) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004489 ALOGD("notifySwitch - eventTime=%" PRId64 ", policyFlags=0x%x, switchValues=0x%08x, "
4490 "switchMask=0x%08x",
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004491 args.eventTime, args.policyFlags, args.switchValues, args.switchMask);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004492 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004493
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004494 uint32_t policyFlags = args.policyFlags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004495 policyFlags |= POLICY_FLAG_TRUSTED;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004496 mPolicy.notifySwitch(args.eventTime, args.switchValues, args.switchMask, policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004497}
4498
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004499void InputDispatcher::notifyDeviceReset(const NotifyDeviceResetArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004500 if (debugInboundEventDetails()) {
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004501 ALOGD("notifyDeviceReset - eventTime=%" PRId64 ", deviceId=%d", args.eventTime,
4502 args.deviceId);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004503 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004504
Antonio Kantekf16f2832021-09-28 04:39:20 +00004505 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004506 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004507 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004508
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004509 std::unique_ptr<DeviceResetEntry> newEntry =
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004510 std::make_unique<DeviceResetEntry>(args.id, args.eventTime, args.deviceId);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004511 needWake = enqueueInboundEventLocked(std::move(newEntry));
Siarhei Vishniakou1160ecd2023-06-28 15:57:47 -07004512
4513 for (auto& [_, verifier] : mVerifiersByDisplay) {
4514 verifier.resetDevice(args.deviceId);
4515 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004516 } // release lock
4517
4518 if (needWake) {
4519 mLooper->wake();
4520 }
4521}
4522
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004523void InputDispatcher::notifyPointerCaptureChanged(const NotifyPointerCaptureChangedArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004524 if (debugInboundEventDetails()) {
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004525 ALOGD("notifyPointerCaptureChanged - eventTime=%" PRId64 ", enabled=%s", args.eventTime,
4526 args.request.enable ? "true" : "false");
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004527 }
Prabir Pradhan7e186182020-11-10 13:56:45 -08004528
Antonio Kantekf16f2832021-09-28 04:39:20 +00004529 bool needWake = false;
Prabir Pradhan99987712020-11-10 18:43:05 -08004530 { // acquire lock
4531 std::scoped_lock _l(mLock);
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004532 auto entry =
4533 std::make_unique<PointerCaptureChangedEntry>(args.id, args.eventTime, args.request);
Prabir Pradhan99987712020-11-10 18:43:05 -08004534 needWake = enqueueInboundEventLocked(std::move(entry));
4535 } // release lock
4536
4537 if (needWake) {
4538 mLooper->wake();
4539 }
Prabir Pradhan7e186182020-11-10 13:56:45 -08004540}
4541
Prabir Pradhan5735a322022-04-11 17:23:34 +00004542InputEventInjectionResult InputDispatcher::injectInputEvent(const InputEvent* event,
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00004543 std::optional<gui::Uid> targetUid,
Prabir Pradhan5735a322022-04-11 17:23:34 +00004544 InputEventInjectionSync syncMode,
4545 std::chrono::milliseconds timeout,
4546 uint32_t policyFlags) {
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004547 Result<void> eventValidation = validateInputEvent(*event);
4548 if (!eventValidation.ok()) {
4549 LOG(INFO) << "Injection failed: invalid event: " << eventValidation.error();
4550 return InputEventInjectionResult::FAILED;
4551 }
4552
Prabir Pradhan65613802023-02-22 23:36:58 +00004553 if (debugInboundEventDetails()) {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00004554 LOG(DEBUG) << __func__ << ": targetUid=" << toString(targetUid, &uidString)
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004555 << ", syncMode=" << ftl::enum_string(syncMode) << ", timeout=" << timeout.count()
4556 << "ms, policyFlags=0x" << std::hex << policyFlags << std::dec
4557 << ", event=" << *event;
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004558 }
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07004559 nsecs_t endTime = now() + std::chrono::duration_cast<std::chrono::nanoseconds>(timeout).count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004560
Prabir Pradhan5735a322022-04-11 17:23:34 +00004561 policyFlags |= POLICY_FLAG_INJECTED | POLICY_FLAG_TRUSTED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004562
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004563 // For all injected events, set device id = VIRTUAL_KEYBOARD_ID. The only exception is events
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004564 // that have gone through the InputFilter. If the event passed through the InputFilter, assign
4565 // the provided device id. If the InputFilter is accessibility, and it modifies or synthesizes
4566 // the injected event, it is responsible for setting POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY.
4567 // For those events, we will set FLAG_IS_ACCESSIBILITY_EVENT to allow apps to distinguish them
4568 // from events that originate from actual hardware.
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004569 int32_t resolvedDeviceId = VIRTUAL_KEYBOARD_ID;
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004570 if (policyFlags & POLICY_FLAG_FILTERED) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004571 resolvedDeviceId = event->getDeviceId();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004572 }
4573
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004574 std::queue<std::unique_ptr<EventEntry>> injectedEntries;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004575 switch (event->getType()) {
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004576 case InputEventType::KEY: {
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004577 const KeyEvent& incomingKey = static_cast<const KeyEvent&>(*event);
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004578 const int32_t action = incomingKey.getAction();
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004579 int32_t flags = incomingKey.getFlags();
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004580 if (policyFlags & POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY) {
4581 flags |= AKEY_EVENT_FLAG_IS_ACCESSIBILITY_EVENT;
4582 }
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004583 int32_t keyCode = incomingKey.getKeyCode();
4584 int32_t metaState = incomingKey.getMetaState();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004585 accelerateMetaShortcuts(resolvedDeviceId, action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004586 /*byref*/ keyCode, /*byref*/ metaState);
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004587 KeyEvent keyEvent;
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004588 keyEvent.initialize(incomingKey.getId(), resolvedDeviceId, incomingKey.getSource(),
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004589 incomingKey.getDisplayId(), INVALID_HMAC, action, flags, keyCode,
4590 incomingKey.getScanCode(), metaState, incomingKey.getRepeatCount(),
4591 incomingKey.getDownTime(), incomingKey.getEventTime());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004592
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004593 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
4594 policyFlags |= POLICY_FLAG_VIRTUAL;
Michael Wright2b3c3302018-03-02 17:19:13 +00004595 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004596
4597 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
4598 android::base::Timer t;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004599 mPolicy.interceptKeyBeforeQueueing(keyEvent, /*byref*/ policyFlags);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004600 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4601 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
4602 std::to_string(t.duration().count()).c_str());
4603 }
4604 }
4605
4606 mLock.lock();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004607 std::unique_ptr<KeyEntry> injectedEntry =
4608 std::make_unique<KeyEntry>(incomingKey.getId(), incomingKey.getEventTime(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004609 resolvedDeviceId, incomingKey.getSource(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004610 incomingKey.getDisplayId(), policyFlags, action,
4611 flags, keyCode, incomingKey.getScanCode(), metaState,
4612 incomingKey.getRepeatCount(),
4613 incomingKey.getDownTime());
4614 injectedEntries.push(std::move(injectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004615 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004616 }
4617
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004618 case InputEventType::MOTION: {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004619 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(*event);
Prabir Pradhanaa561d12021-09-24 06:57:33 -07004620 const bool isPointerEvent =
4621 isFromSource(event->getSource(), AINPUT_SOURCE_CLASS_POINTER);
4622 // If a pointer event has no displayId specified, inject it to the default display.
4623 const uint32_t displayId = isPointerEvent && (event->getDisplayId() == ADISPLAY_ID_NONE)
4624 ? ADISPLAY_ID_DEFAULT
4625 : event->getDisplayId();
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004626 int32_t flags = motionEvent.getFlags();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004627
4628 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004629 nsecs_t eventTime = motionEvent.getEventTime();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004630 android::base::Timer t;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004631 mPolicy.interceptMotionBeforeQueueing(displayId, eventTime, /*byref*/ policyFlags);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004632 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4633 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
4634 std::to_string(t.duration().count()).c_str());
4635 }
4636 }
4637
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004638 if (policyFlags & POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY) {
4639 flags |= AMOTION_EVENT_FLAG_IS_ACCESSIBILITY_EVENT;
4640 }
4641
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004642 mLock.lock();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004643 const nsecs_t* sampleEventTimes = motionEvent.getSampleEventTimes();
4644 const PointerCoords* samplePointerCoords = motionEvent.getSamplePointerCoords();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004645 std::unique_ptr<MotionEntry> injectedEntry =
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004646 std::make_unique<MotionEntry>(motionEvent.getId(), *sampleEventTimes,
4647 resolvedDeviceId, motionEvent.getSource(),
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004648 displayId, policyFlags, motionEvent.getAction(),
4649 motionEvent.getActionButton(), flags,
4650 motionEvent.getMetaState(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004651 motionEvent.getButtonState(),
4652 motionEvent.getClassification(),
4653 motionEvent.getEdgeFlags(),
4654 motionEvent.getXPrecision(),
4655 motionEvent.getYPrecision(),
4656 motionEvent.getRawXCursorPosition(),
4657 motionEvent.getRawYCursorPosition(),
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004658 motionEvent.getDownTime(),
4659 motionEvent.getPointerCount(),
4660 motionEvent.getPointerProperties(),
4661 samplePointerCoords);
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004662 transformMotionEntryForInjectionLocked(*injectedEntry, motionEvent.getTransform());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004663 injectedEntries.push(std::move(injectedEntry));
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004664 for (size_t i = motionEvent.getHistorySize(); i > 0; i--) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004665 sampleEventTimes += 1;
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004666 samplePointerCoords += motionEvent.getPointerCount();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004667 std::unique_ptr<MotionEntry> nextInjectedEntry =
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004668 std::make_unique<MotionEntry>(motionEvent.getId(), *sampleEventTimes,
4669 resolvedDeviceId, motionEvent.getSource(),
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004670 displayId, policyFlags,
4671 motionEvent.getAction(),
4672 motionEvent.getActionButton(), flags,
4673 motionEvent.getMetaState(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004674 motionEvent.getButtonState(),
4675 motionEvent.getClassification(),
4676 motionEvent.getEdgeFlags(),
4677 motionEvent.getXPrecision(),
4678 motionEvent.getYPrecision(),
4679 motionEvent.getRawXCursorPosition(),
4680 motionEvent.getRawYCursorPosition(),
4681 motionEvent.getDownTime(),
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004682 motionEvent.getPointerCount(),
4683 motionEvent.getPointerProperties(),
Prabir Pradhan5beda762021-12-10 09:30:08 +00004684 samplePointerCoords);
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004685 transformMotionEntryForInjectionLocked(*nextInjectedEntry,
4686 motionEvent.getTransform());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004687 injectedEntries.push(std::move(nextInjectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004688 }
4689 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004690 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004691
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004692 default:
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004693 LOG(WARNING) << "Cannot inject " << ftl::enum_string(event->getType()) << " events";
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004694 return InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004695 }
4696
Prabir Pradhan5735a322022-04-11 17:23:34 +00004697 InjectionState* injectionState = new InjectionState(targetUid);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004698 if (syncMode == InputEventInjectionSync::NONE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004699 injectionState->injectionIsAsync = true;
4700 }
4701
4702 injectionState->refCount += 1;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004703 injectedEntries.back()->injectionState = injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004704
4705 bool needWake = false;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004706 while (!injectedEntries.empty()) {
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08004707 if (DEBUG_INJECTION) {
4708 LOG(DEBUG) << "Injecting " << injectedEntries.front()->getDescription();
4709 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004710 needWake |= enqueueInboundEventLocked(std::move(injectedEntries.front()));
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004711 injectedEntries.pop();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004712 }
4713
4714 mLock.unlock();
4715
4716 if (needWake) {
4717 mLooper->wake();
4718 }
4719
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004720 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004721 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004722 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004723
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004724 if (syncMode == InputEventInjectionSync::NONE) {
4725 injectionResult = InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004726 } else {
4727 for (;;) {
4728 injectionResult = injectionState->injectionResult;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004729 if (injectionResult != InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004730 break;
4731 }
4732
4733 nsecs_t remainingTimeout = endTime - now();
4734 if (remainingTimeout <= 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004735 if (DEBUG_INJECTION) {
4736 ALOGD("injectInputEvent - Timed out waiting for injection result "
4737 "to become available.");
4738 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004739 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004740 break;
4741 }
4742
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004743 mInjectionResultAvailable.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004744 }
4745
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004746 if (injectionResult == InputEventInjectionResult::SUCCEEDED &&
4747 syncMode == InputEventInjectionSync::WAIT_FOR_FINISHED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004748 while (injectionState->pendingForegroundDispatches != 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004749 if (DEBUG_INJECTION) {
4750 ALOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
4751 injectionState->pendingForegroundDispatches);
4752 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004753 nsecs_t remainingTimeout = endTime - now();
4754 if (remainingTimeout <= 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004755 if (DEBUG_INJECTION) {
4756 ALOGD("injectInputEvent - Timed out waiting for pending foreground "
4757 "dispatches to finish.");
4758 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004759 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004760 break;
4761 }
4762
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004763 mInjectionSyncFinished.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004764 }
4765 }
4766 }
4767
4768 injectionState->release();
4769 } // release lock
4770
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004771 if (DEBUG_INJECTION) {
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08004772 LOG(DEBUG) << "injectInputEvent - Finished with result "
4773 << ftl::enum_string(injectionResult);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004774 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004775
4776 return injectionResult;
4777}
4778
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004779std::unique_ptr<VerifiedInputEvent> InputDispatcher::verifyInputEvent(const InputEvent& event) {
Gang Wange9087892020-01-07 12:17:14 -05004780 std::array<uint8_t, 32> calculatedHmac;
4781 std::unique_ptr<VerifiedInputEvent> result;
4782 switch (event.getType()) {
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004783 case InputEventType::KEY: {
Gang Wange9087892020-01-07 12:17:14 -05004784 const KeyEvent& keyEvent = static_cast<const KeyEvent&>(event);
4785 VerifiedKeyEvent verifiedKeyEvent = verifiedKeyEventFromKeyEvent(keyEvent);
4786 result = std::make_unique<VerifiedKeyEvent>(verifiedKeyEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004787 calculatedHmac = sign(verifiedKeyEvent);
Gang Wange9087892020-01-07 12:17:14 -05004788 break;
4789 }
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004790 case InputEventType::MOTION: {
Gang Wange9087892020-01-07 12:17:14 -05004791 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(event);
4792 VerifiedMotionEvent verifiedMotionEvent =
4793 verifiedMotionEventFromMotionEvent(motionEvent);
4794 result = std::make_unique<VerifiedMotionEvent>(verifiedMotionEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004795 calculatedHmac = sign(verifiedMotionEvent);
Gang Wange9087892020-01-07 12:17:14 -05004796 break;
4797 }
4798 default: {
4799 ALOGE("Cannot verify events of type %" PRId32, event.getType());
4800 return nullptr;
4801 }
4802 }
4803 if (calculatedHmac == INVALID_HMAC) {
4804 return nullptr;
4805 }
tyiu1573a672023-02-21 22:38:32 +00004806 if (0 != CRYPTO_memcmp(calculatedHmac.data(), event.getHmac().data(), calculatedHmac.size())) {
Gang Wange9087892020-01-07 12:17:14 -05004807 return nullptr;
4808 }
4809 return result;
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004810}
4811
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004812void InputDispatcher::setInjectionResult(EventEntry& entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004813 InputEventInjectionResult injectionResult) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004814 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004815 if (injectionState) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004816 if (DEBUG_INJECTION) {
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08004817 LOG(DEBUG) << "Setting input event injection result to "
4818 << ftl::enum_string(injectionResult);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004819 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004820
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004821 if (injectionState->injectionIsAsync && !(entry.policyFlags & POLICY_FLAG_FILTERED)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004822 // Log the outcome since the injector did not wait for the injection result.
4823 switch (injectionResult) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004824 case InputEventInjectionResult::SUCCEEDED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004825 ALOGV("Asynchronous input event injection succeeded.");
4826 break;
Prabir Pradhan5735a322022-04-11 17:23:34 +00004827 case InputEventInjectionResult::TARGET_MISMATCH:
4828 ALOGV("Asynchronous input event injection target mismatch.");
4829 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004830 case InputEventInjectionResult::FAILED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004831 ALOGW("Asynchronous input event injection failed.");
4832 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004833 case InputEventInjectionResult::TIMED_OUT:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004834 ALOGW("Asynchronous input event injection timed out.");
4835 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004836 case InputEventInjectionResult::PENDING:
4837 ALOGE("Setting result to 'PENDING' for asynchronous injection");
4838 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004839 }
4840 }
4841
4842 injectionState->injectionResult = injectionResult;
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004843 mInjectionResultAvailable.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004844 }
4845}
4846
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004847void InputDispatcher::transformMotionEntryForInjectionLocked(
4848 MotionEntry& entry, const ui::Transform& injectedTransform) const {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004849 // Input injection works in the logical display coordinate space, but the input pipeline works
4850 // display space, so we need to transform the injected events accordingly.
4851 const auto it = mDisplayInfos.find(entry.displayId);
4852 if (it == mDisplayInfos.end()) return;
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004853 const auto& transformToDisplay = it->second.transform.inverse() * injectedTransform;
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004854
Prabir Pradhand9a2ebe2022-07-20 19:25:13 +00004855 if (entry.xCursorPosition != AMOTION_EVENT_INVALID_CURSOR_POSITION &&
4856 entry.yCursorPosition != AMOTION_EVENT_INVALID_CURSOR_POSITION) {
4857 const vec2 cursor =
4858 MotionEvent::calculateTransformedXY(entry.source, transformToDisplay,
4859 {entry.xCursorPosition, entry.yCursorPosition});
4860 entry.xCursorPosition = cursor.x;
4861 entry.yCursorPosition = cursor.y;
4862 }
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004863 for (uint32_t i = 0; i < entry.pointerCount; i++) {
Prabir Pradhan8e6ce222022-02-24 09:08:54 -08004864 entry.pointerCoords[i] =
4865 MotionEvent::calculateTransformedCoords(entry.source, transformToDisplay,
4866 entry.pointerCoords[i]);
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004867 }
4868}
4869
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004870void InputDispatcher::incrementPendingForegroundDispatches(EventEntry& entry) {
4871 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004872 if (injectionState) {
4873 injectionState->pendingForegroundDispatches += 1;
4874 }
4875}
4876
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004877void InputDispatcher::decrementPendingForegroundDispatches(EventEntry& entry) {
4878 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004879 if (injectionState) {
4880 injectionState->pendingForegroundDispatches -= 1;
4881
4882 if (injectionState->pendingForegroundDispatches == 0) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004883 mInjectionSyncFinished.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004884 }
4885 }
4886}
4887
chaviw98318de2021-05-19 16:45:23 -05004888const std::vector<sp<WindowInfoHandle>>& InputDispatcher::getWindowHandlesLocked(
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004889 int32_t displayId) const {
chaviw98318de2021-05-19 16:45:23 -05004890 static const std::vector<sp<WindowInfoHandle>> EMPTY_WINDOW_HANDLES;
Vishnu Nairad321cd2020-08-20 16:40:21 -07004891 auto it = mWindowHandlesByDisplay.find(displayId);
4892 return it != mWindowHandlesByDisplay.end() ? it->second : EMPTY_WINDOW_HANDLES;
Arthur Hungb92218b2018-08-14 12:00:21 +08004893}
4894
chaviw98318de2021-05-19 16:45:23 -05004895sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(
chaviwfbe5d9c2018-12-26 12:23:37 -08004896 const sp<IBinder>& windowHandleToken) const {
arthurhungbe737672020-06-24 12:29:21 +08004897 if (windowHandleToken == nullptr) {
4898 return nullptr;
4899 }
4900
Arthur Hungb92218b2018-08-14 12:00:21 +08004901 for (auto& it : mWindowHandlesByDisplay) {
chaviw98318de2021-05-19 16:45:23 -05004902 const std::vector<sp<WindowInfoHandle>>& windowHandles = it.second;
4903 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
chaviwfbe5d9c2018-12-26 12:23:37 -08004904 if (windowHandle->getToken() == windowHandleToken) {
Arthur Hungb92218b2018-08-14 12:00:21 +08004905 return windowHandle;
4906 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004907 }
4908 }
Yi Kong9b14ac62018-07-17 13:48:38 -07004909 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004910}
4911
chaviw98318de2021-05-19 16:45:23 -05004912sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(const sp<IBinder>& windowHandleToken,
4913 int displayId) const {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004914 if (windowHandleToken == nullptr) {
4915 return nullptr;
4916 }
4917
chaviw98318de2021-05-19 16:45:23 -05004918 for (const sp<WindowInfoHandle>& windowHandle : getWindowHandlesLocked(displayId)) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004919 if (windowHandle->getToken() == windowHandleToken) {
4920 return windowHandle;
4921 }
4922 }
4923 return nullptr;
4924}
4925
chaviw98318de2021-05-19 16:45:23 -05004926sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(
4927 const sp<WindowInfoHandle>& windowHandle) const {
Mady Mellor017bcd12020-06-23 19:12:00 +00004928 for (auto& it : mWindowHandlesByDisplay) {
chaviw98318de2021-05-19 16:45:23 -05004929 const std::vector<sp<WindowInfoHandle>>& windowHandles = it.second;
4930 for (const sp<WindowInfoHandle>& handle : windowHandles) {
arthurhungbe737672020-06-24 12:29:21 +08004931 if (handle->getId() == windowHandle->getId() &&
4932 handle->getToken() == windowHandle->getToken()) {
Mady Mellor017bcd12020-06-23 19:12:00 +00004933 if (windowHandle->getInfo()->displayId != it.first) {
4934 ALOGE("Found window %s in display %" PRId32
4935 ", but it should belong to display %" PRId32,
4936 windowHandle->getName().c_str(), it.first,
4937 windowHandle->getInfo()->displayId);
4938 }
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004939 return handle;
Arthur Hungb92218b2018-08-14 12:00:21 +08004940 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004941 }
4942 }
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004943 return nullptr;
4944}
4945
chaviw98318de2021-05-19 16:45:23 -05004946sp<WindowInfoHandle> InputDispatcher::getFocusedWindowHandleLocked(int displayId) const {
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004947 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(displayId);
4948 return getWindowHandleLocked(focusedToken, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004949}
4950
Prabir Pradhan33e3baa2022-12-06 20:30:22 +00004951ui::Transform InputDispatcher::getTransformLocked(int32_t displayId) const {
4952 auto displayInfoIt = mDisplayInfos.find(displayId);
4953 return displayInfoIt != mDisplayInfos.end() ? displayInfoIt->second.transform
4954 : kIdentityTransform;
4955}
4956
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004957bool InputDispatcher::canWindowReceiveMotionLocked(const sp<WindowInfoHandle>& window,
4958 const MotionEntry& motionEntry) const {
4959 const WindowInfo& info = *window->getInfo();
4960
4961 // Skip spy window targets that are not valid for targeted injection.
4962 if (const auto err = verifyTargetedInjection(window, motionEntry); err) {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004963 return false;
4964 }
4965
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004966 if (info.inputConfig.test(WindowInfo::InputConfig::PAUSE_DISPATCHING)) {
4967 ALOGI("Not sending touch event to %s because it is paused", window->getName().c_str());
4968 return false;
4969 }
4970
4971 if (info.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL)) {
4972 ALOGW("Not sending touch gesture to %s because it has config NO_INPUT_CHANNEL",
4973 window->getName().c_str());
4974 return false;
4975 }
4976
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07004977 std::shared_ptr<Connection> connection = getConnectionLocked(window->getToken());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004978 if (connection == nullptr) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004979 ALOGW("Not sending touch to %s because there's no corresponding connection",
4980 window->getName().c_str());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004981 return false;
4982 }
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004983
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004984 if (!connection->responsive) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004985 ALOGW("Not sending touch to %s because it is not responsive", window->getName().c_str());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004986 return false;
4987 }
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004988
4989 // Drop events that can't be trusted due to occlusion
4990 const auto [x, y] = resolveTouchedPosition(motionEntry);
4991 TouchOcclusionInfo occlusionInfo = computeTouchOcclusionInfoLocked(window, x, y);
4992 if (!isTouchTrustedLocked(occlusionInfo)) {
4993 if (DEBUG_TOUCH_OCCLUSION) {
Prabir Pradhan82e081e2022-12-06 09:50:09 +00004994 ALOGD("Stack of obscuring windows during untrusted touch (%.1f, %.1f):", x, y);
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004995 for (const auto& log : occlusionInfo.debugInfo) {
4996 ALOGD("%s", log.c_str());
4997 }
4998 }
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00004999 ALOGW("Dropping untrusted touch event due to %s/%s", occlusionInfo.obscuringPackage.c_str(),
5000 occlusionInfo.obscuringUid.toString().c_str());
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07005001 return false;
5002 }
5003
5004 // Drop touch events if requested by input feature
5005 if (shouldDropInput(motionEntry, window)) {
5006 return false;
5007 }
5008
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005009 return true;
5010}
5011
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005012std::shared_ptr<InputChannel> InputDispatcher::getInputChannelLocked(
5013 const sp<IBinder>& token) const {
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005014 auto connectionIt = mConnectionsByToken.find(token);
5015 if (connectionIt == mConnectionsByToken.end()) {
Robert Carr5c8a0262018-10-03 16:30:44 -07005016 return nullptr;
5017 }
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005018 return connectionIt->second->inputChannel;
Robert Carr5c8a0262018-10-03 16:30:44 -07005019}
5020
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005021void InputDispatcher::updateWindowHandlesForDisplayLocked(
chaviw98318de2021-05-19 16:45:23 -05005022 const std::vector<sp<WindowInfoHandle>>& windowInfoHandles, int32_t displayId) {
5023 if (windowInfoHandles.empty()) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005024 // Remove all handles on a display if there are no windows left.
5025 mWindowHandlesByDisplay.erase(displayId);
5026 return;
5027 }
5028
5029 // Since we compare the pointer of input window handles across window updates, we need
5030 // to make sure the handle object for the same window stays unchanged across updates.
chaviw98318de2021-05-19 16:45:23 -05005031 const std::vector<sp<WindowInfoHandle>>& oldHandles = getWindowHandlesLocked(displayId);
5032 std::unordered_map<int32_t /*id*/, sp<WindowInfoHandle>> oldHandlesById;
5033 for (const sp<WindowInfoHandle>& handle : oldHandles) {
chaviwaf87b3e2019-10-01 16:59:28 -07005034 oldHandlesById[handle->getId()] = handle;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005035 }
5036
chaviw98318de2021-05-19 16:45:23 -05005037 std::vector<sp<WindowInfoHandle>> newHandles;
5038 for (const sp<WindowInfoHandle>& handle : windowInfoHandles) {
chaviw98318de2021-05-19 16:45:23 -05005039 const WindowInfo* info = handle->getInfo();
Siarhei Vishniakou64452932020-11-06 17:51:32 -06005040 if (getInputChannelLocked(handle->getToken()) == nullptr) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005041 const bool noInputChannel =
Prabir Pradhan51e7db02022-02-07 06:02:57 -08005042 info->inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005043 const bool canReceiveInput =
5044 !info->inputConfig.test(WindowInfo::InputConfig::NOT_TOUCHABLE) ||
5045 !info->inputConfig.test(WindowInfo::InputConfig::NOT_FOCUSABLE);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005046 if (canReceiveInput && !noInputChannel) {
John Recke0710582019-09-26 13:46:12 -07005047 ALOGV("Window handle %s has no registered input channel",
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005048 handle->getName().c_str());
Robert Carr2984b7a2020-04-13 17:06:45 -07005049 continue;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005050 }
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005051 }
5052
5053 if (info->displayId != displayId) {
5054 ALOGE("Window %s updated by wrong display %d, should belong to display %d",
5055 handle->getName().c_str(), displayId, info->displayId);
5056 continue;
5057 }
5058
Robert Carredd13602020-04-13 17:24:34 -07005059 if ((oldHandlesById.find(handle->getId()) != oldHandlesById.end()) &&
5060 (oldHandlesById.at(handle->getId())->getToken() == handle->getToken())) {
chaviw98318de2021-05-19 16:45:23 -05005061 const sp<WindowInfoHandle>& oldHandle = oldHandlesById.at(handle->getId());
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005062 oldHandle->updateFrom(handle);
5063 newHandles.push_back(oldHandle);
5064 } else {
5065 newHandles.push_back(handle);
5066 }
5067 }
5068
5069 // Insert or replace
5070 mWindowHandlesByDisplay[displayId] = newHandles;
5071}
5072
Arthur Hung72d8dc32020-03-28 00:48:39 +00005073void InputDispatcher::setInputWindows(
chaviw98318de2021-05-19 16:45:23 -05005074 const std::unordered_map<int32_t, std::vector<sp<WindowInfoHandle>>>& handlesPerDisplay) {
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005075 // TODO(b/198444055): Remove setInputWindows from InputDispatcher.
Arthur Hung72d8dc32020-03-28 00:48:39 +00005076 { // acquire lock
5077 std::scoped_lock _l(mLock);
Siarhei Vishniakou2508b872020-12-03 16:33:53 -10005078 for (const auto& [displayId, handles] : handlesPerDisplay) {
5079 setInputWindowsLocked(handles, displayId);
Arthur Hung72d8dc32020-03-28 00:48:39 +00005080 }
5081 }
5082 // Wake up poll loop since it may need to make new input dispatching choices.
5083 mLooper->wake();
5084}
5085
Arthur Hungb92218b2018-08-14 12:00:21 +08005086/**
5087 * Called from InputManagerService, update window handle list by displayId that can receive input.
5088 * A window handle contains information about InputChannel, Touch Region, Types, Focused,...
5089 * If set an empty list, remove all handles from the specific display.
5090 * For focused handle, check if need to change and send a cancel event to previous one.
5091 * For removed handle, check if need to send a cancel event if already in touch.
5092 */
Arthur Hung72d8dc32020-03-28 00:48:39 +00005093void InputDispatcher::setInputWindowsLocked(
chaviw98318de2021-05-19 16:45:23 -05005094 const std::vector<sp<WindowInfoHandle>>& windowInfoHandles, int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005095 if (DEBUG_FOCUS) {
5096 std::string windowList;
chaviw98318de2021-05-19 16:45:23 -05005097 for (const sp<WindowInfoHandle>& iwh : windowInfoHandles) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005098 windowList += iwh->getName() + " ";
5099 }
5100 ALOGD("setInputWindows displayId=%" PRId32 " %s", displayId, windowList.c_str());
5101 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005102
Prabir Pradhand65552b2021-10-07 11:23:50 -07005103 // Check preconditions for new input windows
chaviw98318de2021-05-19 16:45:23 -05005104 for (const sp<WindowInfoHandle>& window : windowInfoHandles) {
Prabir Pradhand65552b2021-10-07 11:23:50 -07005105 const WindowInfo& info = *window->getInfo();
5106
5107 // Ensure all tokens are null if the window has feature NO_INPUT_CHANNEL
Prabir Pradhan51e7db02022-02-07 06:02:57 -08005108 const bool noInputWindow = info.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005109 if (noInputWindow && window->getToken() != nullptr) {
5110 ALOGE("%s has feature NO_INPUT_WINDOW, but a non-null token. Clearing",
5111 window->getName().c_str());
5112 window->releaseChannel();
5113 }
Prabir Pradhand65552b2021-10-07 11:23:50 -07005114
Prabir Pradhan5c85e052021-12-22 02:27:12 -08005115 // Ensure all spy windows are trusted overlays
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005116 LOG_ALWAYS_FATAL_IF(info.isSpy() &&
5117 !info.inputConfig.test(
5118 WindowInfo::InputConfig::TRUSTED_OVERLAY),
Prabir Pradhan5c85e052021-12-22 02:27:12 -08005119 "%s has feature SPY, but is not a trusted overlay.",
5120 window->getName().c_str());
5121
Prabir Pradhand65552b2021-10-07 11:23:50 -07005122 // Ensure all stylus interceptors are trusted overlays
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005123 LOG_ALWAYS_FATAL_IF(info.interceptsStylus() &&
5124 !info.inputConfig.test(
5125 WindowInfo::InputConfig::TRUSTED_OVERLAY),
Prabir Pradhand65552b2021-10-07 11:23:50 -07005126 "%s has feature INTERCEPTS_STYLUS, but is not a trusted overlay.",
5127 window->getName().c_str());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005128 }
5129
Arthur Hung72d8dc32020-03-28 00:48:39 +00005130 // Copy old handles for release if they are no longer present.
chaviw98318de2021-05-19 16:45:23 -05005131 const std::vector<sp<WindowInfoHandle>> oldWindowHandles = getWindowHandlesLocked(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005132
chaviw98318de2021-05-19 16:45:23 -05005133 updateWindowHandlesForDisplayLocked(windowInfoHandles, displayId);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005134
chaviw98318de2021-05-19 16:45:23 -05005135 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Arthur Hung72d8dc32020-03-28 00:48:39 +00005136
Vishnu Nairc519ff72021-01-21 08:23:08 -08005137 std::optional<FocusResolver::FocusChanges> changes =
5138 mFocusResolver.setInputWindows(displayId, windowHandles);
5139 if (changes) {
5140 onFocusChangedLocked(*changes);
Arthur Hung72d8dc32020-03-28 00:48:39 +00005141 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005142
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005143 std::unordered_map<int32_t, TouchState>::iterator stateIt =
5144 mTouchStatesByDisplay.find(displayId);
5145 if (stateIt != mTouchStatesByDisplay.end()) {
5146 TouchState& state = stateIt->second;
Arthur Hung72d8dc32020-03-28 00:48:39 +00005147 for (size_t i = 0; i < state.windows.size();) {
5148 TouchedWindow& touchedWindow = state.windows[i];
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07005149 if (getWindowHandleLocked(touchedWindow.windowHandle) == nullptr) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005150 if (DEBUG_FOCUS) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00005151 ALOGD("Touched window was removed: %s in display %" PRId32,
5152 touchedWindow.windowHandle->getName().c_str(), displayId);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005153 }
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005154 std::shared_ptr<InputChannel> touchedInputChannel =
Arthur Hung72d8dc32020-03-28 00:48:39 +00005155 getInputChannelLocked(touchedWindow.windowHandle->getToken());
5156 if (touchedInputChannel != nullptr) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00005157 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
Arthur Hung72d8dc32020-03-28 00:48:39 +00005158 "touched window was removed");
5159 synthesizeCancelationEventsForInputChannelLocked(touchedInputChannel, options);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00005160 // Since we are about to drop the touch, cancel the events for the wallpaper as
5161 // well.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005162 if (touchedWindow.targetFlags.test(InputTarget::Flags::FOREGROUND) &&
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005163 touchedWindow.windowHandle->getInfo()->inputConfig.test(
5164 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER)) {
Siarhei Vishniakouca205502021-07-16 21:31:58 +00005165 sp<WindowInfoHandle> wallpaper = state.getWallpaperWindow();
Arthur Hungc539dbb2022-12-08 07:45:36 +00005166 synthesizeCancelationEventsForWindowLocked(wallpaper, options);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00005167 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005168 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00005169 state.windows.erase(state.windows.begin() + i);
5170 } else {
5171 ++i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005172 }
5173 }
arthurhungb89ccb02020-12-30 16:19:01 +08005174
arthurhung6d4bed92021-03-17 11:59:33 +08005175 // If drag window is gone, it would receive a cancel event and broadcast the DRAG_END. We
arthurhungb89ccb02020-12-30 16:19:01 +08005176 // could just clear the state here.
Arthur Hung3915c1f2022-05-31 07:17:17 +00005177 if (mDragState && mDragState->dragWindow->getInfo()->displayId == displayId &&
arthurhung6d4bed92021-03-17 11:59:33 +08005178 std::find(windowHandles.begin(), windowHandles.end(), mDragState->dragWindow) ==
arthurhungb89ccb02020-12-30 16:19:01 +08005179 windowHandles.end()) {
Arthur Hung3915c1f2022-05-31 07:17:17 +00005180 ALOGI("Drag window went away: %s", mDragState->dragWindow->getName().c_str());
5181 sendDropWindowCommandLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08005182 mDragState.reset();
arthurhungb89ccb02020-12-30 16:19:01 +08005183 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00005184 }
Arthur Hung25e2af12020-03-26 12:58:37 +00005185
Arthur Hung72d8dc32020-03-28 00:48:39 +00005186 // Release information for windows that are no longer present.
5187 // This ensures that unused input channels are released promptly.
5188 // Otherwise, they might stick around until the window handle is destroyed
5189 // which might not happen until the next GC.
chaviw98318de2021-05-19 16:45:23 -05005190 for (const sp<WindowInfoHandle>& oldWindowHandle : oldWindowHandles) {
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07005191 if (getWindowHandleLocked(oldWindowHandle) == nullptr) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00005192 if (DEBUG_FOCUS) {
5193 ALOGD("Window went away: %s", oldWindowHandle->getName().c_str());
Arthur Hung25e2af12020-03-26 12:58:37 +00005194 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00005195 oldWindowHandle->releaseChannel();
Arthur Hung25e2af12020-03-26 12:58:37 +00005196 }
chaviw291d88a2019-02-14 10:33:58 -08005197 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005198}
5199
5200void InputDispatcher::setFocusedApplication(
Chris Yea209fde2020-07-22 13:54:51 -07005201 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005202 if (DEBUG_FOCUS) {
5203 ALOGD("setFocusedApplication displayId=%" PRId32 " %s", displayId,
5204 inputApplicationHandle ? inputApplicationHandle->getName().c_str() : "<nullptr>");
5205 }
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05005206 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005207 std::scoped_lock _l(mLock);
Vishnu Nair599f1412021-06-21 10:39:58 -07005208 setFocusedApplicationLocked(displayId, inputApplicationHandle);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005209 } // release lock
5210
5211 // Wake up poll loop since it may need to make new input dispatching choices.
5212 mLooper->wake();
5213}
5214
Vishnu Nair599f1412021-06-21 10:39:58 -07005215void InputDispatcher::setFocusedApplicationLocked(
5216 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
5217 std::shared_ptr<InputApplicationHandle> oldFocusedApplicationHandle =
5218 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
5219
5220 if (sharedPointersEqual(oldFocusedApplicationHandle, inputApplicationHandle)) {
5221 return; // This application is already focused. No need to wake up or change anything.
5222 }
5223
5224 // Set the new application handle.
5225 if (inputApplicationHandle != nullptr) {
5226 mFocusedApplicationHandlesByDisplay[displayId] = inputApplicationHandle;
5227 } else {
5228 mFocusedApplicationHandlesByDisplay.erase(displayId);
5229 }
5230
5231 // No matter what the old focused application was, stop waiting on it because it is
5232 // no longer focused.
5233 resetNoFocusedWindowTimeoutLocked();
5234}
5235
Tiger Huang721e26f2018-07-24 22:26:19 +08005236/**
5237 * Sets the focused display, which is responsible for receiving focus-dispatched input events where
5238 * the display not specified.
5239 *
5240 * We track any unreleased events for each window. If a window loses the ability to receive the
5241 * released event, we will send a cancel event to it. So when the focused display is changed, we
5242 * cancel all the unreleased display-unspecified events for the focused window on the old focused
5243 * display. The display-specified events won't be affected.
5244 */
5245void InputDispatcher::setFocusedDisplay(int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005246 if (DEBUG_FOCUS) {
5247 ALOGD("setFocusedDisplay displayId=%" PRId32, displayId);
5248 }
Tiger Huang721e26f2018-07-24 22:26:19 +08005249 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005250 std::scoped_lock _l(mLock);
Tiger Huang721e26f2018-07-24 22:26:19 +08005251
5252 if (mFocusedDisplayId != displayId) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07005253 sp<IBinder> oldFocusedWindowToken =
Vishnu Nairc519ff72021-01-21 08:23:08 -08005254 mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07005255 if (oldFocusedWindowToken != nullptr) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005256 std::shared_ptr<InputChannel> inputChannel =
Vishnu Nairad321cd2020-08-20 16:40:21 -07005257 getInputChannelLocked(oldFocusedWindowToken);
Tiger Huang721e26f2018-07-24 22:26:19 +08005258 if (inputChannel != nullptr) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005259 CancelationOptions
Michael Wrightfb04fd52022-11-24 22:31:11 +00005260 options(CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005261 "The display which contains this window no longer has focus.");
Michael Wright3dd60e22019-03-27 22:06:44 +00005262 options.displayId = ADISPLAY_ID_NONE;
Tiger Huang721e26f2018-07-24 22:26:19 +08005263 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
5264 }
5265 }
5266 mFocusedDisplayId = displayId;
5267
Chris Ye3c2d6f52020-08-09 10:39:48 -07005268 // Find new focused window and validate
Vishnu Nairc519ff72021-01-21 08:23:08 -08005269 sp<IBinder> newFocusedWindowToken = mFocusResolver.getFocusedWindowToken(displayId);
Prabir Pradhancef936d2021-07-21 16:17:52 +00005270 sendFocusChangedCommandLocked(oldFocusedWindowToken, newFocusedWindowToken);
Robert Carrf759f162018-11-13 12:57:11 -08005271
Vishnu Nairad321cd2020-08-20 16:40:21 -07005272 if (newFocusedWindowToken == nullptr) {
Tiger Huang721e26f2018-07-24 22:26:19 +08005273 ALOGW("Focused display #%" PRId32 " does not have a focused window.", displayId);
Vishnu Nairc519ff72021-01-21 08:23:08 -08005274 if (mFocusResolver.hasFocusedWindowTokens()) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07005275 ALOGE("But another display has a focused window\n%s",
Vishnu Nairc519ff72021-01-21 08:23:08 -08005276 mFocusResolver.dumpFocusedWindows().c_str());
Tiger Huang721e26f2018-07-24 22:26:19 +08005277 }
5278 }
5279 }
Tiger Huang721e26f2018-07-24 22:26:19 +08005280 } // release lock
5281
5282 // Wake up poll loop since it may need to make new input dispatching choices.
5283 mLooper->wake();
5284}
5285
Michael Wrightd02c5b62014-02-10 15:10:22 -08005286void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005287 if (DEBUG_FOCUS) {
5288 ALOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
5289 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005290
5291 bool changed;
5292 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005293 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005294
5295 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
5296 if (mDispatchFrozen && !frozen) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005297 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005298 }
5299
5300 if (mDispatchEnabled && !enabled) {
5301 resetAndDropEverythingLocked("dispatcher is being disabled");
5302 }
5303
5304 mDispatchEnabled = enabled;
5305 mDispatchFrozen = frozen;
5306 changed = true;
5307 } else {
5308 changed = false;
5309 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005310 } // release lock
5311
5312 if (changed) {
5313 // Wake up poll loop since it may need to make new input dispatching choices.
5314 mLooper->wake();
5315 }
5316}
5317
5318void InputDispatcher::setInputFilterEnabled(bool enabled) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005319 if (DEBUG_FOCUS) {
5320 ALOGD("setInputFilterEnabled: enabled=%d", enabled);
5321 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005322
5323 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005324 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005325
5326 if (mInputFilterEnabled == enabled) {
5327 return;
5328 }
5329
5330 mInputFilterEnabled = enabled;
5331 resetAndDropEverythingLocked("input filter is being enabled or disabled");
5332 } // release lock
5333
5334 // Wake up poll loop since there might be work to do to drop everything.
5335 mLooper->wake();
5336}
5337
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005338bool InputDispatcher::setInTouchMode(bool inTouchMode, gui::Pid pid, gui::Uid uid,
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00005339 bool hasPermission, int32_t displayId) {
Antonio Kantekf16f2832021-09-28 04:39:20 +00005340 bool needWake = false;
5341 {
5342 std::scoped_lock lock(mLock);
Antonio Kantek15beb512022-06-13 22:35:41 +00005343 ALOGD_IF(DEBUG_TOUCH_MODE,
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005344 "Request to change touch mode to %s (calling pid=%s, uid=%s, "
Antonio Kantek15beb512022-06-13 22:35:41 +00005345 "hasPermission=%s, target displayId=%d, mTouchModePerDisplay[displayId]=%s)",
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005346 toString(inTouchMode), pid.toString().c_str(), uid.toString().c_str(),
5347 toString(hasPermission), displayId,
Antonio Kantek15beb512022-06-13 22:35:41 +00005348 mTouchModePerDisplay.count(displayId) == 0
5349 ? "not set"
5350 : std::to_string(mTouchModePerDisplay[displayId]).c_str());
5351
Antonio Kantek15beb512022-06-13 22:35:41 +00005352 auto touchModeIt = mTouchModePerDisplay.find(displayId);
5353 if (touchModeIt != mTouchModePerDisplay.end() && touchModeIt->second == inTouchMode) {
Antonio Kantekea47acb2021-12-23 12:41:25 -08005354 return false;
Antonio Kantekf16f2832021-09-28 04:39:20 +00005355 }
Antonio Kantekea47acb2021-12-23 12:41:25 -08005356 if (!hasPermission) {
Antonio Kantek48710e42022-03-24 14:19:30 -07005357 if (!focusedWindowIsOwnedByLocked(pid, uid) &&
5358 !recentWindowsAreOwnedByLocked(pid, uid)) {
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005359 ALOGD("Touch mode switch rejected, caller (pid=%s, uid=%s) doesn't own the focused "
Antonio Kantek48710e42022-03-24 14:19:30 -07005360 "window nor none of the previously interacted window",
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005361 pid.toString().c_str(), uid.toString().c_str());
Antonio Kantekea47acb2021-12-23 12:41:25 -08005362 return false;
5363 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00005364 }
Antonio Kantek15beb512022-06-13 22:35:41 +00005365 mTouchModePerDisplay[displayId] = inTouchMode;
5366 auto entry = std::make_unique<TouchModeEntry>(mIdGenerator.nextId(), now(), inTouchMode,
5367 displayId);
Antonio Kantekf16f2832021-09-28 04:39:20 +00005368 needWake = enqueueInboundEventLocked(std::move(entry));
5369 } // release lock
5370
5371 if (needWake) {
5372 mLooper->wake();
5373 }
Antonio Kantekea47acb2021-12-23 12:41:25 -08005374 return true;
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -08005375}
5376
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005377bool InputDispatcher::focusedWindowIsOwnedByLocked(gui::Pid pid, gui::Uid uid) {
Antonio Kantek48710e42022-03-24 14:19:30 -07005378 const sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
5379 if (focusedToken == nullptr) {
5380 return false;
5381 }
5382 sp<WindowInfoHandle> windowHandle = getWindowHandleLocked(focusedToken);
5383 return isWindowOwnedBy(windowHandle, pid, uid);
5384}
5385
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005386bool InputDispatcher::recentWindowsAreOwnedByLocked(gui::Pid pid, gui::Uid uid) {
Antonio Kantek48710e42022-03-24 14:19:30 -07005387 return std::find_if(mInteractionConnectionTokens.begin(), mInteractionConnectionTokens.end(),
5388 [&](const sp<IBinder>& connectionToken) REQUIRES(mLock) {
5389 const sp<WindowInfoHandle> windowHandle =
5390 getWindowHandleLocked(connectionToken);
5391 return isWindowOwnedBy(windowHandle, pid, uid);
5392 }) != mInteractionConnectionTokens.end();
5393}
5394
Bernardo Rufinoea97d182020-08-19 14:43:14 +01005395void InputDispatcher::setMaximumObscuringOpacityForTouch(float opacity) {
5396 if (opacity < 0 || opacity > 1) {
5397 LOG_ALWAYS_FATAL("Maximum obscuring opacity for touch should be >= 0 and <= 1");
5398 return;
5399 }
5400
5401 std::scoped_lock lock(mLock);
5402 mMaximumObscuringOpacityForTouch = opacity;
5403}
5404
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005405std::tuple<TouchState*, TouchedWindow*, int32_t /*displayId*/>
5406InputDispatcher::findTouchStateWindowAndDisplayLocked(const sp<IBinder>& token) {
Arthur Hungabbb9d82021-09-01 14:52:30 +00005407 for (auto& [displayId, state] : mTouchStatesByDisplay) {
5408 for (TouchedWindow& w : state.windows) {
5409 if (w.windowHandle->getToken() == token) {
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005410 return std::make_tuple(&state, &w, displayId);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005411 }
5412 }
5413 }
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005414 return std::make_tuple(nullptr, nullptr, ADISPLAY_ID_DEFAULT);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005415}
5416
arthurhungb89ccb02020-12-30 16:19:01 +08005417bool InputDispatcher::transferTouchFocus(const sp<IBinder>& fromToken, const sp<IBinder>& toToken,
5418 bool isDragDrop) {
chaviwfbe5d9c2018-12-26 12:23:37 -08005419 if (fromToken == toToken) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005420 if (DEBUG_FOCUS) {
5421 ALOGD("Trivial transfer to same window.");
5422 }
chaviwfbe5d9c2018-12-26 12:23:37 -08005423 return true;
5424 }
5425
Michael Wrightd02c5b62014-02-10 15:10:22 -08005426 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005427 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005428
Arthur Hungabbb9d82021-09-01 14:52:30 +00005429 // Find the target touch state and touched window by fromToken.
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005430 auto [state, touchedWindow, displayId] = findTouchStateWindowAndDisplayLocked(fromToken);
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005431
Arthur Hungabbb9d82021-09-01 14:52:30 +00005432 if (state == nullptr || touchedWindow == nullptr) {
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005433 ALOGD("Touch transfer failed because from window is not being touched.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005434 return false;
5435 }
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005436 std::set<int32_t> deviceIds = touchedWindow->getTouchingDeviceIds();
5437 if (deviceIds.size() != 1) {
5438 LOG(DEBUG) << "Can't transfer touch. Currently touching devices: " << dumpSet(deviceIds)
5439 << " for window: " << touchedWindow->dump();
5440 return false;
5441 }
5442 const int32_t deviceId = *deviceIds.begin();
Arthur Hungabbb9d82021-09-01 14:52:30 +00005443
Arthur Hungabbb9d82021-09-01 14:52:30 +00005444 sp<WindowInfoHandle> toWindowHandle = getWindowHandleLocked(toToken, displayId);
5445 if (toWindowHandle == nullptr) {
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005446 ALOGW("Cannot transfer touch because to window not found.");
Arthur Hungabbb9d82021-09-01 14:52:30 +00005447 return false;
5448 }
5449
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005450 if (DEBUG_FOCUS) {
5451 ALOGD("transferTouchFocus: fromWindowHandle=%s, toWindowHandle=%s",
Arthur Hungabbb9d82021-09-01 14:52:30 +00005452 touchedWindow->windowHandle->getName().c_str(),
5453 toWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005454 }
5455
Arthur Hungabbb9d82021-09-01 14:52:30 +00005456 // Erase old window.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005457 ftl::Flags<InputTarget::Flags> oldTargetFlags = touchedWindow->targetFlags;
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005458 std::bitset<MAX_POINTER_ID + 1> pointerIds = touchedWindow->getTouchingPointers(deviceId);
Arthur Hungc539dbb2022-12-08 07:45:36 +00005459 sp<WindowInfoHandle> fromWindowHandle = touchedWindow->windowHandle;
Arthur Hungabbb9d82021-09-01 14:52:30 +00005460 state->removeWindowByToken(fromToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005461
Arthur Hungabbb9d82021-09-01 14:52:30 +00005462 // Add new window.
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00005463 nsecs_t downTimeInTarget = now();
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005464 ftl::Flags<InputTarget::Flags> newTargetFlags =
5465 oldTargetFlags & (InputTarget::Flags::SPLIT | InputTarget::Flags::DISPATCH_AS_IS);
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00005466 if (canReceiveForegroundTouches(*toWindowHandle->getInfo())) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005467 newTargetFlags |= InputTarget::Flags::FOREGROUND;
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00005468 }
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005469 state->addOrUpdateWindow(toWindowHandle, newTargetFlags, deviceId, pointerIds,
5470 downTimeInTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005471
Arthur Hungabbb9d82021-09-01 14:52:30 +00005472 // Store the dragging window.
5473 if (isDragDrop) {
Arthur Hungb75c2aa2022-07-15 09:35:36 +00005474 if (pointerIds.count() != 1) {
5475 ALOGW("The drag and drop cannot be started when there is no pointer or more than 1"
5476 " pointer on the window.");
Arthur Hung54745652022-04-20 07:17:41 +00005477 return false;
5478 }
Arthur Hungb75c2aa2022-07-15 09:35:36 +00005479 // Track the pointer id for drag window and generate the drag state.
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08005480 const size_t id = firstMarkedBit(pointerIds);
Arthur Hung54745652022-04-20 07:17:41 +00005481 mDragState = std::make_unique<DragState>(toWindowHandle, id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005482 }
5483
Arthur Hungabbb9d82021-09-01 14:52:30 +00005484 // Synthesize cancel for old window and down for new window.
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07005485 std::shared_ptr<Connection> fromConnection = getConnectionLocked(fromToken);
5486 std::shared_ptr<Connection> toConnection = getConnectionLocked(toToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005487 if (fromConnection != nullptr && toConnection != nullptr) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08005488 fromConnection->inputState.mergePointerStateTo(toConnection->inputState);
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005489 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
5490 "transferring touch from this window to another window");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005491 synthesizeCancelationEventsForConnectionLocked(fromConnection, options);
Arthur Hungc539dbb2022-12-08 07:45:36 +00005492 synthesizePointerDownEventsForConnectionLocked(downTimeInTarget, toConnection,
5493 newTargetFlags);
5494
5495 // Check if the wallpaper window should deliver the corresponding event.
5496 transferWallpaperTouch(oldTargetFlags, newTargetFlags, fromWindowHandle, toWindowHandle,
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005497 *state, deviceId, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005498 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005499 } // release lock
5500
5501 // Wake up poll loop since it may need to make new input dispatching choices.
5502 mLooper->wake();
5503 return true;
5504}
5505
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005506/**
5507 * Get the touched foreground window on the given display.
5508 * Return null if there are no windows touched on that display, or if more than one foreground
5509 * window is being touched.
5510 */
5511sp<WindowInfoHandle> InputDispatcher::findTouchedForegroundWindowLocked(int32_t displayId) const {
5512 auto stateIt = mTouchStatesByDisplay.find(displayId);
5513 if (stateIt == mTouchStatesByDisplay.end()) {
5514 ALOGI("No touch state on display %" PRId32, displayId);
5515 return nullptr;
5516 }
5517
5518 const TouchState& state = stateIt->second;
5519 sp<WindowInfoHandle> touchedForegroundWindow;
5520 // If multiple foreground windows are touched, return nullptr
5521 for (const TouchedWindow& window : state.windows) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005522 if (window.targetFlags.test(InputTarget::Flags::FOREGROUND)) {
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005523 if (touchedForegroundWindow != nullptr) {
5524 ALOGI("Two or more foreground windows: %s and %s",
5525 touchedForegroundWindow->getName().c_str(),
5526 window.windowHandle->getName().c_str());
5527 return nullptr;
5528 }
5529 touchedForegroundWindow = window.windowHandle;
5530 }
5531 }
5532 return touchedForegroundWindow;
5533}
5534
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005535// Binder call
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005536bool InputDispatcher::transferTouch(const sp<IBinder>& destChannelToken, int32_t displayId) {
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005537 sp<IBinder> fromToken;
5538 { // acquire lock
5539 std::scoped_lock _l(mLock);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005540 sp<WindowInfoHandle> toWindowHandle = getWindowHandleLocked(destChannelToken, displayId);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005541 if (toWindowHandle == nullptr) {
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005542 ALOGW("Could not find window associated with token=%p on display %" PRId32,
5543 destChannelToken.get(), displayId);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005544 return false;
5545 }
5546
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005547 sp<WindowInfoHandle> from = findTouchedForegroundWindowLocked(displayId);
5548 if (from == nullptr) {
5549 ALOGE("Could not find a source window in %s for %p", __func__, destChannelToken.get());
5550 return false;
5551 }
5552
5553 fromToken = from->getToken();
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005554 } // release lock
5555
5556 return transferTouchFocus(fromToken, destChannelToken);
5557}
5558
Michael Wrightd02c5b62014-02-10 15:10:22 -08005559void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005560 if (DEBUG_FOCUS) {
5561 ALOGD("Resetting and dropping all events (%s).", reason);
5562 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005563
Michael Wrightfb04fd52022-11-24 22:31:11 +00005564 CancelationOptions options(CancelationOptions::Mode::CANCEL_ALL_EVENTS, reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005565 synthesizeCancelationEventsForAllConnectionsLocked(options);
5566
5567 resetKeyRepeatLocked();
5568 releasePendingEventLocked();
5569 drainInboundQueueLocked();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005570 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005571
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005572 mAnrTracker.clear();
Jeff Brownf086ddb2014-02-11 14:28:48 -08005573 mTouchStatesByDisplay.clear();
Michael Wright78f24442014-08-06 15:55:28 -07005574 mReplacedKeys.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005575}
5576
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005577void InputDispatcher::logDispatchStateLocked() const {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005578 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005579 dumpDispatchStateLocked(dump);
5580
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005581 std::istringstream stream(dump);
5582 std::string line;
5583
5584 while (std::getline(stream, line, '\n')) {
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07005585 ALOGI("%s", line.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005586 }
5587}
5588
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005589std::string InputDispatcher::dumpPointerCaptureStateLocked() const {
Prabir Pradhan99987712020-11-10 18:43:05 -08005590 std::string dump;
5591
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005592 dump += StringPrintf(INDENT "Pointer Capture Requested: %s\n",
5593 toString(mCurrentPointerCaptureRequest.enable));
Prabir Pradhan99987712020-11-10 18:43:05 -08005594
5595 std::string windowName = "None";
5596 if (mWindowTokenWithPointerCapture) {
chaviw98318de2021-05-19 16:45:23 -05005597 const sp<WindowInfoHandle> captureWindowHandle =
Prabir Pradhan99987712020-11-10 18:43:05 -08005598 getWindowHandleLocked(mWindowTokenWithPointerCapture);
5599 windowName = captureWindowHandle ? captureWindowHandle->getName().c_str()
5600 : "token has capture without window";
5601 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005602 dump += StringPrintf(INDENT "Current Window with Pointer Capture: %s\n", windowName.c_str());
Prabir Pradhan99987712020-11-10 18:43:05 -08005603
5604 return dump;
5605}
5606
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005607void InputDispatcher::dumpDispatchStateLocked(std::string& dump) const {
Siarhei Vishniakou043a3ec2019-05-01 11:30:46 -07005608 dump += StringPrintf(INDENT "DispatchEnabled: %s\n", toString(mDispatchEnabled));
5609 dump += StringPrintf(INDENT "DispatchFrozen: %s\n", toString(mDispatchFrozen));
5610 dump += StringPrintf(INDENT "InputFilterEnabled: %s\n", toString(mInputFilterEnabled));
Tiger Huang721e26f2018-07-24 22:26:19 +08005611 dump += StringPrintf(INDENT "FocusedDisplayId: %" PRId32 "\n", mFocusedDisplayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005612
Tiger Huang721e26f2018-07-24 22:26:19 +08005613 if (!mFocusedApplicationHandlesByDisplay.empty()) {
5614 dump += StringPrintf(INDENT "FocusedApplications:\n");
5615 for (auto& it : mFocusedApplicationHandlesByDisplay) {
5616 const int32_t displayId = it.first;
Chris Yea209fde2020-07-22 13:54:51 -07005617 const std::shared_ptr<InputApplicationHandle>& applicationHandle = it.second;
Siarhei Vishniakou70622952020-07-30 11:17:23 -05005618 const std::chrono::duration timeout =
5619 applicationHandle->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005620 dump += StringPrintf(INDENT2 "displayId=%" PRId32
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005621 ", name='%s', dispatchingTimeout=%" PRId64 "ms\n",
Siarhei Vishniakou70622952020-07-30 11:17:23 -05005622 displayId, applicationHandle->getName().c_str(), millis(timeout));
Tiger Huang721e26f2018-07-24 22:26:19 +08005623 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005624 } else {
Tiger Huang721e26f2018-07-24 22:26:19 +08005625 dump += StringPrintf(INDENT "FocusedApplications: <none>\n");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005626 }
Tiger Huang721e26f2018-07-24 22:26:19 +08005627
Vishnu Nairc519ff72021-01-21 08:23:08 -08005628 dump += mFocusResolver.dump();
Prabir Pradhan99987712020-11-10 18:43:05 -08005629 dump += dumpPointerCaptureStateLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005630
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005631 if (!mTouchStatesByDisplay.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005632 dump += StringPrintf(INDENT "TouchStatesByDisplay:\n");
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005633 for (const auto& [displayId, state] : mTouchStatesByDisplay) {
Siarhei Vishniakou6e1e9872022-11-08 17:51:35 -08005634 std::string touchStateDump = addLinePrefix(state.dump(), INDENT2);
5635 dump += INDENT2 + std::to_string(displayId) + " : " + touchStateDump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005636 }
5637 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005638 dump += INDENT "TouchStates: <no displays touched>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005639 }
5640
arthurhung6d4bed92021-03-17 11:59:33 +08005641 if (mDragState) {
5642 dump += StringPrintf(INDENT "DragState:\n");
5643 mDragState->dump(dump, INDENT2);
5644 }
5645
Arthur Hungb92218b2018-08-14 12:00:21 +08005646 if (!mWindowHandlesByDisplay.empty()) {
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005647 for (const auto& [displayId, windowHandles] : mWindowHandlesByDisplay) {
5648 dump += StringPrintf(INDENT "Display: %" PRId32 "\n", displayId);
5649 if (const auto& it = mDisplayInfos.find(displayId); it != mDisplayInfos.end()) {
5650 const auto& displayInfo = it->second;
5651 dump += StringPrintf(INDENT2 "logicalSize=%dx%d\n", displayInfo.logicalWidth,
5652 displayInfo.logicalHeight);
5653 displayInfo.transform.dump(dump, "transform", INDENT4);
5654 } else {
5655 dump += INDENT2 "No DisplayInfo found!\n";
5656 }
5657
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08005658 if (!windowHandles.empty()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08005659 dump += INDENT2 "Windows:\n";
5660 for (size_t i = 0; i < windowHandles.size(); i++) {
chaviw98318de2021-05-19 16:45:23 -05005661 const sp<WindowInfoHandle>& windowHandle = windowHandles[i];
5662 const WindowInfo* windowInfo = windowHandle->getInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005663
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00005664 dump += StringPrintf(INDENT3 "%zu: name='%s', id=%" PRId32 ", displayId=%d, "
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005665 "inputConfig=%s, alpha=%.2f, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005666 "frame=[%d,%d][%d,%d], globalScale=%f, "
Bernardo Rufino49d99e42021-01-18 15:16:59 +00005667 "applicationInfo.name=%s, "
5668 "applicationInfo.token=%s, "
chaviw1ff3d1e2020-07-01 15:53:47 -07005669 "touchableRegion=",
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00005670 i, windowInfo->name.c_str(), windowInfo->id,
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005671 windowInfo->displayId,
5672 windowInfo->inputConfig.string().c_str(),
5673 windowInfo->alpha, windowInfo->frameLeft,
5674 windowInfo->frameTop, windowInfo->frameRight,
5675 windowInfo->frameBottom, windowInfo->globalScaleFactor,
Bernardo Rufino49d99e42021-01-18 15:16:59 +00005676 windowInfo->applicationInfo.name.c_str(),
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07005677 binderToString(windowInfo->applicationInfo.token).c_str());
Bernardo Rufino53fc31e2020-11-03 11:01:07 +00005678 dump += dumpRegion(windowInfo->touchableRegion);
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005679 dump += StringPrintf(", ownerPid=%s, ownerUid=%s, dispatchingTimeout=%" PRId64
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005680 "ms, hasToken=%s, "
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005681 "touchOcclusionMode=%s\n",
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005682 windowInfo->ownerPid.toString().c_str(),
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00005683 windowInfo->ownerUid.toString().c_str(),
Bernardo Rufinoc2f1fad2020-11-04 17:30:57 +00005684 millis(windowInfo->dispatchingTimeout),
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07005685 binderToString(windowInfo->token).c_str(),
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005686 toString(windowInfo->touchOcclusionMode).c_str());
chaviw85b44202020-07-24 11:46:21 -07005687 windowInfo->transform.dump(dump, "transform", INDENT4);
Arthur Hungb92218b2018-08-14 12:00:21 +08005688 }
5689 } else {
5690 dump += INDENT2 "Windows: <none>\n";
5691 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005692 }
5693 } else {
Arthur Hungb92218b2018-08-14 12:00:21 +08005694 dump += INDENT "Displays: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005695 }
5696
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005697 if (!mGlobalMonitorsByDisplay.empty()) {
5698 for (const auto& [displayId, monitors] : mGlobalMonitorsByDisplay) {
5699 dump += StringPrintf(INDENT "Global monitors on display %d:\n", displayId);
Michael Wright3dd60e22019-03-27 22:06:44 +00005700 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005701 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005702 } else {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005703 dump += INDENT "Global Monitors: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005704 }
5705
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005706 const nsecs_t currentTime = now();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005707
5708 // Dump recently dispatched or dropped events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005709 if (!mRecentQueue.empty()) {
5710 dump += StringPrintf(INDENT "RecentQueue: length=%zu\n", mRecentQueue.size());
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005711 for (const std::shared_ptr<EventEntry>& entry : mRecentQueue) {
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 "RecentQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005718 }
5719
5720 // Dump event currently being dispatched.
5721 if (mPendingEvent) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005722 dump += INDENT "PendingEvent:\n";
5723 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005724 dump += mPendingEvent->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005725 dump += StringPrintf(", age=%" PRId64 "ms\n",
5726 ns2ms(currentTime - mPendingEvent->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005727 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005728 dump += INDENT "PendingEvent: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005729 }
5730
5731 // Dump inbound events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005732 if (!mInboundQueue.empty()) {
5733 dump += StringPrintf(INDENT "InboundQueue: length=%zu\n", mInboundQueue.size());
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005734 for (const std::shared_ptr<EventEntry>& entry : mInboundQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005735 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005736 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005737 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005738 }
5739 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005740 dump += INDENT "InboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005741 }
5742
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005743 if (!mReplacedKeys.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005744 dump += INDENT "ReplacedKeys:\n";
Michael Wright3cec4462022-11-24 22:05:46 +00005745 for (const auto& [replacement, newKeyCode] : mReplacedKeys) {
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005746 dump += StringPrintf(INDENT2 "originalKeyCode=%d, deviceId=%d -> newKeyCode=%d\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005747 replacement.keyCode, replacement.deviceId, newKeyCode);
Michael Wright78f24442014-08-06 15:55:28 -07005748 }
5749 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005750 dump += INDENT "ReplacedKeys: <empty>\n";
Michael Wright78f24442014-08-06 15:55:28 -07005751 }
5752
Prabir Pradhancef936d2021-07-21 16:17:52 +00005753 if (!mCommandQueue.empty()) {
5754 dump += StringPrintf(INDENT "CommandQueue: size=%zu\n", mCommandQueue.size());
5755 } else {
5756 dump += INDENT "CommandQueue: <empty>\n";
5757 }
5758
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005759 if (!mConnectionsByToken.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005760 dump += INDENT "Connections:\n";
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005761 for (const auto& [token, connection] : mConnectionsByToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005762 dump += StringPrintf(INDENT2 "%i: channelName='%s', windowName='%s', "
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005763 "status=%s, monitor=%s, responsive=%s\n",
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005764 connection->inputChannel->getFd().get(),
5765 connection->getInputChannelName().c_str(),
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08005766 connection->getWindowName().c_str(),
5767 ftl::enum_string(connection->status).c_str(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005768 toString(connection->monitor), toString(connection->responsive));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005769
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005770 if (!connection->outboundQueue.empty()) {
5771 dump += StringPrintf(INDENT3 "OutboundQueue: length=%zu\n",
5772 connection->outboundQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005773 dump += dumpQueue(connection->outboundQueue, currentTime);
5774
Michael Wrightd02c5b62014-02-10 15:10:22 -08005775 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005776 dump += INDENT3 "OutboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005777 }
5778
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005779 if (!connection->waitQueue.empty()) {
5780 dump += StringPrintf(INDENT3 "WaitQueue: length=%zu\n",
5781 connection->waitQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005782 dump += dumpQueue(connection->waitQueue, currentTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005783 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005784 dump += INDENT3 "WaitQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005785 }
Siarhei Vishniakoud38a1e02023-07-18 11:55:17 -07005786 std::stringstream inputStateDump;
5787 inputStateDump << connection->inputState;
5788 if (!isEmpty(inputStateDump)) {
5789 dump += INDENT3 "InputState: ";
5790 dump += inputStateDump.str() + "\n";
5791 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005792 }
5793 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005794 dump += INDENT "Connections: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005795 }
5796
5797 if (isAppSwitchPendingLocked()) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005798 dump += StringPrintf(INDENT "AppSwitch: pending, due in %" PRId64 "ms\n",
5799 ns2ms(mAppSwitchDueTime - now()));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005800 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005801 dump += INDENT "AppSwitch: not pending\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005802 }
5803
Antonio Kantek15beb512022-06-13 22:35:41 +00005804 if (!mTouchModePerDisplay.empty()) {
5805 dump += INDENT "TouchModePerDisplay:\n";
5806 for (const auto& [displayId, touchMode] : mTouchModePerDisplay) {
5807 dump += StringPrintf(INDENT2 "Display: %" PRId32 " TouchMode: %s\n", displayId,
5808 std::to_string(touchMode).c_str());
5809 }
5810 } else {
5811 dump += INDENT "TouchModePerDisplay: <none>\n";
5812 }
5813
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005814 dump += INDENT "Configuration:\n";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005815 dump += StringPrintf(INDENT2 "KeyRepeatDelay: %" PRId64 "ms\n", ns2ms(mConfig.keyRepeatDelay));
5816 dump += StringPrintf(INDENT2 "KeyRepeatTimeout: %" PRId64 "ms\n",
5817 ns2ms(mConfig.keyRepeatTimeout));
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00005818 dump += mLatencyTracker.dump(INDENT2);
Siarhei Vishniakoua04181f2021-03-26 05:56:49 +00005819 dump += mLatencyAggregator.dump(INDENT2);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005820}
5821
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005822void InputDispatcher::dumpMonitors(std::string& dump, const std::vector<Monitor>& monitors) const {
Michael Wright3dd60e22019-03-27 22:06:44 +00005823 const size_t numMonitors = monitors.size();
5824 for (size_t i = 0; i < numMonitors; i++) {
5825 const Monitor& monitor = monitors[i];
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005826 const std::shared_ptr<InputChannel>& channel = monitor.inputChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005827 dump += StringPrintf(INDENT2 "%zu: '%s', ", i, channel->getName().c_str());
5828 dump += "\n";
5829 }
5830}
5831
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005832class LooperEventCallback : public LooperCallback {
5833public:
5834 LooperEventCallback(std::function<int(int events)> callback) : mCallback(callback) {}
5835 int handleEvent(int /*fd*/, int events, void* /*data*/) override { return mCallback(events); }
5836
5837private:
5838 std::function<int(int events)> mCallback;
5839};
5840
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005841Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputChannel(const std::string& name) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00005842 if (DEBUG_CHANNEL_CREATION) {
5843 ALOGD("channel '%s' ~ createInputChannel", name.c_str());
5844 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005845
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005846 std::unique_ptr<InputChannel> serverChannel;
Garfield Tan15601662020-09-22 15:32:38 -07005847 std::unique_ptr<InputChannel> clientChannel;
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005848 status_t result = InputChannel::openInputChannelPair(name, serverChannel, clientChannel);
Garfield Tan15601662020-09-22 15:32:38 -07005849
5850 if (result) {
5851 return base::Error(result) << "Failed to open input channel pair with name " << name;
5852 }
5853
Michael Wrightd02c5b62014-02-10 15:10:22 -08005854 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005855 std::scoped_lock _l(mLock);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005856 const sp<IBinder>& token = serverChannel->getConnectionToken();
Garfield Tan15601662020-09-22 15:32:38 -07005857 int fd = serverChannel->getFd();
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07005858 std::shared_ptr<Connection> connection =
5859 std::make_shared<Connection>(std::move(serverChannel), /*monitor=*/false,
5860 mIdGenerator);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005861
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005862 if (mConnectionsByToken.find(token) != mConnectionsByToken.end()) {
5863 ALOGE("Created a new connection, but the token %p is already known", token.get());
5864 }
5865 mConnectionsByToken.emplace(token, connection);
5866
5867 std::function<int(int events)> callback = std::bind(&InputDispatcher::handleReceiveCallback,
5868 this, std::placeholders::_1, token);
5869
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005870 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, sp<LooperEventCallback>::make(callback),
5871 nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005872 } // release lock
5873
5874 // Wake the looper because some connections have changed.
5875 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07005876 return clientChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005877}
5878
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005879Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputMonitor(int32_t displayId,
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005880 const std::string& name,
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005881 gui::Pid pid) {
Garfield Tan15601662020-09-22 15:32:38 -07005882 std::shared_ptr<InputChannel> serverChannel;
5883 std::unique_ptr<InputChannel> clientChannel;
5884 status_t result = openInputChannelPair(name, serverChannel, clientChannel);
5885 if (result) {
5886 return base::Error(result) << "Failed to open input channel pair with name " << name;
5887 }
5888
Michael Wright3dd60e22019-03-27 22:06:44 +00005889 { // acquire lock
5890 std::scoped_lock _l(mLock);
5891
5892 if (displayId < 0) {
Garfield Tan15601662020-09-22 15:32:38 -07005893 return base::Error(BAD_VALUE) << "Attempted to create input monitor with name " << name
5894 << " without a specified display.";
Michael Wright3dd60e22019-03-27 22:06:44 +00005895 }
5896
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07005897 std::shared_ptr<Connection> connection =
5898 std::make_shared<Connection>(serverChannel, /*monitor=*/true, mIdGenerator);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005899 const sp<IBinder>& token = serverChannel->getConnectionToken();
Garfield Tan15601662020-09-22 15:32:38 -07005900 const int fd = serverChannel->getFd();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005901
5902 if (mConnectionsByToken.find(token) != mConnectionsByToken.end()) {
5903 ALOGE("Created a new connection, but the token %p is already known", token.get());
5904 }
5905 mConnectionsByToken.emplace(token, connection);
5906 std::function<int(int events)> callback = std::bind(&InputDispatcher::handleReceiveCallback,
5907 this, std::placeholders::_1, token);
Michael Wright3dd60e22019-03-27 22:06:44 +00005908
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005909 mGlobalMonitorsByDisplay[displayId].emplace_back(serverChannel, pid);
Michael Wright3dd60e22019-03-27 22:06:44 +00005910
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005911 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, sp<LooperEventCallback>::make(callback),
5912 nullptr);
Michael Wright3dd60e22019-03-27 22:06:44 +00005913 }
Garfield Tan15601662020-09-22 15:32:38 -07005914
Michael Wright3dd60e22019-03-27 22:06:44 +00005915 // Wake the looper because some connections have changed.
5916 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07005917 return clientChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005918}
5919
Garfield Tan15601662020-09-22 15:32:38 -07005920status_t InputDispatcher::removeInputChannel(const sp<IBinder>& connectionToken) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005921 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005922 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005923
Harry Cutts33476232023-01-30 19:57:29 +00005924 status_t status = removeInputChannelLocked(connectionToken, /*notify=*/false);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005925 if (status) {
5926 return status;
5927 }
5928 } // release lock
5929
5930 // Wake the poll loop because removing the connection may have changed the current
5931 // synchronization state.
5932 mLooper->wake();
5933 return OK;
5934}
5935
Garfield Tan15601662020-09-22 15:32:38 -07005936status_t InputDispatcher::removeInputChannelLocked(const sp<IBinder>& connectionToken,
5937 bool notify) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07005938 std::shared_ptr<Connection> connection = getConnectionLocked(connectionToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005939 if (connection == nullptr) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005940 // Connection can be removed via socket hang up or an explicit call to 'removeInputChannel'
Michael Wrightd02c5b62014-02-10 15:10:22 -08005941 return BAD_VALUE;
5942 }
5943
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005944 removeConnectionLocked(connection);
Robert Carr5c8a0262018-10-03 16:30:44 -07005945
Michael Wrightd02c5b62014-02-10 15:10:22 -08005946 if (connection->monitor) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005947 removeMonitorChannelLocked(connectionToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005948 }
5949
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005950 mLooper->removeFd(connection->inputChannel->getFd());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005951
5952 nsecs_t currentTime = now();
5953 abortBrokenDispatchCycleLocked(currentTime, connection, notify);
5954
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08005955 connection->status = Connection::Status::ZOMBIE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005956 return OK;
5957}
5958
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005959void InputDispatcher::removeMonitorChannelLocked(const sp<IBinder>& connectionToken) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005960 for (auto it = mGlobalMonitorsByDisplay.begin(); it != mGlobalMonitorsByDisplay.end();) {
5961 auto& [displayId, monitors] = *it;
5962 std::erase_if(monitors, [connectionToken](const Monitor& monitor) {
5963 return monitor.inputChannel->getConnectionToken() == connectionToken;
5964 });
Michael Wright3dd60e22019-03-27 22:06:44 +00005965
Michael Wright3dd60e22019-03-27 22:06:44 +00005966 if (monitors.empty()) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005967 it = mGlobalMonitorsByDisplay.erase(it);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005968 } else {
5969 ++it;
5970 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005971 }
5972}
5973
Michael Wright3dd60e22019-03-27 22:06:44 +00005974status_t InputDispatcher::pilferPointers(const sp<IBinder>& token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005975 std::scoped_lock _l(mLock);
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00005976 return pilferPointersLocked(token);
5977}
Michael Wright3dd60e22019-03-27 22:06:44 +00005978
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00005979status_t InputDispatcher::pilferPointersLocked(const sp<IBinder>& token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005980 const std::shared_ptr<InputChannel> requestingChannel = getInputChannelLocked(token);
5981 if (!requestingChannel) {
5982 ALOGW("Attempted to pilfer pointers from an un-registered channel or invalid token");
5983 return BAD_VALUE;
Michael Wright3dd60e22019-03-27 22:06:44 +00005984 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005985
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005986 auto [statePtr, windowPtr, displayId] = findTouchStateWindowAndDisplayLocked(token);
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005987 if (statePtr == nullptr || windowPtr == nullptr) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005988 ALOGW("Attempted to pilfer points from a channel without any on-going pointer streams."
5989 " Ignoring.");
5990 return BAD_VALUE;
5991 }
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005992 std::set<int32_t> deviceIds = windowPtr->getTouchingDeviceIds();
5993 if (deviceIds.size() != 1) {
5994 LOG(WARNING) << "Can't pilfer. Currently touching devices: " << dumpSet(deviceIds)
5995 << " in window: " << windowPtr->dump();
5996 return BAD_VALUE;
5997 }
5998 const int32_t deviceId = *deviceIds.begin();
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005999
6000 TouchState& state = *statePtr;
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00006001 TouchedWindow& window = *windowPtr;
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006002 // Send cancel events to all the input channels we're stealing from.
Michael Wrightfb04fd52022-11-24 22:31:11 +00006003 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006004 "input channel stole pointer stream");
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07006005 options.deviceId = deviceId;
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07006006 options.displayId = displayId;
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07006007 std::bitset<MAX_POINTER_ID + 1> pointerIds = window.getTouchingPointers(deviceId);
6008 options.pointerIds = pointerIds;
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006009 std::string canceledWindows;
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00006010 for (const TouchedWindow& w : state.windows) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006011 const std::shared_ptr<InputChannel> channel =
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00006012 getInputChannelLocked(w.windowHandle->getToken());
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006013 if (channel != nullptr && channel->getConnectionToken() != token) {
6014 synthesizeCancelationEventsForInputChannelLocked(channel, options);
6015 canceledWindows += canceledWindows.empty() ? "[" : ", ";
6016 canceledWindows += channel->getName();
6017 }
6018 }
6019 canceledWindows += canceledWindows.empty() ? "[]" : "]";
6020 ALOGI("Channel %s is stealing touch from %s", requestingChannel->getName().c_str(),
6021 canceledWindows.c_str());
6022
Prabir Pradhane680f9b2022-02-04 04:24:00 -08006023 // Prevent the gesture from being sent to any other windows.
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00006024 // This only blocks relevant pointers to be sent to other windows
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07006025 window.addPilferingPointers(deviceId, pointerIds);
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00006026
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07006027 state.cancelPointersForWindowsExcept(deviceId, pointerIds, token);
Michael Wright3dd60e22019-03-27 22:06:44 +00006028 return OK;
6029}
6030
Prabir Pradhan99987712020-11-10 18:43:05 -08006031void InputDispatcher::requestPointerCapture(const sp<IBinder>& windowToken, bool enabled) {
6032 { // acquire lock
6033 std::scoped_lock _l(mLock);
6034 if (DEBUG_FOCUS) {
chaviw98318de2021-05-19 16:45:23 -05006035 const sp<WindowInfoHandle> windowHandle = getWindowHandleLocked(windowToken);
Prabir Pradhan99987712020-11-10 18:43:05 -08006036 ALOGI("Request to %s Pointer Capture from: %s.", enabled ? "enable" : "disable",
6037 windowHandle != nullptr ? windowHandle->getName().c_str()
6038 : "token without window");
6039 }
6040
Vishnu Nairc519ff72021-01-21 08:23:08 -08006041 const sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Prabir Pradhan99987712020-11-10 18:43:05 -08006042 if (focusedToken != windowToken) {
6043 ALOGW("Ignoring request to %s Pointer Capture: window does not have focus.",
6044 enabled ? "enable" : "disable");
6045 return;
6046 }
6047
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006048 if (enabled == mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006049 ALOGW("Ignoring request to %s Pointer Capture: "
6050 "window has %s requested pointer capture.",
6051 enabled ? "enable" : "disable", enabled ? "already" : "not");
6052 return;
6053 }
6054
Christine Franksb768bb42021-11-29 12:11:31 -08006055 if (enabled) {
6056 if (std::find(mIneligibleDisplaysForPointerCapture.begin(),
6057 mIneligibleDisplaysForPointerCapture.end(),
6058 mFocusedDisplayId) != mIneligibleDisplaysForPointerCapture.end()) {
6059 ALOGW("Ignoring request to enable Pointer Capture: display is not eligible");
6060 return;
6061 }
6062 }
6063
Prabir Pradhan99987712020-11-10 18:43:05 -08006064 setPointerCaptureLocked(enabled);
6065 } // release lock
6066
6067 // Wake the thread to process command entries.
6068 mLooper->wake();
6069}
6070
Christine Franksb768bb42021-11-29 12:11:31 -08006071void InputDispatcher::setDisplayEligibilityForPointerCapture(int32_t displayId, bool isEligible) {
6072 { // acquire lock
6073 std::scoped_lock _l(mLock);
6074 std::erase(mIneligibleDisplaysForPointerCapture, displayId);
6075 if (!isEligible) {
6076 mIneligibleDisplaysForPointerCapture.push_back(displayId);
6077 }
6078 } // release lock
6079}
6080
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00006081std::optional<gui::Pid> InputDispatcher::findMonitorPidByTokenLocked(const sp<IBinder>& token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006082 for (const auto& [_, monitors] : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00006083 for (const Monitor& monitor : monitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07006084 if (monitor.inputChannel->getConnectionToken() == token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006085 return monitor.pid;
Michael Wright3dd60e22019-03-27 22:06:44 +00006086 }
6087 }
6088 }
6089 return std::nullopt;
6090}
6091
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006092std::shared_ptr<Connection> InputDispatcher::getConnectionLocked(
6093 const sp<IBinder>& inputConnectionToken) const {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07006094 if (inputConnectionToken == nullptr) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07006095 return nullptr;
Arthur Hung3b413f22018-10-26 18:05:34 +08006096 }
6097
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00006098 for (const auto& [token, connection] : mConnectionsByToken) {
6099 if (token == inputConnectionToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07006100 return connection;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006101 }
6102 }
Robert Carr4e670e52018-08-15 13:26:12 -07006103
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07006104 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006105}
6106
Siarhei Vishniakouad991402020-10-28 11:40:09 -05006107std::string InputDispatcher::getConnectionNameLocked(const sp<IBinder>& connectionToken) const {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006108 std::shared_ptr<Connection> connection = getConnectionLocked(connectionToken);
Siarhei Vishniakouad991402020-10-28 11:40:09 -05006109 if (connection == nullptr) {
6110 return "<nullptr>";
6111 }
6112 return connection->getInputChannelName();
6113}
6114
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006115void InputDispatcher::removeConnectionLocked(const std::shared_ptr<Connection>& connection) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006116 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00006117 mConnectionsByToken.erase(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07006118}
6119
Prabir Pradhancef936d2021-07-21 16:17:52 +00006120void InputDispatcher::doDispatchCycleFinishedCommand(nsecs_t finishTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006121 const std::shared_ptr<Connection>& connection,
6122 uint32_t seq, bool handled,
6123 nsecs_t consumeTime) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006124 // Handle post-event policy actions.
6125 std::deque<DispatchEntry*>::iterator dispatchEntryIt = connection->findWaitQueueEntry(seq);
6126 if (dispatchEntryIt == connection->waitQueue.end()) {
6127 return;
6128 }
6129 DispatchEntry* dispatchEntry = *dispatchEntryIt;
6130 const nsecs_t eventDuration = finishTime - dispatchEntry->deliveryTime;
6131 if (eventDuration > SLOW_EVENT_PROCESSING_WARNING_TIMEOUT) {
6132 ALOGI("%s spent %" PRId64 "ms processing %s", connection->getWindowName().c_str(),
6133 ns2ms(eventDuration), dispatchEntry->eventEntry->getDescription().c_str());
6134 }
6135 if (shouldReportFinishedEvent(*dispatchEntry, *connection)) {
6136 mLatencyTracker.trackFinishedEvent(dispatchEntry->eventEntry->id,
6137 connection->inputChannel->getConnectionToken(),
6138 dispatchEntry->deliveryTime, consumeTime, finishTime);
6139 }
6140
6141 bool restartEvent;
6142 if (dispatchEntry->eventEntry->type == EventEntry::Type::KEY) {
6143 KeyEntry& keyEntry = static_cast<KeyEntry&>(*(dispatchEntry->eventEntry));
6144 restartEvent =
6145 afterKeyEventLockedInterruptable(connection, dispatchEntry, keyEntry, handled);
6146 } else if (dispatchEntry->eventEntry->type == EventEntry::Type::MOTION) {
6147 MotionEntry& motionEntry = static_cast<MotionEntry&>(*(dispatchEntry->eventEntry));
6148 restartEvent = afterMotionEventLockedInterruptable(connection, dispatchEntry, motionEntry,
6149 handled);
6150 } else {
6151 restartEvent = false;
6152 }
6153
6154 // Dequeue the event and start the next cycle.
6155 // Because the lock might have been released, it is possible that the
6156 // contents of the wait queue to have been drained, so we need to double-check
6157 // a few things.
6158 dispatchEntryIt = connection->findWaitQueueEntry(seq);
6159 if (dispatchEntryIt != connection->waitQueue.end()) {
6160 dispatchEntry = *dispatchEntryIt;
6161 connection->waitQueue.erase(dispatchEntryIt);
6162 const sp<IBinder>& connectionToken = connection->inputChannel->getConnectionToken();
6163 mAnrTracker.erase(dispatchEntry->timeoutTime, connectionToken);
6164 if (!connection->responsive) {
6165 connection->responsive = isConnectionResponsive(*connection);
6166 if (connection->responsive) {
6167 // The connection was unresponsive, and now it's responsive.
6168 processConnectionResponsiveLocked(*connection);
6169 }
6170 }
6171 traceWaitQueueLength(*connection);
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08006172 if (restartEvent && connection->status == Connection::Status::NORMAL) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006173 connection->outboundQueue.push_front(dispatchEntry);
6174 traceOutboundQueueLength(*connection);
6175 } else {
6176 releaseDispatchEntry(dispatchEntry);
6177 }
6178 }
6179
6180 // Start the next dispatch cycle for this connection.
6181 startDispatchCycleLocked(now(), connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006182}
6183
Prabir Pradhancef936d2021-07-21 16:17:52 +00006184void InputDispatcher::sendFocusChangedCommandLocked(const sp<IBinder>& oldToken,
6185 const sp<IBinder>& newToken) {
6186 auto command = [this, oldToken, newToken]() REQUIRES(mLock) {
6187 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00006188 mPolicy.notifyFocusChanged(oldToken, newToken);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006189 };
6190 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08006191}
6192
Prabir Pradhancef936d2021-07-21 16:17:52 +00006193void InputDispatcher::sendDropWindowCommandLocked(const sp<IBinder>& token, float x, float y) {
6194 auto command = [this, token, x, y]() REQUIRES(mLock) {
6195 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00006196 mPolicy.notifyDropWindow(token, x, y);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006197 };
6198 postCommandLocked(std::move(command));
Robert Carrf759f162018-11-13 12:57:11 -08006199}
6200
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006201void InputDispatcher::onAnrLocked(const std::shared_ptr<Connection>& connection) {
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006202 if (connection == nullptr) {
6203 LOG_ALWAYS_FATAL("Caller must check for nullness");
6204 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006205 // Since we are allowing the policy to extend the timeout, maybe the waitQueue
6206 // is already healthy again. Don't raise ANR in this situation
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006207 if (connection->waitQueue.empty()) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006208 ALOGI("Not raising ANR because the connection %s has recovered",
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006209 connection->inputChannel->getName().c_str());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006210 return;
6211 }
6212 /**
6213 * The "oldestEntry" is the entry that was first sent to the application. That entry, however,
6214 * may not be the one that caused the timeout to occur. One possibility is that window timeout
6215 * has changed. This could cause newer entries to time out before the already dispatched
6216 * entries. In that situation, the newest entries caused ANR. But in all likelihood, the app
6217 * processes the events linearly. So providing information about the oldest entry seems to be
6218 * most useful.
6219 */
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006220 DispatchEntry* oldestEntry = *connection->waitQueue.begin();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006221 const nsecs_t currentWait = now() - oldestEntry->deliveryTime;
6222 std::string reason =
6223 android::base::StringPrintf("%s is not responding. Waited %" PRId64 "ms for %s",
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006224 connection->inputChannel->getName().c_str(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006225 ns2ms(currentWait),
6226 oldestEntry->eventEntry->getDescription().c_str());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006227 sp<IBinder> connectionToken = connection->inputChannel->getConnectionToken();
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -06006228 updateLastAnrStateLocked(getWindowHandleLocked(connectionToken), reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006229
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006230 processConnectionUnresponsiveLocked(*connection, std::move(reason));
6231
6232 // Stop waking up for events on this connection, it is already unresponsive
6233 cancelEventsForAnrLocked(connection);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006234}
6235
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05006236void InputDispatcher::onAnrLocked(std::shared_ptr<InputApplicationHandle> application) {
6237 std::string reason =
6238 StringPrintf("%s does not have a focused window", application->getName().c_str());
6239 updateLastAnrStateLocked(*application, reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006240
Yabin Cui8eb9c552023-06-08 18:05:07 +00006241 auto command = [this, app = std::move(application)]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006242 scoped_unlock unlock(mLock);
Yabin Cuiced952f2023-06-09 21:12:51 +00006243 mPolicy.notifyNoFocusedWindowAnr(app);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006244 };
6245 postCommandLocked(std::move(command));
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00006246}
6247
chaviw98318de2021-05-19 16:45:23 -05006248void InputDispatcher::updateLastAnrStateLocked(const sp<WindowInfoHandle>& window,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006249 const std::string& reason) {
6250 const std::string windowLabel = getApplicationWindowLabel(nullptr, window);
6251 updateLastAnrStateLocked(windowLabel, reason);
6252}
6253
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05006254void InputDispatcher::updateLastAnrStateLocked(const InputApplicationHandle& application,
6255 const std::string& reason) {
6256 const std::string windowLabel = getApplicationWindowLabel(&application, nullptr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006257 updateLastAnrStateLocked(windowLabel, reason);
6258}
6259
6260void InputDispatcher::updateLastAnrStateLocked(const std::string& windowLabel,
6261 const std::string& reason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006262 // Capture a record of the InputDispatcher state at the time of the ANR.
Yi Kong9b14ac62018-07-17 13:48:38 -07006263 time_t t = time(nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006264 struct tm tm;
6265 localtime_r(&t, &tm);
6266 char timestr[64];
6267 strftime(timestr, sizeof(timestr), "%F %T", &tm);
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006268 mLastAnrState.clear();
6269 mLastAnrState += INDENT "ANR:\n";
6270 mLastAnrState += StringPrintf(INDENT2 "Time: %s\n", timestr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006271 mLastAnrState += StringPrintf(INDENT2 "Reason: %s\n", reason.c_str());
6272 mLastAnrState += StringPrintf(INDENT2 "Window: %s\n", windowLabel.c_str());
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006273 dumpDispatchStateLocked(mLastAnrState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006274}
6275
Prabir Pradhancef936d2021-07-21 16:17:52 +00006276void InputDispatcher::doInterceptKeyBeforeDispatchingCommand(const sp<IBinder>& focusedWindowToken,
6277 KeyEntry& entry) {
6278 const KeyEvent event = createKeyEvent(entry);
6279 nsecs_t delay = 0;
6280 { // release lock
6281 scoped_unlock unlock(mLock);
6282 android::base::Timer t;
Prabir Pradhana41d2442023-04-20 21:30:40 +00006283 delay = mPolicy.interceptKeyBeforeDispatching(focusedWindowToken, event, entry.policyFlags);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006284 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
6285 ALOGW("Excessive delay in interceptKeyBeforeDispatching; took %s ms",
6286 std::to_string(t.duration().count()).c_str());
6287 }
6288 } // acquire lock
Michael Wrightd02c5b62014-02-10 15:10:22 -08006289
6290 if (delay < 0) {
Michael Wright5caf55a2022-11-24 22:31:42 +00006291 entry.interceptKeyResult = KeyEntry::InterceptKeyResult::SKIP;
Prabir Pradhancef936d2021-07-21 16:17:52 +00006292 } else if (delay == 0) {
Michael Wright5caf55a2022-11-24 22:31:42 +00006293 entry.interceptKeyResult = KeyEntry::InterceptKeyResult::CONTINUE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006294 } else {
Michael Wright5caf55a2022-11-24 22:31:42 +00006295 entry.interceptKeyResult = KeyEntry::InterceptKeyResult::TRY_AGAIN_LATER;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006296 entry.interceptKeyWakeupTime = now() + delay;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006297 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006298}
6299
Prabir Pradhancef936d2021-07-21 16:17:52 +00006300void InputDispatcher::sendWindowUnresponsiveCommandLocked(const sp<IBinder>& token,
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00006301 std::optional<gui::Pid> pid,
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006302 std::string reason) {
Yabin Cui8eb9c552023-06-08 18:05:07 +00006303 auto command = [this, token, pid, r = std::move(reason)]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006304 scoped_unlock unlock(mLock);
Yabin Cuiced952f2023-06-09 21:12:51 +00006305 mPolicy.notifyWindowUnresponsive(token, pid, r);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006306 };
6307 postCommandLocked(std::move(command));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006308}
6309
Prabir Pradhanedd96402022-02-15 01:46:16 -08006310void InputDispatcher::sendWindowResponsiveCommandLocked(const sp<IBinder>& token,
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00006311 std::optional<gui::Pid> pid) {
Prabir Pradhanedd96402022-02-15 01:46:16 -08006312 auto command = [this, token, pid]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006313 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00006314 mPolicy.notifyWindowResponsive(token, pid);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006315 };
6316 postCommandLocked(std::move(command));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006317}
6318
6319/**
6320 * Tell the policy that a connection has become unresponsive so that it can start ANR.
6321 * Check whether the connection of interest is a monitor or a window, and add the corresponding
6322 * command entry to the command queue.
6323 */
6324void InputDispatcher::processConnectionUnresponsiveLocked(const Connection& connection,
6325 std::string reason) {
6326 const sp<IBinder>& connectionToken = connection.inputChannel->getConnectionToken();
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00006327 std::optional<gui::Pid> pid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006328 if (connection.monitor) {
6329 ALOGW("Monitor %s is unresponsive: %s", connection.inputChannel->getName().c_str(),
6330 reason.c_str());
Prabir Pradhanedd96402022-02-15 01:46:16 -08006331 pid = findMonitorPidByTokenLocked(connectionToken);
6332 } else {
6333 // The connection is a window
6334 ALOGW("Window %s is unresponsive: %s", connection.inputChannel->getName().c_str(),
6335 reason.c_str());
6336 const sp<WindowInfoHandle> handle = getWindowHandleLocked(connectionToken);
6337 if (handle != nullptr) {
6338 pid = handle->getInfo()->ownerPid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006339 }
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006340 }
Prabir Pradhanedd96402022-02-15 01:46:16 -08006341 sendWindowUnresponsiveCommandLocked(connectionToken, pid, std::move(reason));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006342}
6343
6344/**
6345 * Tell the policy that a connection has become responsive so that it can stop ANR.
6346 */
6347void InputDispatcher::processConnectionResponsiveLocked(const Connection& connection) {
6348 const sp<IBinder>& connectionToken = connection.inputChannel->getConnectionToken();
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00006349 std::optional<gui::Pid> pid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006350 if (connection.monitor) {
Prabir Pradhanedd96402022-02-15 01:46:16 -08006351 pid = findMonitorPidByTokenLocked(connectionToken);
6352 } else {
6353 // The connection is a window
6354 const sp<WindowInfoHandle> handle = getWindowHandleLocked(connectionToken);
6355 if (handle != nullptr) {
6356 pid = handle->getInfo()->ownerPid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006357 }
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006358 }
Prabir Pradhanedd96402022-02-15 01:46:16 -08006359 sendWindowResponsiveCommandLocked(connectionToken, pid);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006360}
6361
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006362bool InputDispatcher::afterKeyEventLockedInterruptable(
6363 const std::shared_ptr<Connection>& connection, DispatchEntry* dispatchEntry,
6364 KeyEntry& keyEntry, bool handled) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006365 if (keyEntry.flags & AKEY_EVENT_FLAG_FALLBACK) {
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006366 if (!handled) {
6367 // Report the key as unhandled, since the fallback was not handled.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006368 mReporter->reportUnhandledKey(keyEntry.id);
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006369 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006370 return false;
6371 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006372
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006373 // Get the fallback key state.
6374 // Clear it out after dispatching the UP.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006375 int32_t originalKeyCode = keyEntry.keyCode;
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006376 std::optional<int32_t> fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006377 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006378 connection->inputState.removeFallbackKey(originalKeyCode);
6379 }
6380
6381 if (handled || !dispatchEntry->hasForegroundTarget()) {
6382 // If the application handles the original key for which we previously
6383 // generated a fallback or if the window is not a foreground window,
6384 // then cancel the associated fallback key, if any.
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006385 if (fallbackKeyCode) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006386 // Dispatch the unhandled key to the policy with the cancel flag.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006387 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6388 ALOGD("Unhandled key event: Asking policy to cancel fallback action. "
6389 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6390 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount,
6391 keyEntry.policyFlags);
6392 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006393 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006394 event.setFlags(event.getFlags() | AKEY_EVENT_FLAG_CANCELED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006395
6396 mLock.unlock();
6397
Prabir Pradhana41d2442023-04-20 21:30:40 +00006398 if (const auto unhandledKeyFallback =
6399 mPolicy.dispatchUnhandledKey(connection->inputChannel->getConnectionToken(),
6400 event, keyEntry.policyFlags);
6401 unhandledKeyFallback) {
6402 event = *unhandledKeyFallback;
6403 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006404
6405 mLock.lock();
6406
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006407 // Cancel the fallback key.
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006408 if (*fallbackKeyCode != AKEYCODE_UNKNOWN) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00006409 CancelationOptions options(CancelationOptions::Mode::CANCEL_FALLBACK_EVENTS,
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006410 "application handled the original non-fallback key "
6411 "or is no longer a foreground target, "
6412 "canceling previously dispatched fallback key");
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006413 options.keyCode = *fallbackKeyCode;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006414 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006415 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006416 connection->inputState.removeFallbackKey(originalKeyCode);
6417 }
6418 } else {
6419 // If the application did not handle a non-fallback key, first check
6420 // that we are in a good state to perform unhandled key event processing
6421 // Then ask the policy what to do with it.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006422 bool initialDown = keyEntry.action == AKEY_EVENT_ACTION_DOWN && keyEntry.repeatCount == 0;
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006423 if (!fallbackKeyCode && !initialDown) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006424 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6425 ALOGD("Unhandled key event: Skipping unhandled key event processing "
6426 "since this is not an initial down. "
6427 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6428 originalKeyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
6429 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006430 return false;
6431 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006432
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006433 // Dispatch the unhandled key to the policy.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006434 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6435 ALOGD("Unhandled key event: Asking policy to perform fallback action. "
6436 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6437 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
6438 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006439 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006440
6441 mLock.unlock();
6442
Prabir Pradhana41d2442023-04-20 21:30:40 +00006443 bool fallback = false;
6444 if (auto fb = mPolicy.dispatchUnhandledKey(connection->inputChannel->getConnectionToken(),
6445 event, keyEntry.policyFlags);
6446 fb) {
6447 fallback = true;
6448 event = *fb;
6449 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006450
6451 mLock.lock();
6452
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08006453 if (connection->status != Connection::Status::NORMAL) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006454 connection->inputState.removeFallbackKey(originalKeyCode);
6455 return false;
6456 }
6457
6458 // Latch the fallback keycode for this key on an initial down.
6459 // The fallback keycode cannot change at any other point in the lifecycle.
6460 if (initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006461 if (fallback) {
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006462 *fallbackKeyCode = event.getKeyCode();
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006463 } else {
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006464 *fallbackKeyCode = AKEYCODE_UNKNOWN;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006465 }
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006466 connection->inputState.setFallbackKey(originalKeyCode, *fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006467 }
6468
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006469 ALOG_ASSERT(fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006470
6471 // Cancel the fallback key if the policy decides not to send it anymore.
6472 // We will continue to dispatch the key to the policy but we will no
6473 // longer dispatch a fallback key to the application.
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006474 if (*fallbackKeyCode != AKEYCODE_UNKNOWN &&
6475 (!fallback || *fallbackKeyCode != event.getKeyCode())) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006476 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6477 if (fallback) {
6478 ALOGD("Unhandled key event: Policy requested to send key %d"
6479 "as a fallback for %d, but on the DOWN it had requested "
6480 "to send %d instead. Fallback canceled.",
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006481 event.getKeyCode(), originalKeyCode, *fallbackKeyCode);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006482 } else {
6483 ALOGD("Unhandled key event: Policy did not request fallback for %d, "
6484 "but on the DOWN it had requested to send %d. "
6485 "Fallback canceled.",
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006486 originalKeyCode, *fallbackKeyCode);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006487 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006488 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006489
Michael Wrightfb04fd52022-11-24 22:31:11 +00006490 CancelationOptions options(CancelationOptions::Mode::CANCEL_FALLBACK_EVENTS,
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006491 "canceling fallback, policy no longer desires it");
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006492 options.keyCode = *fallbackKeyCode;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006493 synthesizeCancelationEventsForConnectionLocked(connection, options);
6494
6495 fallback = false;
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006496 *fallbackKeyCode = AKEYCODE_UNKNOWN;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006497 if (keyEntry.action != AKEY_EVENT_ACTION_UP) {
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006498 connection->inputState.setFallbackKey(originalKeyCode, *fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006499 }
6500 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006501
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006502 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6503 {
6504 std::string msg;
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006505 const std::map<int32_t, int32_t>& fallbackKeys =
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006506 connection->inputState.getFallbackKeys();
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006507 for (const auto& [key, value] : fallbackKeys) {
6508 msg += StringPrintf(", %d->%d", key, value);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006509 }
6510 ALOGD("Unhandled key event: %zu currently tracked fallback keys%s.",
6511 fallbackKeys.size(), msg.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006512 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006513 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006514
6515 if (fallback) {
6516 // Restart the dispatch cycle using the fallback key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006517 keyEntry.eventTime = event.getEventTime();
6518 keyEntry.deviceId = event.getDeviceId();
6519 keyEntry.source = event.getSource();
6520 keyEntry.displayId = event.getDisplayId();
6521 keyEntry.flags = event.getFlags() | AKEY_EVENT_FLAG_FALLBACK;
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006522 keyEntry.keyCode = *fallbackKeyCode;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006523 keyEntry.scanCode = event.getScanCode();
6524 keyEntry.metaState = event.getMetaState();
6525 keyEntry.repeatCount = event.getRepeatCount();
6526 keyEntry.downTime = event.getDownTime();
6527 keyEntry.syntheticRepeat = false;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006528
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006529 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6530 ALOGD("Unhandled key event: Dispatching fallback key. "
6531 "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006532 originalKeyCode, *fallbackKeyCode, keyEntry.metaState);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006533 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006534 return true; // restart the event
6535 } else {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006536 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6537 ALOGD("Unhandled key event: No fallback key.");
6538 }
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006539
6540 // Report the key as unhandled, since there is no fallback key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006541 mReporter->reportUnhandledKey(keyEntry.id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006542 }
6543 }
6544 return false;
6545}
6546
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006547bool InputDispatcher::afterMotionEventLockedInterruptable(
6548 const std::shared_ptr<Connection>& connection, DispatchEntry* dispatchEntry,
6549 MotionEntry& motionEntry, bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006550 return false;
6551}
6552
Michael Wrightd02c5b62014-02-10 15:10:22 -08006553void InputDispatcher::traceInboundQueueLengthLocked() {
6554 if (ATRACE_ENABLED()) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07006555 ATRACE_INT("iq", mInboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006556 }
6557}
6558
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006559void InputDispatcher::traceOutboundQueueLength(const Connection& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006560 if (ATRACE_ENABLED()) {
6561 char counterName[40];
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006562 snprintf(counterName, sizeof(counterName), "oq:%s", connection.getWindowName().c_str());
6563 ATRACE_INT(counterName, connection.outboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006564 }
6565}
6566
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006567void InputDispatcher::traceWaitQueueLength(const Connection& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006568 if (ATRACE_ENABLED()) {
6569 char counterName[40];
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006570 snprintf(counterName, sizeof(counterName), "wq:%s", connection.getWindowName().c_str());
6571 ATRACE_INT(counterName, connection.waitQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006572 }
6573}
6574
Siarhei Vishniakou5e20f272023-06-08 17:24:44 -07006575void InputDispatcher::dump(std::string& dump) const {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006576 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006577
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006578 dump += "Input Dispatcher State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08006579 dumpDispatchStateLocked(dump);
6580
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006581 if (!mLastAnrState.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006582 dump += "\nInput Dispatcher State at time of last ANR:\n";
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006583 dump += mLastAnrState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006584 }
6585}
6586
6587void InputDispatcher::monitor() {
6588 // Acquire and release the lock to ensure that the dispatcher has not deadlocked.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006589 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006590 mLooper->wake();
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006591 mDispatcherIsAlive.wait(_l);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006592}
6593
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08006594/**
6595 * Wake up the dispatcher and wait until it processes all events and commands.
6596 * The notification of mDispatcherEnteredIdle is guaranteed to happen after wake(), so
6597 * this method can be safely called from any thread, as long as you've ensured that
6598 * the work you are interested in completing has already been queued.
6599 */
Siarhei Vishniakoua66d65e2023-06-16 10:32:51 -07006600bool InputDispatcher::waitForIdle() const {
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08006601 /**
6602 * Timeout should represent the longest possible time that a device might spend processing
6603 * events and commands.
6604 */
6605 constexpr std::chrono::duration TIMEOUT = 100ms;
6606 std::unique_lock lock(mLock);
6607 mLooper->wake();
6608 std::cv_status result = mDispatcherEnteredIdle.wait_for(lock, TIMEOUT);
6609 return result == std::cv_status::no_timeout;
6610}
6611
Vishnu Naire798b472020-07-23 13:52:21 -07006612/**
6613 * Sets focus to the window identified by the token. This must be called
6614 * after updating any input window handles.
6615 *
6616 * Params:
6617 * request.token - input channel token used to identify the window that should gain focus.
6618 * request.focusedToken - the token that the caller expects currently to be focused. If the
6619 * specified token does not match the currently focused window, this request will be dropped.
6620 * If the specified focused token matches the currently focused window, the call will succeed.
6621 * Set this to "null" if this call should succeed no matter what the currently focused token is.
6622 * request.timestamp - SYSTEM_TIME_MONOTONIC timestamp in nanos set by the client (wm)
6623 * when requesting the focus change. This determines which request gets
6624 * precedence if there is a focus change request from another source such as pointer down.
6625 */
Vishnu Nair958da932020-08-21 17:12:37 -07006626void InputDispatcher::setFocusedWindow(const FocusRequest& request) {
6627 { // acquire lock
6628 std::scoped_lock _l(mLock);
Vishnu Nairc519ff72021-01-21 08:23:08 -08006629 std::optional<FocusResolver::FocusChanges> changes =
6630 mFocusResolver.setFocusedWindow(request, getWindowHandlesLocked(request.displayId));
6631 if (changes) {
6632 onFocusChangedLocked(*changes);
Vishnu Nair958da932020-08-21 17:12:37 -07006633 }
6634 } // release lock
6635 // Wake up poll loop since it may need to make new input dispatching choices.
6636 mLooper->wake();
6637}
6638
Vishnu Nairc519ff72021-01-21 08:23:08 -08006639void InputDispatcher::onFocusChangedLocked(const FocusResolver::FocusChanges& changes) {
6640 if (changes.oldFocus) {
6641 std::shared_ptr<InputChannel> focusedInputChannel = getInputChannelLocked(changes.oldFocus);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006642 if (focusedInputChannel) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00006643 CancelationOptions options(CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS,
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006644 "focus left window");
6645 synthesizeCancelationEventsForInputChannelLocked(focusedInputChannel, options);
Harry Cutts33476232023-01-30 19:57:29 +00006646 enqueueFocusEventLocked(changes.oldFocus, /*hasFocus=*/false, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006647 }
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006648 }
Vishnu Nairc519ff72021-01-21 08:23:08 -08006649 if (changes.newFocus) {
Harry Cutts33476232023-01-30 19:57:29 +00006650 enqueueFocusEventLocked(changes.newFocus, /*hasFocus=*/true, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006651 }
6652
Prabir Pradhan99987712020-11-10 18:43:05 -08006653 // If a window has pointer capture, then it must have focus. We need to ensure that this
6654 // contract is upheld when pointer capture is being disabled due to a loss of window focus.
6655 // If the window loses focus before it loses pointer capture, then the window can be in a state
6656 // where it has pointer capture but not focus, violating the contract. Therefore we must
6657 // dispatch the pointer capture event before the focus event. Since focus events are added to
6658 // the front of the queue (above), we add the pointer capture event to the front of the queue
6659 // after the focus events are added. This ensures the pointer capture event ends up at the
6660 // front.
6661 disablePointerCaptureForcedLocked();
6662
Vishnu Nairc519ff72021-01-21 08:23:08 -08006663 if (mFocusedDisplayId == changes.displayId) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006664 sendFocusChangedCommandLocked(changes.oldFocus, changes.newFocus);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006665 }
6666}
Vishnu Nair958da932020-08-21 17:12:37 -07006667
Prabir Pradhan99987712020-11-10 18:43:05 -08006668void InputDispatcher::disablePointerCaptureForcedLocked() {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006669 if (!mCurrentPointerCaptureRequest.enable && !mWindowTokenWithPointerCapture) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006670 return;
6671 }
6672
6673 ALOGD_IF(DEBUG_FOCUS, "Disabling Pointer Capture because the window lost focus.");
6674
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006675 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006676 setPointerCaptureLocked(false);
6677 }
6678
6679 if (!mWindowTokenWithPointerCapture) {
6680 // No need to send capture changes because no window has capture.
6681 return;
6682 }
6683
6684 if (mPendingEvent != nullptr) {
6685 // Move the pending event to the front of the queue. This will give the chance
6686 // for the pending event to be dropped if it is a captured event.
6687 mInboundQueue.push_front(mPendingEvent);
6688 mPendingEvent = nullptr;
6689 }
6690
6691 auto entry = std::make_unique<PointerCaptureChangedEntry>(mIdGenerator.nextId(), now(),
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006692 mCurrentPointerCaptureRequest);
Prabir Pradhan99987712020-11-10 18:43:05 -08006693 mInboundQueue.push_front(std::move(entry));
6694}
6695
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006696void InputDispatcher::setPointerCaptureLocked(bool enable) {
6697 mCurrentPointerCaptureRequest.enable = enable;
6698 mCurrentPointerCaptureRequest.seq++;
6699 auto command = [this, request = mCurrentPointerCaptureRequest]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006700 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00006701 mPolicy.setPointerCapture(request);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006702 };
6703 postCommandLocked(std::move(command));
Prabir Pradhan99987712020-11-10 18:43:05 -08006704}
6705
Vishnu Nair599f1412021-06-21 10:39:58 -07006706void InputDispatcher::displayRemoved(int32_t displayId) {
6707 { // acquire lock
6708 std::scoped_lock _l(mLock);
6709 // Set an empty list to remove all handles from the specific display.
Harry Cutts101ee9b2023-07-06 18:04:14 +00006710 setInputWindowsLocked(/*windowInfoHandles=*/{}, displayId);
Vishnu Nair599f1412021-06-21 10:39:58 -07006711 setFocusedApplicationLocked(displayId, nullptr);
6712 // Call focus resolver to clean up stale requests. This must be called after input windows
6713 // have been removed for the removed display.
6714 mFocusResolver.displayRemoved(displayId);
Christine Franksb768bb42021-11-29 12:11:31 -08006715 // Reset pointer capture eligibility, regardless of previous state.
6716 std::erase(mIneligibleDisplaysForPointerCapture, displayId);
Antonio Kantek15beb512022-06-13 22:35:41 +00006717 // Remove the associated touch mode state.
6718 mTouchModePerDisplay.erase(displayId);
Siarhei Vishniakou5c02a712023-05-15 15:45:02 -07006719 mVerifiersByDisplay.erase(displayId);
Vishnu Nair599f1412021-06-21 10:39:58 -07006720 } // release lock
6721
6722 // Wake up poll loop since it may need to make new input dispatching choices.
6723 mLooper->wake();
6724}
6725
Patrick Williamsd828f302023-04-28 17:52:08 -05006726void InputDispatcher::onWindowInfosChanged(const gui::WindowInfosUpdate& update) {
chaviw15fab6f2021-06-07 14:15:52 -05006727 // The listener sends the windows as a flattened array. Separate the windows by display for
6728 // more convenient parsing.
6729 std::unordered_map<int32_t, std::vector<sp<WindowInfoHandle>>> handlesPerDisplay;
Patrick Williamsd828f302023-04-28 17:52:08 -05006730 for (const auto& info : update.windowInfos) {
chaviw15fab6f2021-06-07 14:15:52 -05006731 handlesPerDisplay.emplace(info.displayId, std::vector<sp<WindowInfoHandle>>());
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07006732 handlesPerDisplay[info.displayId].push_back(sp<WindowInfoHandle>::make(info));
chaviw15fab6f2021-06-07 14:15:52 -05006733 }
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006734
6735 { // acquire lock
6736 std::scoped_lock _l(mLock);
Prabir Pradhan814fe082022-07-22 20:22:18 +00006737
6738 // Ensure that we have an entry created for all existing displays so that if a displayId has
6739 // no windows, we can tell that the windows were removed from the display.
6740 for (const auto& [displayId, _] : mWindowHandlesByDisplay) {
6741 handlesPerDisplay[displayId];
6742 }
6743
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006744 mDisplayInfos.clear();
Patrick Williamsd828f302023-04-28 17:52:08 -05006745 for (const auto& displayInfo : update.displayInfos) {
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006746 mDisplayInfos.emplace(displayInfo.displayId, displayInfo);
6747 }
6748
6749 for (const auto& [displayId, handles] : handlesPerDisplay) {
6750 setInputWindowsLocked(handles, displayId);
6751 }
Patrick Williams9464b2c2023-05-23 11:22:04 -05006752
6753 if (update.vsyncId < mWindowInfosVsyncId) {
6754 ALOGE("Received out of order window infos update. Last update vsync id: %" PRId64
6755 ", current update vsync id: %" PRId64,
6756 mWindowInfosVsyncId, update.vsyncId);
6757 }
6758 mWindowInfosVsyncId = update.vsyncId;
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006759 }
6760 // Wake up poll loop since it may need to make new input dispatching choices.
6761 mLooper->wake();
chaviw15fab6f2021-06-07 14:15:52 -05006762}
6763
Vishnu Nair062a8672021-09-03 16:07:44 -07006764bool InputDispatcher::shouldDropInput(
6765 const EventEntry& entry, const sp<android::gui::WindowInfoHandle>& windowHandle) const {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006766 if (windowHandle->getInfo()->inputConfig.test(WindowInfo::InputConfig::DROP_INPUT) ||
6767 (windowHandle->getInfo()->inputConfig.test(
6768 WindowInfo::InputConfig::DROP_INPUT_IF_OBSCURED) &&
Vishnu Nair062a8672021-09-03 16:07:44 -07006769 isWindowObscuredLocked(windowHandle))) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006770 ALOGW("Dropping %s event targeting %s as requested by the input configuration {%s} on "
6771 "display %" PRId32 ".",
Vishnu Nair062a8672021-09-03 16:07:44 -07006772 ftl::enum_string(entry.type).c_str(), windowHandle->getName().c_str(),
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006773 windowHandle->getInfo()->inputConfig.string().c_str(),
Vishnu Nair062a8672021-09-03 16:07:44 -07006774 windowHandle->getInfo()->displayId);
6775 return true;
6776 }
6777 return false;
6778}
6779
Siarhei Vishniakou18050092021-09-01 13:32:49 -07006780void InputDispatcher::DispatcherWindowListener::onWindowInfosChanged(
Patrick Williamsd828f302023-04-28 17:52:08 -05006781 const gui::WindowInfosUpdate& update) {
6782 mDispatcher.onWindowInfosChanged(update);
Siarhei Vishniakou18050092021-09-01 13:32:49 -07006783}
6784
Arthur Hungdfd528e2021-12-08 13:23:04 +00006785void InputDispatcher::cancelCurrentTouch() {
6786 {
6787 std::scoped_lock _l(mLock);
6788 ALOGD("Canceling all ongoing pointer gestures on all displays.");
Michael Wrightfb04fd52022-11-24 22:31:11 +00006789 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
Arthur Hungdfd528e2021-12-08 13:23:04 +00006790 "cancel current touch");
6791 synthesizeCancelationEventsForAllConnectionsLocked(options);
6792
6793 mTouchStatesByDisplay.clear();
Arthur Hungdfd528e2021-12-08 13:23:04 +00006794 }
6795 // Wake up poll loop since there might be work to do.
6796 mLooper->wake();
6797}
6798
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006799void InputDispatcher::setMonitorDispatchingTimeoutForTest(std::chrono::nanoseconds timeout) {
6800 std::scoped_lock _l(mLock);
6801 mMonitorDispatchingTimeout = timeout;
6802}
6803
Arthur Hungc539dbb2022-12-08 07:45:36 +00006804void InputDispatcher::slipWallpaperTouch(ftl::Flags<InputTarget::Flags> targetFlags,
6805 const sp<WindowInfoHandle>& oldWindowHandle,
6806 const sp<WindowInfoHandle>& newWindowHandle,
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07006807 TouchState& state, int32_t deviceId, int32_t pointerId,
Siarhei Vishniakoubf880522023-05-01 11:03:22 -07006808 std::vector<InputTarget>& targets) const {
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08006809 std::bitset<MAX_POINTER_ID + 1> pointerIds;
6810 pointerIds.set(pointerId);
Arthur Hungc539dbb2022-12-08 07:45:36 +00006811 const bool oldHasWallpaper = oldWindowHandle->getInfo()->inputConfig.test(
6812 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
6813 const bool newHasWallpaper = targetFlags.test(InputTarget::Flags::FOREGROUND) &&
6814 newWindowHandle->getInfo()->inputConfig.test(
6815 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
6816 const sp<WindowInfoHandle> oldWallpaper =
6817 oldHasWallpaper ? state.getWallpaperWindow() : nullptr;
6818 const sp<WindowInfoHandle> newWallpaper =
6819 newHasWallpaper ? findWallpaperWindowBelow(newWindowHandle) : nullptr;
6820 if (oldWallpaper == newWallpaper) {
6821 return;
6822 }
6823
6824 if (oldWallpaper != nullptr) {
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08006825 const TouchedWindow& oldTouchedWindow = state.getTouchedWindow(oldWallpaper);
6826 addWindowTargetLocked(oldWallpaper,
6827 oldTouchedWindow.targetFlags |
6828 InputTarget::Flags::DISPATCH_AS_SLIPPERY_EXIT,
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07006829 pointerIds, oldTouchedWindow.getDownTimeInTarget(deviceId), targets);
6830 state.removeTouchingPointerFromWindow(deviceId, pointerId, oldWallpaper);
Arthur Hungc539dbb2022-12-08 07:45:36 +00006831 }
6832
6833 if (newWallpaper != nullptr) {
6834 state.addOrUpdateWindow(newWallpaper,
6835 InputTarget::Flags::DISPATCH_AS_SLIPPERY_ENTER |
6836 InputTarget::Flags::WINDOW_IS_OBSCURED |
6837 InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED,
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07006838 deviceId, pointerIds);
Arthur Hungc539dbb2022-12-08 07:45:36 +00006839 }
6840}
6841
6842void InputDispatcher::transferWallpaperTouch(ftl::Flags<InputTarget::Flags> oldTargetFlags,
6843 ftl::Flags<InputTarget::Flags> newTargetFlags,
6844 const sp<WindowInfoHandle> fromWindowHandle,
6845 const sp<WindowInfoHandle> toWindowHandle,
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07006846 TouchState& state, int32_t deviceId,
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08006847 std::bitset<MAX_POINTER_ID + 1> pointerIds) {
Arthur Hungc539dbb2022-12-08 07:45:36 +00006848 const bool oldHasWallpaper = oldTargetFlags.test(InputTarget::Flags::FOREGROUND) &&
6849 fromWindowHandle->getInfo()->inputConfig.test(
6850 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
6851 const bool newHasWallpaper = newTargetFlags.test(InputTarget::Flags::FOREGROUND) &&
6852 toWindowHandle->getInfo()->inputConfig.test(
6853 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
6854
6855 const sp<WindowInfoHandle> oldWallpaper =
6856 oldHasWallpaper ? state.getWallpaperWindow() : nullptr;
6857 const sp<WindowInfoHandle> newWallpaper =
6858 newHasWallpaper ? findWallpaperWindowBelow(toWindowHandle) : nullptr;
6859 if (oldWallpaper == newWallpaper) {
6860 return;
6861 }
6862
6863 if (oldWallpaper != nullptr) {
6864 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
6865 "transferring touch focus to another window");
6866 state.removeWindowByToken(oldWallpaper->getToken());
6867 synthesizeCancelationEventsForWindowLocked(oldWallpaper, options);
6868 }
6869
6870 if (newWallpaper != nullptr) {
6871 nsecs_t downTimeInTarget = now();
6872 ftl::Flags<InputTarget::Flags> wallpaperFlags =
6873 oldTargetFlags & (InputTarget::Flags::SPLIT | InputTarget::Flags::DISPATCH_AS_IS);
6874 wallpaperFlags |= InputTarget::Flags::WINDOW_IS_OBSCURED |
6875 InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED;
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07006876 state.addOrUpdateWindow(newWallpaper, wallpaperFlags, deviceId, pointerIds,
6877 downTimeInTarget);
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006878 std::shared_ptr<Connection> wallpaperConnection =
6879 getConnectionLocked(newWallpaper->getToken());
Arthur Hungc539dbb2022-12-08 07:45:36 +00006880 if (wallpaperConnection != nullptr) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006881 std::shared_ptr<Connection> toConnection =
6882 getConnectionLocked(toWindowHandle->getToken());
Arthur Hungc539dbb2022-12-08 07:45:36 +00006883 toConnection->inputState.mergePointerStateTo(wallpaperConnection->inputState);
6884 synthesizePointerDownEventsForConnectionLocked(downTimeInTarget, wallpaperConnection,
6885 wallpaperFlags);
6886 }
6887 }
6888}
6889
6890sp<WindowInfoHandle> InputDispatcher::findWallpaperWindowBelow(
6891 const sp<WindowInfoHandle>& windowHandle) const {
6892 const std::vector<sp<WindowInfoHandle>>& windowHandles =
6893 getWindowHandlesLocked(windowHandle->getInfo()->displayId);
6894 bool foundWindow = false;
6895 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
6896 if (!foundWindow && otherHandle != windowHandle) {
6897 continue;
6898 }
6899 if (windowHandle == otherHandle) {
6900 foundWindow = true;
6901 continue;
6902 }
6903
6904 if (otherHandle->getInfo()->inputConfig.test(WindowInfo::InputConfig::IS_WALLPAPER)) {
6905 return otherHandle;
6906 }
6907 }
6908 return nullptr;
6909}
6910
Nergi Rahardi730cf3c2023-04-13 12:41:17 +09006911void InputDispatcher::setKeyRepeatConfiguration(nsecs_t timeout, nsecs_t delay) {
6912 std::scoped_lock _l(mLock);
6913
6914 mConfig.keyRepeatTimeout = timeout;
6915 mConfig.keyRepeatDelay = delay;
6916}
6917
Garfield Tane84e6f92019-08-29 17:28:41 -07006918} // namespace android::inputdispatcher