blob: 34e019e0521ea8c8128fe76244fed50769df8121 [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 Vishniakou6773db62023-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 Vishniakou63b63612023-04-12 11:00:23 -0700122inline const std::string binderToString(const sp<IBinder>& binder) {
Bernardo Rufino49d99e42021-01-18 15:16:59 +0000123 if (binder == nullptr) {
124 return "<null>";
125 }
126 return StringPrintf("%p", binder.get());
127}
128
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +0000129static std::string uidString(const gui::Uid& uid) {
130 return uid.toString();
131}
132
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000133inline int32_t getMotionEventActionPointerIndex(int32_t action) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700134 return (action & AMOTION_EVENT_ACTION_POINTER_INDEX_MASK) >>
135 AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800136}
137
Siarhei Vishniakou6773db62023-04-21 11:30:20 -0700138Result<void> checkKeyAction(int32_t action) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800139 switch (action) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700140 case AKEY_EVENT_ACTION_DOWN:
141 case AKEY_EVENT_ACTION_UP:
Siarhei Vishniakou6773db62023-04-21 11:30:20 -0700142 return {};
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700143 default:
Siarhei Vishniakou6773db62023-04-21 11:30:20 -0700144 return Error() << "Key event has invalid action code " << action;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800145 }
146}
147
Siarhei Vishniakou6773db62023-04-21 11:30:20 -0700148Result<void> validateKeyEvent(int32_t action) {
149 return checkKeyAction(action);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800150}
151
Siarhei Vishniakou6773db62023-04-21 11:30:20 -0700152Result<void> checkMotionAction(int32_t action, int32_t actionButton, int32_t pointerCount) {
Siarhei Vishniakou2f61bdc2022-12-02 08:55:51 -0800153 switch (MotionEvent::getActionMasked(action)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700154 case AMOTION_EVENT_ACTION_DOWN:
Siarhei Vishniakou6773db62023-04-21 11:30:20 -0700155 case AMOTION_EVENT_ACTION_UP: {
156 if (pointerCount != 1) {
157 return Error() << "invalid pointer count " << pointerCount;
158 }
159 return {};
160 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700161 case AMOTION_EVENT_ACTION_MOVE:
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700162 case AMOTION_EVENT_ACTION_HOVER_ENTER:
163 case AMOTION_EVENT_ACTION_HOVER_MOVE:
Siarhei Vishniakou6773db62023-04-21 11:30:20 -0700164 case AMOTION_EVENT_ACTION_HOVER_EXIT: {
165 if (pointerCount < 1) {
166 return Error() << "invalid pointer count " << pointerCount;
167 }
168 return {};
169 }
Siarhei Vishniakou2f61bdc2022-12-02 08:55:51 -0800170 case AMOTION_EVENT_ACTION_CANCEL:
171 case AMOTION_EVENT_ACTION_OUTSIDE:
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700172 case AMOTION_EVENT_ACTION_SCROLL:
Siarhei Vishniakou6773db62023-04-21 11:30:20 -0700173 return {};
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700174 case AMOTION_EVENT_ACTION_POINTER_DOWN:
175 case AMOTION_EVENT_ACTION_POINTER_UP: {
Siarhei Vishniakou2f61bdc2022-12-02 08:55:51 -0800176 const int32_t index = MotionEvent::getActionIndex(action);
Siarhei Vishniakou6773db62023-04-21 11:30:20 -0700177 if (index < 0) {
178 return Error() << "invalid index " << index << " for "
179 << MotionEvent::actionToString(action);
180 }
181 if (index >= pointerCount) {
182 return Error() << "invalid index " << index << " for pointerCount " << pointerCount;
183 }
184 if (pointerCount <= 1) {
185 return Error() << "invalid pointer count " << pointerCount << " for "
186 << MotionEvent::actionToString(action);
187 }
188 return {};
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700189 }
190 case AMOTION_EVENT_ACTION_BUTTON_PRESS:
Siarhei Vishniakou6773db62023-04-21 11:30:20 -0700191 case AMOTION_EVENT_ACTION_BUTTON_RELEASE: {
192 if (actionButton == 0) {
193 return Error() << "action button should be nonzero for "
194 << MotionEvent::actionToString(action);
195 }
196 return {};
197 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700198 default:
Siarhei Vishniakou6773db62023-04-21 11:30:20 -0700199 return Error() << "invalid action " << action;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800200 }
201}
202
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000203int64_t millis(std::chrono::nanoseconds t) {
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -0500204 return std::chrono::duration_cast<std::chrono::milliseconds>(t).count();
205}
206
Siarhei Vishniakou6773db62023-04-21 11:30:20 -0700207Result<void> validateMotionEvent(int32_t action, int32_t actionButton, size_t pointerCount,
208 const PointerProperties* pointerProperties) {
209 Result<void> actionCheck = checkMotionAction(action, actionButton, pointerCount);
210 if (!actionCheck.ok()) {
211 return actionCheck;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800212 }
213 if (pointerCount < 1 || pointerCount > MAX_POINTERS) {
Siarhei Vishniakou6773db62023-04-21 11:30:20 -0700214 return Error() << "Motion event has invalid pointer count " << pointerCount
215 << "; value must be between 1 and " << MAX_POINTERS << ".";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800216 }
Siarhei Vishniakou8a878352023-01-30 14:05:01 -0800217 std::bitset<MAX_POINTER_ID + 1> pointerIdBits;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800218 for (size_t i = 0; i < pointerCount; i++) {
219 int32_t id = pointerProperties[i].id;
220 if (id < 0 || id > MAX_POINTER_ID) {
Siarhei Vishniakou6773db62023-04-21 11:30:20 -0700221 return Error() << "Motion event has invalid pointer id " << id
222 << "; value must be between 0 and " << MAX_POINTER_ID;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800223 }
Siarhei Vishniakou8a878352023-01-30 14:05:01 -0800224 if (pointerIdBits.test(id)) {
Siarhei Vishniakou6773db62023-04-21 11:30:20 -0700225 return Error() << "Motion event has duplicate pointer id " << id;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800226 }
Siarhei Vishniakou8a878352023-01-30 14:05:01 -0800227 pointerIdBits.set(id);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800228 }
Siarhei Vishniakou6773db62023-04-21 11:30:20 -0700229 return {};
230}
231
232Result<void> validateInputEvent(const InputEvent& event) {
233 switch (event.getType()) {
234 case InputEventType::KEY: {
235 const KeyEvent& key = static_cast<const KeyEvent&>(event);
236 const int32_t action = key.getAction();
237 return validateKeyEvent(action);
238 }
239 case InputEventType::MOTION: {
240 const MotionEvent& motion = static_cast<const MotionEvent&>(event);
241 const int32_t action = motion.getAction();
242 const size_t pointerCount = motion.getPointerCount();
243 const PointerProperties* pointerProperties = motion.getPointerProperties();
244 const int32_t actionButton = motion.getActionButton();
245 return validateMotionEvent(action, actionButton, pointerCount, pointerProperties);
246 }
247 default: {
248 return {};
249 }
250 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800251}
252
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000253std::string dumpRegion(const Region& region) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800254 if (region.isEmpty()) {
Bernardo Rufino53fc31e2020-11-03 11:01:07 +0000255 return "<empty>";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800256 }
257
Bernardo Rufino53fc31e2020-11-03 11:01:07 +0000258 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800259 bool first = true;
260 Region::const_iterator cur = region.begin();
261 Region::const_iterator const tail = region.end();
262 while (cur != tail) {
263 if (first) {
264 first = false;
265 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800266 dump += "|";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800267 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800268 dump += StringPrintf("[%d,%d][%d,%d]", cur->left, cur->top, cur->right, cur->bottom);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800269 cur++;
270 }
Bernardo Rufino53fc31e2020-11-03 11:01:07 +0000271 return dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800272}
273
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000274std::string dumpQueue(const std::deque<DispatchEntry*>& queue, nsecs_t currentTime) {
Siarhei Vishniakou14411c92020-09-18 21:15:05 -0500275 constexpr size_t maxEntries = 50; // max events to print
276 constexpr size_t skipBegin = maxEntries / 2;
277 const size_t skipEnd = queue.size() - maxEntries / 2;
278 // skip from maxEntries / 2 ... size() - maxEntries/2
279 // only print from 0 .. skipBegin and then from skipEnd .. size()
280
281 std::string dump;
282 for (size_t i = 0; i < queue.size(); i++) {
283 const DispatchEntry& entry = *queue[i];
284 if (i >= skipBegin && i < skipEnd) {
285 dump += StringPrintf(INDENT4 "<skipped %zu entries>\n", skipEnd - skipBegin);
286 i = skipEnd - 1; // it will be incremented to "skipEnd" by 'continue'
287 continue;
288 }
289 dump.append(INDENT4);
290 dump += entry.eventEntry->getDescription();
Siarhei Vishniakou253f4642022-11-09 13:42:06 -0800291 dump += StringPrintf(", seq=%" PRIu32 ", targetFlags=%s, resolvedAction=%d, age=%" PRId64
292 "ms",
293 entry.seq, entry.targetFlags.string().c_str(), entry.resolvedAction,
Siarhei Vishniakou14411c92020-09-18 21:15:05 -0500294 ns2ms(currentTime - entry.eventEntry->eventTime));
295 if (entry.deliveryTime != 0) {
296 // This entry was delivered, so add information on how long we've been waiting
297 dump += StringPrintf(", wait=%" PRId64 "ms", ns2ms(currentTime - entry.deliveryTime));
298 }
299 dump.append("\n");
300 }
301 return dump;
302}
303
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -0700304/**
305 * Find the entry in std::unordered_map by key, and return it.
306 * If the entry is not found, return a default constructed entry.
307 *
308 * Useful when the entries are vectors, since an empty vector will be returned
309 * if the entry is not found.
310 * Also useful when the entries are sp<>. If an entry is not found, nullptr is returned.
311 */
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700312template <typename K, typename V>
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000313V getValueByKey(const std::unordered_map<K, V>& map, K key) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -0700314 auto it = map.find(key);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700315 return it != map.end() ? it->second : V{};
Tiger Huang721e26f2018-07-24 22:26:19 +0800316}
317
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000318bool haveSameToken(const sp<WindowInfoHandle>& first, const sp<WindowInfoHandle>& second) {
chaviwaf87b3e2019-10-01 16:59:28 -0700319 if (first == second) {
320 return true;
321 }
322
323 if (first == nullptr || second == nullptr) {
324 return false;
325 }
326
327 return first->getToken() == second->getToken();
328}
329
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000330bool haveSameApplicationToken(const WindowInfo* first, const WindowInfo* second) {
Bernardo Rufino1ff9d592021-01-18 16:58:57 +0000331 if (first == nullptr || second == nullptr) {
332 return false;
333 }
334 return first->applicationInfo.token != nullptr &&
335 first->applicationInfo.token == second->applicationInfo.token;
336}
337
Siarhei Vishniakou8a878352023-01-30 14:05:01 -0800338template <typename T>
339size_t firstMarkedBit(T set) {
340 // TODO: replace with std::countr_zero from <bit> when that's available
341 LOG_ALWAYS_FATAL_IF(set.none());
342 size_t i = 0;
343 while (!set.test(i)) {
344 i++;
345 }
346 return i;
347}
348
Siarhei Vishniakou253f4642022-11-09 13:42:06 -0800349std::unique_ptr<DispatchEntry> createDispatchEntry(
350 const InputTarget& inputTarget, std::shared_ptr<EventEntry> eventEntry,
351 ftl::Flags<InputTarget::Flags> inputTargetFlags) {
chaviw1ff3d1e2020-07-01 15:53:47 -0700352 if (inputTarget.useDefaultPointerTransform()) {
353 const ui::Transform& transform = inputTarget.getDefaultPointerTransform();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700354 return std::make_unique<DispatchEntry>(eventEntry, inputTargetFlags, transform,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700355 inputTarget.displayTransform,
356 inputTarget.globalScaleFactor);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000357 }
358
359 ALOG_ASSERT(eventEntry->type == EventEntry::Type::MOTION);
360 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(*eventEntry);
361
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700362 std::vector<PointerCoords> pointerCoords;
363 pointerCoords.resize(motionEntry.pointerCount);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000364
365 // Use the first pointer information to normalize all other pointers. This could be any pointer
366 // as long as all other pointers are normalized to the same value and the final DispatchEntry
chaviw1ff3d1e2020-07-01 15:53:47 -0700367 // uses the transform for the normalized pointer.
368 const ui::Transform& firstPointerTransform =
Siarhei Vishniakou8a878352023-01-30 14:05:01 -0800369 inputTarget.pointerTransforms[firstMarkedBit(inputTarget.pointerIds)];
chaviw1ff3d1e2020-07-01 15:53:47 -0700370 ui::Transform inverseFirstTransform = firstPointerTransform.inverse();
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000371
372 // Iterate through all pointers in the event to normalize against the first.
373 for (uint32_t pointerIndex = 0; pointerIndex < motionEntry.pointerCount; pointerIndex++) {
374 const PointerProperties& pointerProperties = motionEntry.pointerProperties[pointerIndex];
375 uint32_t pointerId = uint32_t(pointerProperties.id);
chaviw1ff3d1e2020-07-01 15:53:47 -0700376 const ui::Transform& currTransform = inputTarget.pointerTransforms[pointerId];
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000377
378 pointerCoords[pointerIndex].copyFrom(motionEntry.pointerCoords[pointerIndex]);
chaviw1ff3d1e2020-07-01 15:53:47 -0700379 // First, apply the current pointer's transform to update the coordinates into
380 // window space.
381 pointerCoords[pointerIndex].transform(currTransform);
382 // Next, apply the inverse transform of the normalized coordinates so the
383 // current coordinates are transformed into the normalized coordinate space.
384 pointerCoords[pointerIndex].transform(inverseFirstTransform);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000385 }
386
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700387 std::unique_ptr<MotionEntry> combinedMotionEntry =
388 std::make_unique<MotionEntry>(motionEntry.id, motionEntry.eventTime,
389 motionEntry.deviceId, motionEntry.source,
390 motionEntry.displayId, motionEntry.policyFlags,
391 motionEntry.action, motionEntry.actionButton,
392 motionEntry.flags, motionEntry.metaState,
393 motionEntry.buttonState, motionEntry.classification,
394 motionEntry.edgeFlags, motionEntry.xPrecision,
395 motionEntry.yPrecision, motionEntry.xCursorPosition,
396 motionEntry.yCursorPosition, motionEntry.downTime,
397 motionEntry.pointerCount, motionEntry.pointerProperties,
Prabir Pradhan5beda762021-12-10 09:30:08 +0000398 pointerCoords.data());
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000399
400 if (motionEntry.injectionState) {
401 combinedMotionEntry->injectionState = motionEntry.injectionState;
402 combinedMotionEntry->injectionState->refCount += 1;
403 }
404
405 std::unique_ptr<DispatchEntry> dispatchEntry =
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700406 std::make_unique<DispatchEntry>(std::move(combinedMotionEntry), inputTargetFlags,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700407 firstPointerTransform, inputTarget.displayTransform,
408 inputTarget.globalScaleFactor);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000409 return dispatchEntry;
410}
411
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000412status_t openInputChannelPair(const std::string& name, std::shared_ptr<InputChannel>& serverChannel,
413 std::unique_ptr<InputChannel>& clientChannel) {
Garfield Tan15601662020-09-22 15:32:38 -0700414 std::unique_ptr<InputChannel> uniqueServerChannel;
415 status_t result = InputChannel::openInputChannelPair(name, uniqueServerChannel, clientChannel);
416
417 serverChannel = std::move(uniqueServerChannel);
418 return result;
419}
420
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -0500421template <typename T>
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000422bool sharedPointersEqual(const std::shared_ptr<T>& lhs, const std::shared_ptr<T>& rhs) {
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -0500423 if (lhs == nullptr && rhs == nullptr) {
424 return true;
425 }
426 if (lhs == nullptr || rhs == nullptr) {
427 return false;
428 }
429 return *lhs == *rhs;
430}
431
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000432KeyEvent createKeyEvent(const KeyEntry& entry) {
Siarhei Vishniakou2e2ea992020-12-15 02:57:19 +0000433 KeyEvent event;
434 event.initialize(entry.id, entry.deviceId, entry.source, entry.displayId, INVALID_HMAC,
435 entry.action, entry.flags, entry.keyCode, entry.scanCode, entry.metaState,
436 entry.repeatCount, entry.downTime, entry.eventTime);
437 return event;
438}
439
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000440bool shouldReportMetricsForConnection(const Connection& connection) {
Siarhei Vishniakouf2652122021-03-05 21:39:46 +0000441 // Do not keep track of gesture monitors. They receive every event and would disproportionately
442 // affect the statistics.
443 if (connection.monitor) {
444 return false;
445 }
446 // If the connection is experiencing ANR, let's skip it. We have separate ANR metrics
447 if (!connection.responsive) {
448 return false;
449 }
450 return true;
451}
452
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000453bool shouldReportFinishedEvent(const DispatchEntry& dispatchEntry, const Connection& connection) {
Siarhei Vishniakouf2652122021-03-05 21:39:46 +0000454 const EventEntry& eventEntry = *dispatchEntry.eventEntry;
455 const int32_t& inputEventId = eventEntry.id;
456 if (inputEventId != dispatchEntry.resolvedEventId) {
457 // Event was transmuted
458 return false;
459 }
460 if (inputEventId == android::os::IInputConstants::INVALID_INPUT_EVENT_ID) {
461 return false;
462 }
463 // Only track latency for events that originated from hardware
464 if (eventEntry.isSynthesized()) {
465 return false;
466 }
467 const EventEntry::Type& inputEventEntryType = eventEntry.type;
468 if (inputEventEntryType == EventEntry::Type::KEY) {
469 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
470 if (keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) {
471 return false;
472 }
473 } else if (inputEventEntryType == EventEntry::Type::MOTION) {
474 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
475 if (motionEntry.action == AMOTION_EVENT_ACTION_CANCEL ||
476 motionEntry.action == AMOTION_EVENT_ACTION_HOVER_EXIT) {
477 return false;
478 }
479 } else {
480 // Not a key or a motion
481 return false;
482 }
483 if (!shouldReportMetricsForConnection(connection)) {
484 return false;
485 }
486 return true;
487}
488
Prabir Pradhancef936d2021-07-21 16:17:52 +0000489/**
490 * Connection is responsive if it has no events in the waitQueue that are older than the
491 * current time.
492 */
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000493bool isConnectionResponsive(const Connection& connection) {
Prabir Pradhancef936d2021-07-21 16:17:52 +0000494 const nsecs_t currentTime = now();
495 for (const DispatchEntry* entry : connection.waitQueue) {
496 if (entry->timeoutTime < currentTime) {
497 return false;
498 }
499 }
500 return true;
501}
502
Antonio Kantekf16f2832021-09-28 04:39:20 +0000503// Returns true if the event type passed as argument represents a user activity.
504bool isUserActivityEvent(const EventEntry& eventEntry) {
505 switch (eventEntry.type) {
Josep del Riob3981622023-04-18 15:49:45 +0000506 case EventEntry::Type::CONFIGURATION_CHANGED:
507 case EventEntry::Type::DEVICE_RESET:
508 case EventEntry::Type::DRAG:
Antonio Kantekf16f2832021-09-28 04:39:20 +0000509 case EventEntry::Type::FOCUS:
510 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
Antonio Kantekf16f2832021-09-28 04:39:20 +0000511 case EventEntry::Type::SENSOR:
Josep del Riob3981622023-04-18 15:49:45 +0000512 case EventEntry::Type::TOUCH_MODE_CHANGED:
Antonio Kantekf16f2832021-09-28 04:39:20 +0000513 return false;
Antonio Kantekf16f2832021-09-28 04:39:20 +0000514 case EventEntry::Type::KEY:
515 case EventEntry::Type::MOTION:
516 return true;
517 }
518}
519
Prabir Pradhan3f90d312021-11-19 03:57:24 -0800520// Returns true if the given window can accept pointer events at the given display location.
Prabir Pradhan82e081e2022-12-06 09:50:09 +0000521bool windowAcceptsTouchAt(const WindowInfo& windowInfo, int32_t displayId, float x, float y,
Prabir Pradhan33e3baa2022-12-06 20:30:22 +0000522 bool isStylus, const ui::Transform& displayTransform) {
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -0800523 const auto inputConfig = windowInfo.inputConfig;
524 if (windowInfo.displayId != displayId ||
525 inputConfig.test(WindowInfo::InputConfig::NOT_VISIBLE)) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -0800526 return false;
527 }
Prabir Pradhand65552b2021-10-07 11:23:50 -0700528 const bool windowCanInterceptTouch = isStylus && windowInfo.interceptsStylus();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -0800529 if (inputConfig.test(WindowInfo::InputConfig::NOT_TOUCHABLE) && !windowCanInterceptTouch) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -0800530 return false;
531 }
Prabir Pradhan33e3baa2022-12-06 20:30:22 +0000532
533 // Window Manager works in the logical display coordinate space. When it specifies bounds for a
534 // window as (l, t, r, b), the range of x in [l, r) and y in [t, b) are considered to be inside
535 // the window. Points on the right and bottom edges should not be inside the window, so we need
536 // to be careful about performing a hit test when the display is rotated, since the "right" and
537 // "bottom" of the window will be different in the display (un-rotated) space compared to in the
538 // logical display in which WM determined the bounds. Perform the hit test in the logical
539 // display space to ensure these edges are considered correctly in all orientations.
540 const auto touchableRegion = displayTransform.transform(windowInfo.touchableRegion);
541 const auto p = displayTransform.transform(x, y);
542 if (!touchableRegion.contains(std::floor(p.x), std::floor(p.y))) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -0800543 return false;
544 }
545 return true;
546}
547
Prabir Pradhand65552b2021-10-07 11:23:50 -0700548bool isPointerFromStylus(const MotionEntry& entry, int32_t pointerIndex) {
549 return isFromSource(entry.source, AINPUT_SOURCE_STYLUS) &&
Prabir Pradhane5626962022-10-27 20:30:53 +0000550 isStylusToolType(entry.pointerProperties[pointerIndex].toolType);
Prabir Pradhand65552b2021-10-07 11:23:50 -0700551}
552
Siarhei Vishniakou253f4642022-11-09 13:42:06 -0800553// Determines if the given window can be targeted as InputTarget::Flags::FOREGROUND.
Prabir Pradhan6dfbf262022-03-14 15:24:30 +0000554// Foreground events are only sent to "foreground targetable" windows, but not all gestures sent to
555// such window are necessarily targeted with the flag. For example, an event with ACTION_OUTSIDE can
556// be sent to such a window, but it is not a foreground event and doesn't use
Siarhei Vishniakou253f4642022-11-09 13:42:06 -0800557// InputTarget::Flags::FOREGROUND.
Prabir Pradhan6dfbf262022-03-14 15:24:30 +0000558bool canReceiveForegroundTouches(const WindowInfo& info) {
559 // A non-touchable window can still receive touch events (e.g. in the case of
560 // STYLUS_INTERCEPTOR), so prevent such windows from receiving foreground events for touches.
561 return !info.inputConfig.test(gui::WindowInfo::InputConfig::NOT_TOUCHABLE) && !info.isSpy();
562}
563
Prabir Pradhane59c6dc2023-06-13 19:53:03 +0000564bool isWindowOwnedBy(const sp<WindowInfoHandle>& windowHandle, gui::Pid pid, gui::Uid uid) {
Antonio Kantek48710e42022-03-24 14:19:30 -0700565 if (windowHandle == nullptr) {
566 return false;
567 }
568 const WindowInfo* windowInfo = windowHandle->getInfo();
569 if (pid == windowInfo->ownerPid && uid == windowInfo->ownerUid) {
570 return true;
571 }
572 return false;
573}
574
Prabir Pradhan5735a322022-04-11 17:23:34 +0000575// Checks targeted injection using the window's owner's uid.
576// Returns an empty string if an entry can be sent to the given window, or an error message if the
577// entry is a targeted injection whose uid target doesn't match the window owner.
578std::optional<std::string> verifyTargetedInjection(const sp<WindowInfoHandle>& window,
579 const EventEntry& entry) {
580 if (entry.injectionState == nullptr || !entry.injectionState->targetUid) {
581 // The event was not injected, or the injected event does not target a window.
582 return {};
583 }
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +0000584 const auto uid = *entry.injectionState->targetUid;
Prabir Pradhan5735a322022-04-11 17:23:34 +0000585 if (window == nullptr) {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +0000586 return StringPrintf("No valid window target for injection into uid %s.",
587 uid.toString().c_str());
Prabir Pradhan5735a322022-04-11 17:23:34 +0000588 }
589 if (entry.injectionState->targetUid != window->getInfo()->ownerUid) {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +0000590 return StringPrintf("Injected event targeted at uid %s would be dispatched to window '%s' "
591 "owned by uid %s.",
592 uid.toString().c_str(), window->getName().c_str(),
593 window->getInfo()->ownerUid.toString().c_str());
Prabir Pradhan5735a322022-04-11 17:23:34 +0000594 }
595 return {};
596}
597
Prabir Pradhan82e081e2022-12-06 09:50:09 +0000598std::pair<float, float> resolveTouchedPosition(const MotionEntry& entry) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -0700599 const bool isFromMouse = isFromSource(entry.source, AINPUT_SOURCE_MOUSE);
600 // Always dispatch mouse events to cursor position.
601 if (isFromMouse) {
Prabir Pradhan82e081e2022-12-06 09:50:09 +0000602 return {entry.xCursorPosition, entry.yCursorPosition};
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -0700603 }
604
605 const int32_t pointerIndex = getMotionEventActionPointerIndex(entry.action);
Prabir Pradhan82e081e2022-12-06 09:50:09 +0000606 return {entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_X),
607 entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_Y)};
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -0700608}
609
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -0700610std::optional<nsecs_t> getDownTime(const EventEntry& eventEntry) {
611 if (eventEntry.type == EventEntry::Type::KEY) {
612 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
613 return keyEntry.downTime;
614 } else if (eventEntry.type == EventEntry::Type::MOTION) {
615 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
616 return motionEntry.downTime;
617 }
618 return std::nullopt;
619}
620
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000621/**
622 * Compare the old touch state to the new touch state, and generate the corresponding touched
623 * windows (== input targets).
624 * If a window had the hovering pointer, but now it doesn't, produce HOVER_EXIT for that window.
625 * If the pointer just entered the new window, produce HOVER_ENTER.
626 * For pointers remaining in the window, produce HOVER_MOVE.
627 */
628std::vector<TouchedWindow> getHoveringWindowsLocked(const TouchState* oldState,
629 const TouchState& newTouchState,
630 const MotionEntry& entry) {
631 std::vector<TouchedWindow> out;
632 const int32_t maskedAction = MotionEvent::getActionMasked(entry.action);
633 if (maskedAction != AMOTION_EVENT_ACTION_HOVER_ENTER &&
634 maskedAction != AMOTION_EVENT_ACTION_HOVER_MOVE &&
635 maskedAction != AMOTION_EVENT_ACTION_HOVER_EXIT) {
636 // Not a hover event - don't need to do anything
637 return out;
638 }
639
640 // We should consider all hovering pointers here. But for now, just use the first one
641 const int32_t pointerId = entry.pointerProperties[0].id;
642
643 std::set<sp<WindowInfoHandle>> oldWindows;
644 if (oldState != nullptr) {
645 oldWindows = oldState->getWindowsWithHoveringPointer(entry.deviceId, pointerId);
646 }
647
648 std::set<sp<WindowInfoHandle>> newWindows =
649 newTouchState.getWindowsWithHoveringPointer(entry.deviceId, pointerId);
650
651 // If the pointer is no longer in the new window set, send HOVER_EXIT.
652 for (const sp<WindowInfoHandle>& oldWindow : oldWindows) {
653 if (newWindows.find(oldWindow) == newWindows.end()) {
654 TouchedWindow touchedWindow;
655 touchedWindow.windowHandle = oldWindow;
656 touchedWindow.targetFlags = InputTarget::Flags::DISPATCH_AS_HOVER_EXIT;
Siarhei Vishniakou8a878352023-01-30 14:05:01 -0800657 touchedWindow.pointerIds.set(pointerId);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000658 out.push_back(touchedWindow);
659 }
660 }
661
662 for (const sp<WindowInfoHandle>& newWindow : newWindows) {
663 TouchedWindow touchedWindow;
664 touchedWindow.windowHandle = newWindow;
665 if (oldWindows.find(newWindow) == oldWindows.end()) {
666 // Any windows that have this pointer now, and didn't have it before, should get
667 // HOVER_ENTER
668 touchedWindow.targetFlags = InputTarget::Flags::DISPATCH_AS_HOVER_ENTER;
669 } else {
670 // This pointer was already sent to the window. Use ACTION_HOVER_MOVE.
Siarhei Vishniakouc2eb8502023-04-11 18:33:36 -0700671 if (CC_UNLIKELY(maskedAction != AMOTION_EVENT_ACTION_HOVER_MOVE)) {
672 LOG(FATAL) << "Expected ACTION_HOVER_MOVE instead of " << entry.getDescription();
673 }
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000674 touchedWindow.targetFlags = InputTarget::Flags::DISPATCH_AS_IS;
675 }
Siarhei Vishniakou8a878352023-01-30 14:05:01 -0800676 touchedWindow.pointerIds.set(pointerId);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000677 if (canReceiveForegroundTouches(*newWindow->getInfo())) {
678 touchedWindow.targetFlags |= InputTarget::Flags::FOREGROUND;
679 }
680 out.push_back(touchedWindow);
681 }
682 return out;
683}
684
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -0800685template <typename T>
686std::vector<T>& operator+=(std::vector<T>& left, const std::vector<T>& right) {
687 left.insert(left.end(), right.begin(), right.end());
688 return left;
689}
690
Harry Cuttsb166c002023-05-09 13:06:05 +0000691// Filter windows in a TouchState and targets in a vector to remove untrusted windows/targets from
692// both.
693void filterUntrustedTargets(TouchState& touchState, std::vector<InputTarget>& targets) {
694 std::erase_if(touchState.windows, [&](const TouchedWindow& window) {
695 if (!window.windowHandle->getInfo()->inputConfig.test(
696 WindowInfo::InputConfig::TRUSTED_OVERLAY)) {
697 // In addition to TouchState, erase this window from the input targets! We don't have a
698 // good way to do this today except by adding a nested loop.
699 // TODO(b/282025641): simplify this code once InputTargets are being identified
700 // separately from TouchedWindows.
701 std::erase_if(targets, [&](const InputTarget& target) {
702 return target.inputChannel->getConnectionToken() == window.windowHandle->getToken();
703 });
704 return true;
705 }
706 return false;
707 });
708}
709
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000710} // namespace
711
Michael Wrightd02c5b62014-02-10 15:10:22 -0800712// --- InputDispatcher ---
713
Prabir Pradhana41d2442023-04-20 21:30:40 +0000714InputDispatcher::InputDispatcher(InputDispatcherPolicyInterface& policy)
Siarhei Vishniakou289e9242022-02-15 14:50:16 -0800715 : InputDispatcher(policy, STALE_EVENT_TIMEOUT) {}
716
Prabir Pradhana41d2442023-04-20 21:30:40 +0000717InputDispatcher::InputDispatcher(InputDispatcherPolicyInterface& policy,
Siarhei Vishniakou289e9242022-02-15 14:50:16 -0800718 std::chrono::nanoseconds staleEventTimeout)
Garfield Tan00f511d2019-06-12 16:55:40 -0700719 : mPolicy(policy),
720 mPendingEvent(nullptr),
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700721 mLastDropReason(DropReason::NOT_DROPPED),
Garfield Tanff1f1bb2020-01-28 13:24:04 -0800722 mIdGenerator(IdGenerator::Source::INPUT_DISPATCHER),
Garfield Tan00f511d2019-06-12 16:55:40 -0700723 mAppSwitchSawKeyDown(false),
Colin Cross5b799302022-10-18 21:52:41 -0700724 mAppSwitchDueTime(LLONG_MAX),
Garfield Tan00f511d2019-06-12 16:55:40 -0700725 mNextUnblockedEvent(nullptr),
Prabir Pradhan1376fcd2022-01-21 09:56:35 -0800726 mMonitorDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT),
Garfield Tan00f511d2019-06-12 16:55:40 -0700727 mDispatchEnabled(false),
728 mDispatchFrozen(false),
729 mInputFilterEnabled(false),
Bernardo Rufinoea97d182020-08-19 14:43:14 +0100730 mMaximumObscuringOpacityForTouch(1.0f),
Siarhei Vishniakou2508b872020-12-03 16:33:53 -1000731 mFocusedDisplayId(ADISPLAY_ID_DEFAULT),
Prabir Pradhan99987712020-11-10 18:43:05 -0800732 mWindowTokenWithPointerCapture(nullptr),
Siarhei Vishniakou289e9242022-02-15 14:50:16 -0800733 mStaleEventTimeout(staleEventTimeout),
Siarhei Vishniakoua04181f2021-03-26 05:56:49 +0000734 mLatencyAggregator(),
Antonio Kantek15beb512022-06-13 22:35:41 +0000735 mLatencyTracker(&mLatencyAggregator) {
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -0700736 mLooper = sp<Looper>::make(false);
Prabir Pradhanf93562f2018-11-29 12:13:37 -0800737 mReporter = createInputReporter();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800738
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -0700739 mWindowInfoListener = sp<DispatcherWindowListener>::make(*this);
Siarhei Vishniakou31977182022-09-30 08:51:23 -0700740#if defined(__ANDROID__)
Siarhei Vishniakou18050092021-09-01 13:32:49 -0700741 SurfaceComposerClient::getDefault()->addWindowInfosListener(mWindowInfoListener);
Siarhei Vishniakou31977182022-09-30 08:51:23 -0700742#endif
Yi Kong9b14ac62018-07-17 13:48:38 -0700743 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800744}
745
746InputDispatcher::~InputDispatcher() {
Prabir Pradhancef936d2021-07-21 16:17:52 +0000747 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800748
Prabir Pradhancef936d2021-07-21 16:17:52 +0000749 resetKeyRepeatLocked();
750 releasePendingEventLocked();
751 drainInboundQueueLocked();
752 mCommandQueue.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800753
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +0000754 while (!mConnectionsByToken.empty()) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -0700755 std::shared_ptr<Connection> connection = mConnectionsByToken.begin()->second;
Harry Cutts33476232023-01-30 19:57:29 +0000756 removeInputChannelLocked(connection->inputChannel->getConnectionToken(), /*notify=*/false);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800757 }
758}
759
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700760status_t InputDispatcher::start() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700761 if (mThread) {
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700762 return ALREADY_EXISTS;
763 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700764 mThread = std::make_unique<InputThread>(
765 "InputDispatcher", [this]() { dispatchOnce(); }, [this]() { mLooper->wake(); });
766 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700767}
768
769status_t InputDispatcher::stop() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700770 if (mThread && mThread->isCallingThread()) {
771 ALOGE("InputDispatcher cannot be stopped from its own thread!");
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700772 return INVALID_OPERATION;
773 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700774 mThread.reset();
775 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700776}
777
Michael Wrightd02c5b62014-02-10 15:10:22 -0800778void InputDispatcher::dispatchOnce() {
Colin Cross5b799302022-10-18 21:52:41 -0700779 nsecs_t nextWakeupTime = LLONG_MAX;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800780 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -0800781 std::scoped_lock _l(mLock);
782 mDispatcherIsAlive.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800783
784 // Run a dispatch loop if there are no pending commands.
785 // The dispatch loop might enqueue commands to run afterwards.
786 if (!haveCommandsLocked()) {
787 dispatchOnceInnerLocked(&nextWakeupTime);
788 }
789
790 // Run all pending commands if there are any.
791 // If any commands were run then force the next poll to wake up immediately.
Prabir Pradhancef936d2021-07-21 16:17:52 +0000792 if (runCommandsLockedInterruptable()) {
Colin Cross5b799302022-10-18 21:52:41 -0700793 nextWakeupTime = LLONG_MIN;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800794 }
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800795
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700796 // If we are still waiting for ack on some events,
797 // we might have to wake up earlier to check if an app is anr'ing.
798 const nsecs_t nextAnrCheck = processAnrsLocked();
799 nextWakeupTime = std::min(nextWakeupTime, nextAnrCheck);
800
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800801 // We are about to enter an infinitely long sleep, because we have no commands or
802 // pending or queued events
Colin Cross5b799302022-10-18 21:52:41 -0700803 if (nextWakeupTime == LLONG_MAX) {
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800804 mDispatcherEnteredIdle.notify_all();
805 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800806 } // release lock
807
808 // Wait for callback or timeout or wake. (make sure we round up, not down)
809 nsecs_t currentTime = now();
810 int timeoutMillis = toMillisecondTimeoutDelay(currentTime, nextWakeupTime);
811 mLooper->pollOnce(timeoutMillis);
812}
813
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700814/**
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500815 * Raise ANR if there is no focused window.
816 * Before the ANR is raised, do a final state check:
817 * 1. The currently focused application must be the same one we are waiting for.
818 * 2. Ensure we still don't have a focused window.
819 */
820void InputDispatcher::processNoFocusedWindowAnrLocked() {
821 // Check if the application that we are waiting for is still focused.
822 std::shared_ptr<InputApplicationHandle> focusedApplication =
823 getValueByKey(mFocusedApplicationHandlesByDisplay, mAwaitedApplicationDisplayId);
824 if (focusedApplication == nullptr ||
825 focusedApplication->getApplicationToken() !=
826 mAwaitedFocusedApplication->getApplicationToken()) {
827 // Unexpected because we should have reset the ANR timer when focused application changed
828 ALOGE("Waited for a focused window, but focused application has already changed to %s",
829 focusedApplication->getName().c_str());
830 return; // The focused application has changed.
831 }
832
chaviw98318de2021-05-19 16:45:23 -0500833 const sp<WindowInfoHandle>& focusedWindowHandle =
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500834 getFocusedWindowHandleLocked(mAwaitedApplicationDisplayId);
835 if (focusedWindowHandle != nullptr) {
836 return; // We now have a focused window. No need for ANR.
837 }
838 onAnrLocked(mAwaitedFocusedApplication);
839}
840
841/**
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700842 * Check if any of the connections' wait queues have events that are too old.
843 * If we waited for events to be ack'ed for more than the window timeout, raise an ANR.
844 * Return the time at which we should wake up next.
845 */
846nsecs_t InputDispatcher::processAnrsLocked() {
847 const nsecs_t currentTime = now();
Colin Cross5b799302022-10-18 21:52:41 -0700848 nsecs_t nextAnrCheck = LLONG_MAX;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700849 // Check if we are waiting for a focused window to appear. Raise ANR if waited too long
850 if (mNoFocusedWindowTimeoutTime.has_value() && mAwaitedFocusedApplication != nullptr) {
851 if (currentTime >= *mNoFocusedWindowTimeoutTime) {
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500852 processNoFocusedWindowAnrLocked();
Chris Yea209fde2020-07-22 13:54:51 -0700853 mAwaitedFocusedApplication.reset();
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500854 mNoFocusedWindowTimeoutTime = std::nullopt;
Colin Cross5b799302022-10-18 21:52:41 -0700855 return LLONG_MIN;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700856 } else {
Siarhei Vishniakou38a6d272020-10-20 20:29:33 -0500857 // Keep waiting. We will drop the event when mNoFocusedWindowTimeoutTime comes.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700858 nextAnrCheck = *mNoFocusedWindowTimeoutTime;
859 }
860 }
861
862 // Check if any connection ANRs are due
863 nextAnrCheck = std::min(nextAnrCheck, mAnrTracker.firstTimeout());
864 if (currentTime < nextAnrCheck) { // most likely scenario
865 return nextAnrCheck; // everything is normal. Let's check again at nextAnrCheck
866 }
867
868 // If we reached here, we have an unresponsive connection.
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -0700869 std::shared_ptr<Connection> connection = getConnectionLocked(mAnrTracker.firstToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700870 if (connection == nullptr) {
871 ALOGE("Could not find connection for entry %" PRId64, mAnrTracker.firstTimeout());
872 return nextAnrCheck;
873 }
874 connection->responsive = false;
875 // Stop waking up for this unresponsive connection
876 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000877 onAnrLocked(connection);
Colin Cross5b799302022-10-18 21:52:41 -0700878 return LLONG_MIN;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700879}
880
Prabir Pradhan1376fcd2022-01-21 09:56:35 -0800881std::chrono::nanoseconds InputDispatcher::getDispatchingTimeoutLocked(
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -0700882 const std::shared_ptr<Connection>& connection) {
Prabir Pradhan1376fcd2022-01-21 09:56:35 -0800883 if (connection->monitor) {
884 return mMonitorDispatchingTimeout;
885 }
886 const sp<WindowInfoHandle> window =
887 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700888 if (window != nullptr) {
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500889 return window->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700890 }
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500891 return DEFAULT_INPUT_DISPATCHING_TIMEOUT;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700892}
893
Michael Wrightd02c5b62014-02-10 15:10:22 -0800894void InputDispatcher::dispatchOnceInnerLocked(nsecs_t* nextWakeupTime) {
895 nsecs_t currentTime = now();
896
Jeff Browndc5992e2014-04-11 01:27:26 -0700897 // Reset the key repeat timer whenever normal dispatch is suspended while the
898 // device is in a non-interactive state. This is to ensure that we abort a key
899 // repeat if the device is just coming out of sleep.
900 if (!mDispatchEnabled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800901 resetKeyRepeatLocked();
902 }
903
904 // If dispatching is frozen, do not process timeouts or try to deliver any new events.
905 if (mDispatchFrozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +0100906 if (DEBUG_FOCUS) {
907 ALOGD("Dispatch frozen. Waiting some more.");
908 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800909 return;
910 }
911
912 // Optimize latency of app switches.
913 // Essentially we start a short timeout when an app switch key (HOME / ENDCALL) has
914 // been pressed. When it expires, we preempt dispatch and drop all other pending events.
915 bool isAppSwitchDue = mAppSwitchDueTime <= currentTime;
916 if (mAppSwitchDueTime < *nextWakeupTime) {
917 *nextWakeupTime = mAppSwitchDueTime;
918 }
919
920 // Ready to start a new event.
921 // If we don't already have a pending event, go grab one.
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700922 if (!mPendingEvent) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700923 if (mInboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800924 if (isAppSwitchDue) {
925 // The inbound queue is empty so the app switch key we were waiting
926 // for will never arrive. Stop waiting for it.
927 resetPendingAppSwitchLocked(false);
928 isAppSwitchDue = false;
929 }
930
931 // Synthesize a key repeat if appropriate.
932 if (mKeyRepeatState.lastKeyEntry) {
933 if (currentTime >= mKeyRepeatState.nextRepeatTime) {
934 mPendingEvent = synthesizeKeyRepeatLocked(currentTime);
935 } else {
936 if (mKeyRepeatState.nextRepeatTime < *nextWakeupTime) {
937 *nextWakeupTime = mKeyRepeatState.nextRepeatTime;
938 }
939 }
940 }
941
942 // Nothing to do if there is no pending event.
943 if (!mPendingEvent) {
944 return;
945 }
946 } else {
947 // Inbound queue has at least one entry.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700948 mPendingEvent = mInboundQueue.front();
949 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800950 traceInboundQueueLengthLocked();
951 }
952
953 // Poke user activity for this event.
954 if (mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700955 pokeUserActivityLocked(*mPendingEvent);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800956 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800957 }
958
959 // Now we have an event to dispatch.
960 // All events are eventually dequeued and processed this way, even if we intend to drop them.
Yi Kong9b14ac62018-07-17 13:48:38 -0700961 ALOG_ASSERT(mPendingEvent != nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800962 bool done = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700963 DropReason dropReason = DropReason::NOT_DROPPED;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800964 if (!(mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700965 dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800966 } else if (!mDispatchEnabled) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700967 dropReason = DropReason::DISABLED;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800968 }
969
970 if (mNextUnblockedEvent == mPendingEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -0700971 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800972 }
973
974 switch (mPendingEvent->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700975 case EventEntry::Type::CONFIGURATION_CHANGED: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700976 const ConfigurationChangedEntry& typedEntry =
977 static_cast<const ConfigurationChangedEntry&>(*mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700978 done = dispatchConfigurationChangedLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700979 dropReason = DropReason::NOT_DROPPED; // configuration changes are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700980 break;
981 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800982
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700983 case EventEntry::Type::DEVICE_RESET: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700984 const DeviceResetEntry& typedEntry =
985 static_cast<const DeviceResetEntry&>(*mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700986 done = dispatchDeviceResetLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700987 dropReason = DropReason::NOT_DROPPED; // device resets are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700988 break;
989 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800990
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100991 case EventEntry::Type::FOCUS: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700992 std::shared_ptr<FocusEntry> typedEntry =
993 std::static_pointer_cast<FocusEntry>(mPendingEvent);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100994 dispatchFocusLocked(currentTime, typedEntry);
995 done = true;
996 dropReason = DropReason::NOT_DROPPED; // focus events are never dropped
997 break;
998 }
999
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001000 case EventEntry::Type::TOUCH_MODE_CHANGED: {
1001 const auto typedEntry = std::static_pointer_cast<TouchModeEntry>(mPendingEvent);
1002 dispatchTouchModeChangeLocked(currentTime, typedEntry);
1003 done = true;
1004 dropReason = DropReason::NOT_DROPPED; // touch mode events are never dropped
1005 break;
1006 }
1007
Prabir Pradhan99987712020-11-10 18:43:05 -08001008 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
1009 const auto typedEntry =
1010 std::static_pointer_cast<PointerCaptureChangedEntry>(mPendingEvent);
1011 dispatchPointerCaptureChangedLocked(currentTime, typedEntry, dropReason);
1012 done = true;
1013 break;
1014 }
1015
arthurhungb89ccb02020-12-30 16:19:01 +08001016 case EventEntry::Type::DRAG: {
1017 std::shared_ptr<DragEntry> typedEntry =
1018 std::static_pointer_cast<DragEntry>(mPendingEvent);
1019 dispatchDragLocked(currentTime, typedEntry);
1020 done = true;
1021 break;
1022 }
1023
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001024 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001025 std::shared_ptr<KeyEntry> keyEntry = std::static_pointer_cast<KeyEntry>(mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001026 if (isAppSwitchDue) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001027 if (isAppSwitchKeyEvent(*keyEntry)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001028 resetPendingAppSwitchLocked(true);
1029 isAppSwitchDue = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001030 } else if (dropReason == DropReason::NOT_DROPPED) {
1031 dropReason = DropReason::APP_SWITCH;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001032 }
1033 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001034 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *keyEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001035 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001036 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001037 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
1038 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001039 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001040 done = dispatchKeyLocked(currentTime, keyEntry, &dropReason, nextWakeupTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001041 break;
1042 }
1043
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001044 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001045 std::shared_ptr<MotionEntry> motionEntry =
1046 std::static_pointer_cast<MotionEntry>(mPendingEvent);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001047 if (dropReason == DropReason::NOT_DROPPED && isAppSwitchDue) {
1048 dropReason = DropReason::APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001049 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001050 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *motionEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001051 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001052 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001053 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
1054 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001055 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001056 done = dispatchMotionLocked(currentTime, motionEntry, &dropReason, nextWakeupTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001057 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001058 }
Chris Yef59a2f42020-10-16 12:55:26 -07001059
1060 case EventEntry::Type::SENSOR: {
1061 std::shared_ptr<SensorEntry> sensorEntry =
1062 std::static_pointer_cast<SensorEntry>(mPendingEvent);
1063 if (dropReason == DropReason::NOT_DROPPED && isAppSwitchDue) {
1064 dropReason = DropReason::APP_SWITCH;
1065 }
1066 // Sensor timestamps use SYSTEM_TIME_BOOTTIME time base, so we can't use
1067 // 'currentTime' here, get SYSTEM_TIME_BOOTTIME instead.
1068 nsecs_t bootTime = systemTime(SYSTEM_TIME_BOOTTIME);
1069 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(bootTime, *sensorEntry)) {
1070 dropReason = DropReason::STALE;
1071 }
1072 dispatchSensorLocked(currentTime, sensorEntry, &dropReason, nextWakeupTime);
1073 done = true;
1074 break;
1075 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001076 }
1077
1078 if (done) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001079 if (dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001080 dropInboundEventLocked(*mPendingEvent, dropReason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001081 }
Michael Wright3a981722015-06-10 15:26:13 +01001082 mLastDropReason = dropReason;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001083
1084 releasePendingEventLocked();
Colin Cross5b799302022-10-18 21:52:41 -07001085 *nextWakeupTime = LLONG_MIN; // force next poll to wake up immediately
Michael Wrightd02c5b62014-02-10 15:10:22 -08001086 }
1087}
1088
Siarhei Vishniakou289e9242022-02-15 14:50:16 -08001089bool InputDispatcher::isStaleEvent(nsecs_t currentTime, const EventEntry& entry) {
1090 return std::chrono::nanoseconds(currentTime - entry.eventTime) >= mStaleEventTimeout;
1091}
1092
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001093/**
1094 * Return true if the events preceding this incoming motion event should be dropped
1095 * Return false otherwise (the default behaviour)
1096 */
1097bool InputDispatcher::shouldPruneInboundQueueLocked(const MotionEntry& motionEntry) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001098 const bool isPointerDownEvent = motionEntry.action == AMOTION_EVENT_ACTION_DOWN &&
Prabir Pradhanaa561d12021-09-24 06:57:33 -07001099 isFromSource(motionEntry.source, AINPUT_SOURCE_CLASS_POINTER);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001100
1101 // Optimize case where the current application is unresponsive and the user
1102 // decides to touch a window in a different application.
1103 // If the application takes too long to catch up then we drop all events preceding
1104 // the touch into the other window.
1105 if (isPointerDownEvent && mAwaitedFocusedApplication != nullptr) {
Siarhei Vishniakou9306c382022-09-30 15:30:31 -07001106 const int32_t displayId = motionEntry.displayId;
1107 const auto [x, y] = resolveTouchedPosition(motionEntry);
Harry Cutts33476232023-01-30 19:57:29 +00001108 const bool isStylus = isPointerFromStylus(motionEntry, /*pointerIndex=*/0);
Siarhei Vishniakou9306c382022-09-30 15:30:31 -07001109
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08001110 auto [touchedWindowHandle, _] = findTouchedWindowAtLocked(displayId, x, y, isStylus);
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001111 if (touchedWindowHandle != nullptr &&
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001112 touchedWindowHandle->getApplicationToken() !=
1113 mAwaitedFocusedApplication->getApplicationToken()) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001114 // User touched a different application than the one we are waiting on.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001115 ALOGI("Pruning input queue because user touched a different application while waiting "
1116 "for %s",
1117 mAwaitedFocusedApplication->getName().c_str());
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001118 return true;
1119 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001120
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08001121 // Alternatively, maybe there's a spy window that could handle this event.
1122 const std::vector<sp<WindowInfoHandle>> touchedSpies =
1123 findTouchedSpyWindowsAtLocked(displayId, x, y, isStylus);
1124 for (const auto& windowHandle : touchedSpies) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07001125 const std::shared_ptr<Connection> connection =
1126 getConnectionLocked(windowHandle->getToken());
Siarhei Vishniakou34ed4d42020-06-18 00:43:02 +00001127 if (connection != nullptr && connection->responsive) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08001128 // This spy window could take more input. Drop all events preceding this
1129 // event, so that the spy window can get a chance to receive the stream.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001130 ALOGW("Pruning the input queue because %s is unresponsive, but we have a "
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08001131 "responsive spy window that may handle the event.",
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001132 mAwaitedFocusedApplication->getName().c_str());
1133 return true;
1134 }
1135 }
1136 }
1137
1138 // Prevent getting stuck: if we have a pending key event, and some motion events that have not
1139 // yet been processed by some connections, the dispatcher will wait for these motion
1140 // events to be processed before dispatching the key event. This is because these motion events
1141 // may cause a new window to be launched, which the user might expect to receive focus.
1142 // To prevent waiting forever for such events, just send the key to the currently focused window
1143 if (isPointerDownEvent && mKeyIsWaitingForEventsTimeout) {
1144 ALOGD("Received a new pointer down event, stop waiting for events to process and "
1145 "just send the pending key event to the focused window.");
1146 mKeyIsWaitingForEventsTimeout = now();
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001147 }
1148 return false;
1149}
1150
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001151bool InputDispatcher::enqueueInboundEventLocked(std::unique_ptr<EventEntry> newEntry) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001152 bool needWake = mInboundQueue.empty();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001153 mInboundQueue.push_back(std::move(newEntry));
1154 EventEntry& entry = *(mInboundQueue.back());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001155 traceInboundQueueLengthLocked();
1156
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001157 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001158 case EventEntry::Type::KEY: {
Prabir Pradhan5735a322022-04-11 17:23:34 +00001159 LOG_ALWAYS_FATAL_IF((entry.policyFlags & POLICY_FLAG_TRUSTED) == 0,
1160 "Unexpected untrusted event.");
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001161 // Optimize app switch latency.
1162 // If the application takes too long to catch up then we drop all events preceding
1163 // the app switch key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001164 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001165 if (isAppSwitchKeyEvent(keyEntry)) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001166 if (keyEntry.action == AKEY_EVENT_ACTION_DOWN) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001167 mAppSwitchSawKeyDown = true;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001168 } else if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001169 if (mAppSwitchSawKeyDown) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001170 if (DEBUG_APP_SWITCH) {
1171 ALOGD("App switch is pending!");
1172 }
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001173 mAppSwitchDueTime = keyEntry.eventTime + APP_SWITCH_TIMEOUT;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001174 mAppSwitchSawKeyDown = false;
1175 needWake = true;
1176 }
1177 }
1178 }
Arthur Hung2ee6d0b2022-03-03 20:19:38 +08001179
1180 // If a new up event comes in, and the pending event with same key code has been asked
1181 // to try again later because of the policy. We have to reset the intercept key wake up
1182 // time for it may have been handled in the policy and could be dropped.
1183 if (keyEntry.action == AKEY_EVENT_ACTION_UP && mPendingEvent &&
1184 mPendingEvent->type == EventEntry::Type::KEY) {
1185 KeyEntry& pendingKey = static_cast<KeyEntry&>(*mPendingEvent);
1186 if (pendingKey.keyCode == keyEntry.keyCode &&
1187 pendingKey.interceptKeyResult ==
Michael Wright5caf55a2022-11-24 22:31:42 +00001188 KeyEntry::InterceptKeyResult::TRY_AGAIN_LATER) {
1189 pendingKey.interceptKeyResult = KeyEntry::InterceptKeyResult::UNKNOWN;
Arthur Hung2ee6d0b2022-03-03 20:19:38 +08001190 pendingKey.interceptKeyWakeupTime = 0;
1191 needWake = true;
1192 }
1193 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001194 break;
1195 }
1196
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001197 case EventEntry::Type::MOTION: {
Prabir Pradhan5735a322022-04-11 17:23:34 +00001198 LOG_ALWAYS_FATAL_IF((entry.policyFlags & POLICY_FLAG_TRUSTED) == 0,
1199 "Unexpected untrusted event.");
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001200 if (shouldPruneInboundQueueLocked(static_cast<MotionEntry&>(entry))) {
1201 mNextUnblockedEvent = mInboundQueue.back();
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001202 needWake = true;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001203 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001204 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001205 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001206 case EventEntry::Type::FOCUS: {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001207 LOG_ALWAYS_FATAL("Focus events should be inserted using enqueueFocusEventLocked");
1208 break;
1209 }
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001210 case EventEntry::Type::TOUCH_MODE_CHANGED:
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001211 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08001212 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07001213 case EventEntry::Type::SENSOR:
arthurhungb89ccb02020-12-30 16:19:01 +08001214 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
1215 case EventEntry::Type::DRAG: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001216 // nothing to do
1217 break;
1218 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001219 }
1220
1221 return needWake;
1222}
1223
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001224void InputDispatcher::addRecentEventLocked(std::shared_ptr<EventEntry> entry) {
Chris Yef59a2f42020-10-16 12:55:26 -07001225 // Do not store sensor event in recent queue to avoid flooding the queue.
1226 if (entry->type != EventEntry::Type::SENSOR) {
1227 mRecentQueue.push_back(entry);
1228 }
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001229 if (mRecentQueue.size() > RECENT_QUEUE_MAX_SIZE) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001230 mRecentQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001231 }
1232}
1233
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08001234std::pair<sp<WindowInfoHandle>, std::vector<InputTarget>>
Prabir Pradhan82e081e2022-12-06 09:50:09 +00001235InputDispatcher::findTouchedWindowAtLocked(int32_t displayId, float x, float y, bool isStylus,
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08001236 bool ignoreDragWindow) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001237 // Traverse windows from front to back to find touched window.
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08001238 std::vector<InputTarget> outsideTargets;
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001239 const auto& windowHandles = getWindowHandlesLocked(displayId);
chaviw98318de2021-05-19 16:45:23 -05001240 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
arthurhung6d4bed92021-03-17 11:59:33 +08001241 if (ignoreDragWindow && haveSameToken(windowHandle, mDragState->dragWindow)) {
arthurhungb89ccb02020-12-30 16:19:01 +08001242 continue;
1243 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001244
Prabir Pradhan3f90d312021-11-19 03:57:24 -08001245 const WindowInfo& info = *windowHandle->getInfo();
Prabir Pradhan33e3baa2022-12-06 20:30:22 +00001246 if (!info.isSpy() &&
1247 windowAcceptsTouchAt(info, displayId, x, y, isStylus, getTransformLocked(displayId))) {
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08001248 return {windowHandle, outsideTargets};
Prabir Pradhan3f90d312021-11-19 03:57:24 -08001249 }
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001250
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08001251 if (info.inputConfig.test(WindowInfo::InputConfig::WATCH_OUTSIDE_TOUCH)) {
1252 addWindowTargetLocked(windowHandle, InputTarget::Flags::DISPATCH_AS_OUTSIDE,
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08001253 /*pointerIds=*/{}, /*firstDownTimeInTarget=*/std::nullopt,
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08001254 outsideTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001255 }
1256 }
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08001257 return {nullptr, {}};
Michael Wrightd02c5b62014-02-10 15:10:22 -08001258}
1259
Prabir Pradhand65552b2021-10-07 11:23:50 -07001260std::vector<sp<WindowInfoHandle>> InputDispatcher::findTouchedSpyWindowsAtLocked(
Prabir Pradhan82e081e2022-12-06 09:50:09 +00001261 int32_t displayId, float x, float y, bool isStylus) const {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001262 // Traverse windows from front to back and gather the touched spy windows.
1263 std::vector<sp<WindowInfoHandle>> spyWindows;
1264 const auto& windowHandles = getWindowHandlesLocked(displayId);
1265 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
1266 const WindowInfo& info = *windowHandle->getInfo();
1267
Prabir Pradhan33e3baa2022-12-06 20:30:22 +00001268 if (!windowAcceptsTouchAt(info, displayId, x, y, isStylus, getTransformLocked(displayId))) {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001269 continue;
1270 }
1271 if (!info.isSpy()) {
1272 // The first touched non-spy window was found, so return the spy windows touched so far.
1273 return spyWindows;
1274 }
1275 spyWindows.push_back(windowHandle);
1276 }
1277 return spyWindows;
1278}
1279
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001280void InputDispatcher::dropInboundEventLocked(const EventEntry& entry, DropReason dropReason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001281 const char* reason;
1282 switch (dropReason) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001283 case DropReason::POLICY:
Prabir Pradhan65613802023-02-22 23:36:58 +00001284 if (debugInboundEventDetails()) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001285 ALOGD("Dropped event because policy consumed it.");
1286 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001287 reason = "inbound event was dropped because the policy consumed it";
1288 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001289 case DropReason::DISABLED:
1290 if (mLastDropReason != DropReason::DISABLED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001291 ALOGI("Dropped event because input dispatch is disabled.");
1292 }
1293 reason = "inbound event was dropped because input dispatch is disabled";
1294 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001295 case DropReason::APP_SWITCH:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001296 ALOGI("Dropped event because of pending overdue app switch.");
1297 reason = "inbound event was dropped because of pending overdue app switch";
1298 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001299 case DropReason::BLOCKED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001300 ALOGI("Dropped event because the current application is not responding and the user "
1301 "has started interacting with a different application.");
1302 reason = "inbound event was dropped because the current application is not responding "
1303 "and the user has started interacting with a different application";
1304 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001305 case DropReason::STALE:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001306 ALOGI("Dropped event because it is stale.");
1307 reason = "inbound event was dropped because it is stale";
1308 break;
Prabir Pradhan99987712020-11-10 18:43:05 -08001309 case DropReason::NO_POINTER_CAPTURE:
1310 ALOGI("Dropped event because there is no window with Pointer Capture.");
1311 reason = "inbound event was dropped because there is no window with Pointer Capture";
1312 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001313 case DropReason::NOT_DROPPED: {
1314 LOG_ALWAYS_FATAL("Should not be dropping a NOT_DROPPED event");
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001315 return;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001316 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001317 }
1318
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001319 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001320 case EventEntry::Type::KEY: {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001321 CancelationOptions options(CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS, reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001322 synthesizeCancelationEventsForAllConnectionsLocked(options);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001323 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001324 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001325 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001326 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
1327 if (motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001328 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS, reason);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001329 synthesizeCancelationEventsForAllConnectionsLocked(options);
1330 } else {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001331 CancelationOptions options(CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS,
1332 reason);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001333 synthesizeCancelationEventsForAllConnectionsLocked(options);
1334 }
1335 break;
1336 }
Chris Yef59a2f42020-10-16 12:55:26 -07001337 case EventEntry::Type::SENSOR: {
1338 break;
1339 }
arthurhungb89ccb02020-12-30 16:19:01 +08001340 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
1341 case EventEntry::Type::DRAG: {
Prabir Pradhan99987712020-11-10 18:43:05 -08001342 break;
1343 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001344 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001345 case EventEntry::Type::TOUCH_MODE_CHANGED:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001346 case EventEntry::Type::CONFIGURATION_CHANGED:
1347 case EventEntry::Type::DEVICE_RESET: {
Dominik Laskowski75788452021-02-09 18:51:25 -08001348 LOG_ALWAYS_FATAL("Should not drop %s events", ftl::enum_string(entry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001349 break;
1350 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001351 }
1352}
1353
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08001354static bool isAppSwitchKeyCode(int32_t keyCode) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001355 return keyCode == AKEYCODE_HOME || keyCode == AKEYCODE_ENDCALL ||
1356 keyCode == AKEYCODE_APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001357}
1358
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001359bool InputDispatcher::isAppSwitchKeyEvent(const KeyEntry& keyEntry) {
1360 return !(keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) && isAppSwitchKeyCode(keyEntry.keyCode) &&
1361 (keyEntry.policyFlags & POLICY_FLAG_TRUSTED) &&
1362 (keyEntry.policyFlags & POLICY_FLAG_PASS_TO_USER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001363}
1364
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07001365bool InputDispatcher::isAppSwitchPendingLocked() const {
Colin Cross5b799302022-10-18 21:52:41 -07001366 return mAppSwitchDueTime != LLONG_MAX;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001367}
1368
1369void InputDispatcher::resetPendingAppSwitchLocked(bool handled) {
Colin Cross5b799302022-10-18 21:52:41 -07001370 mAppSwitchDueTime = LLONG_MAX;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001371
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001372 if (DEBUG_APP_SWITCH) {
1373 if (handled) {
1374 ALOGD("App switch has arrived.");
1375 } else {
1376 ALOGD("App switch was abandoned.");
1377 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001378 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001379}
1380
Michael Wrightd02c5b62014-02-10 15:10:22 -08001381bool InputDispatcher::haveCommandsLocked() const {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001382 return !mCommandQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001383}
1384
Prabir Pradhancef936d2021-07-21 16:17:52 +00001385bool InputDispatcher::runCommandsLockedInterruptable() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001386 if (mCommandQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001387 return false;
1388 }
1389
1390 do {
Prabir Pradhancef936d2021-07-21 16:17:52 +00001391 auto command = std::move(mCommandQueue.front());
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001392 mCommandQueue.pop_front();
Prabir Pradhancef936d2021-07-21 16:17:52 +00001393 // Commands are run with the lock held, but may release and re-acquire the lock from within.
1394 command();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001395 } while (!mCommandQueue.empty());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001396 return true;
1397}
1398
Prabir Pradhancef936d2021-07-21 16:17:52 +00001399void InputDispatcher::postCommandLocked(Command&& command) {
1400 mCommandQueue.push_back(command);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001401}
1402
1403void InputDispatcher::drainInboundQueueLocked() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001404 while (!mInboundQueue.empty()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001405 std::shared_ptr<EventEntry> entry = mInboundQueue.front();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001406 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001407 releaseInboundEventLocked(entry);
1408 }
1409 traceInboundQueueLengthLocked();
1410}
1411
1412void InputDispatcher::releasePendingEventLocked() {
1413 if (mPendingEvent) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001414 releaseInboundEventLocked(mPendingEvent);
Yi Kong9b14ac62018-07-17 13:48:38 -07001415 mPendingEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001416 }
1417}
1418
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001419void InputDispatcher::releaseInboundEventLocked(std::shared_ptr<EventEntry> entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001420 InjectionState* injectionState = entry->injectionState;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001421 if (injectionState && injectionState->injectionResult == InputEventInjectionResult::PENDING) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001422 if (DEBUG_DISPATCH_CYCLE) {
1423 ALOGD("Injected inbound event was dropped.");
1424 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001425 setInjectionResult(*entry, InputEventInjectionResult::FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001426 }
1427 if (entry == mNextUnblockedEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001428 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001429 }
1430 addRecentEventLocked(entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001431}
1432
1433void InputDispatcher::resetKeyRepeatLocked() {
1434 if (mKeyRepeatState.lastKeyEntry) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001435 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001436 }
1437}
1438
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001439std::shared_ptr<KeyEntry> InputDispatcher::synthesizeKeyRepeatLocked(nsecs_t currentTime) {
1440 std::shared_ptr<KeyEntry> entry = mKeyRepeatState.lastKeyEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001441
Michael Wright2e732952014-09-24 13:26:59 -07001442 uint32_t policyFlags = entry->policyFlags &
1443 (POLICY_FLAG_RAW_MASK | POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_TRUSTED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001444
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001445 std::shared_ptr<KeyEntry> newEntry =
1446 std::make_unique<KeyEntry>(mIdGenerator.nextId(), currentTime, entry->deviceId,
1447 entry->source, entry->displayId, policyFlags, entry->action,
1448 entry->flags, entry->keyCode, entry->scanCode,
1449 entry->metaState, entry->repeatCount + 1, entry->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001450
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001451 newEntry->syntheticRepeat = true;
1452 mKeyRepeatState.lastKeyEntry = newEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001453 mKeyRepeatState.nextRepeatTime = currentTime + mConfig.keyRepeatDelay;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001454 return newEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001455}
1456
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001457bool InputDispatcher::dispatchConfigurationChangedLocked(nsecs_t currentTime,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001458 const ConfigurationChangedEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001459 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1460 ALOGD("dispatchConfigurationChanged - eventTime=%" PRId64, entry.eventTime);
1461 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001462
1463 // Reset key repeating in case a keyboard device was added or removed or something.
1464 resetKeyRepeatLocked();
1465
1466 // Enqueue a command to run outside the lock to tell the policy that the configuration changed.
Prabir Pradhancef936d2021-07-21 16:17:52 +00001467 auto command = [this, eventTime = entry.eventTime]() REQUIRES(mLock) {
1468 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00001469 mPolicy.notifyConfigurationChanged(eventTime);
Prabir Pradhancef936d2021-07-21 16:17:52 +00001470 };
1471 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001472 return true;
1473}
1474
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001475bool InputDispatcher::dispatchDeviceResetLocked(nsecs_t currentTime,
1476 const DeviceResetEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001477 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1478 ALOGD("dispatchDeviceReset - eventTime=%" PRId64 ", deviceId=%d", entry.eventTime,
1479 entry.deviceId);
1480 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001481
liushenxiang42232912021-05-21 20:24:09 +08001482 // Reset key repeating in case a keyboard device was disabled or enabled.
1483 if (mKeyRepeatState.lastKeyEntry && mKeyRepeatState.lastKeyEntry->deviceId == entry.deviceId) {
1484 resetKeyRepeatLocked();
1485 }
1486
Michael Wrightfb04fd52022-11-24 22:31:11 +00001487 CancelationOptions options(CancelationOptions::Mode::CANCEL_ALL_EVENTS, "device was reset");
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001488 options.deviceId = entry.deviceId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001489 synthesizeCancelationEventsForAllConnectionsLocked(options);
Siarhei Vishniakou0686f0c2023-05-02 11:56:15 -07001490
1491 // Remove all active pointers from this device
1492 for (auto& [_, touchState] : mTouchStatesByDisplay) {
1493 touchState.removeAllPointersForDevice(entry.deviceId);
1494 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001495 return true;
1496}
1497
Vishnu Nairad321cd2020-08-20 16:40:21 -07001498void InputDispatcher::enqueueFocusEventLocked(const sp<IBinder>& windowToken, bool hasFocus,
Vishnu Nairc519ff72021-01-21 08:23:08 -08001499 const std::string& reason) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001500 if (mPendingEvent != nullptr) {
1501 // Move the pending event to the front of the queue. This will give the chance
1502 // for the pending event to get dispatched to the newly focused window
1503 mInboundQueue.push_front(mPendingEvent);
1504 mPendingEvent = nullptr;
1505 }
1506
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001507 std::unique_ptr<FocusEntry> focusEntry =
1508 std::make_unique<FocusEntry>(mIdGenerator.nextId(), now(), windowToken, hasFocus,
1509 reason);
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001510
1511 // This event should go to the front of the queue, but behind all other focus events
1512 // Find the last focus event, and insert right after it
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001513 std::deque<std::shared_ptr<EventEntry>>::reverse_iterator it =
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001514 std::find_if(mInboundQueue.rbegin(), mInboundQueue.rend(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001515 [](const std::shared_ptr<EventEntry>& event) {
1516 return event->type == EventEntry::Type::FOCUS;
1517 });
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001518
1519 // Maintain the order of focus events. Insert the entry after all other focus events.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001520 mInboundQueue.insert(it.base(), std::move(focusEntry));
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001521}
1522
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001523void InputDispatcher::dispatchFocusLocked(nsecs_t currentTime, std::shared_ptr<FocusEntry> entry) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05001524 std::shared_ptr<InputChannel> channel = getInputChannelLocked(entry->connectionToken);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001525 if (channel == nullptr) {
1526 return; // Window has gone away
1527 }
1528 InputTarget target;
1529 target.inputChannel = channel;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08001530 target.flags = InputTarget::Flags::DISPATCH_AS_IS;
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001531 entry->dispatchInProgress = true;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00001532 std::string message = std::string("Focus ") + (entry->hasFocus ? "entering " : "leaving ") +
1533 channel->getName();
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07001534 std::string reason = std::string("reason=").append(entry->reason);
1535 android_log_event_list(LOGTAG_INPUT_FOCUS) << message << reason << LOG_ID_EVENTS;
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001536 dispatchEventLocked(currentTime, entry, {target});
1537}
1538
Prabir Pradhan99987712020-11-10 18:43:05 -08001539void InputDispatcher::dispatchPointerCaptureChangedLocked(
1540 nsecs_t currentTime, const std::shared_ptr<PointerCaptureChangedEntry>& entry,
1541 DropReason& dropReason) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001542 dropReason = DropReason::NOT_DROPPED;
1543
Prabir Pradhan99987712020-11-10 18:43:05 -08001544 const bool haveWindowWithPointerCapture = mWindowTokenWithPointerCapture != nullptr;
Prabir Pradhan99987712020-11-10 18:43:05 -08001545 sp<IBinder> token;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001546
1547 if (entry->pointerCaptureRequest.enable) {
1548 // Enable Pointer Capture.
1549 if (haveWindowWithPointerCapture &&
1550 (entry->pointerCaptureRequest == mCurrentPointerCaptureRequest)) {
Prabir Pradhan7092e262022-05-03 16:51:09 +00001551 // This can happen if pointer capture is disabled and re-enabled before we notify the
1552 // app of the state change, so there is no need to notify the app.
1553 ALOGI("Skipping dispatch of Pointer Capture being enabled: no state change.");
1554 return;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001555 }
1556 if (!mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08001557 // This can happen if a window requests capture and immediately releases capture.
1558 ALOGW("No window requested Pointer Capture.");
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001559 dropReason = DropReason::NO_POINTER_CAPTURE;
Prabir Pradhan99987712020-11-10 18:43:05 -08001560 return;
1561 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001562 if (entry->pointerCaptureRequest.seq != mCurrentPointerCaptureRequest.seq) {
1563 ALOGI("Skipping dispatch of Pointer Capture being enabled: sequence number mismatch.");
1564 return;
1565 }
1566
Vishnu Nairc519ff72021-01-21 08:23:08 -08001567 token = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Prabir Pradhan99987712020-11-10 18:43:05 -08001568 LOG_ALWAYS_FATAL_IF(!token, "Cannot find focused window for Pointer Capture.");
1569 mWindowTokenWithPointerCapture = token;
1570 } else {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001571 // Disable Pointer Capture.
1572 // We do not check if the sequence number matches for requests to disable Pointer Capture
1573 // for two reasons:
1574 // 1. Pointer Capture can be disabled by a focus change, which means we can get two entries
1575 // to disable capture with the same sequence number: one generated by
1576 // disablePointerCaptureForcedLocked() and another as an acknowledgement of Pointer
1577 // Capture being disabled in InputReader.
1578 // 2. We respect any request to disable Pointer Capture generated by InputReader, since the
1579 // actual Pointer Capture state that affects events being generated by input devices is
1580 // in InputReader.
1581 if (!haveWindowWithPointerCapture) {
1582 // Pointer capture was already forcefully disabled because of focus change.
1583 dropReason = DropReason::NOT_DROPPED;
1584 return;
1585 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001586 token = mWindowTokenWithPointerCapture;
1587 mWindowTokenWithPointerCapture = nullptr;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001588 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan7d030382020-12-21 07:58:35 -08001589 setPointerCaptureLocked(false);
1590 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001591 }
1592
1593 auto channel = getInputChannelLocked(token);
1594 if (channel == nullptr) {
1595 // Window has gone away, clean up Pointer Capture state.
1596 mWindowTokenWithPointerCapture = nullptr;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001597 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan7d030382020-12-21 07:58:35 -08001598 setPointerCaptureLocked(false);
1599 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001600 return;
1601 }
1602 InputTarget target;
1603 target.inputChannel = channel;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08001604 target.flags = InputTarget::Flags::DISPATCH_AS_IS;
Prabir Pradhan99987712020-11-10 18:43:05 -08001605 entry->dispatchInProgress = true;
1606 dispatchEventLocked(currentTime, entry, {target});
1607
1608 dropReason = DropReason::NOT_DROPPED;
1609}
1610
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001611void InputDispatcher::dispatchTouchModeChangeLocked(nsecs_t currentTime,
1612 const std::shared_ptr<TouchModeEntry>& entry) {
1613 const std::vector<sp<WindowInfoHandle>>& windowHandles =
Antonio Kantek15beb512022-06-13 22:35:41 +00001614 getWindowHandlesLocked(entry->displayId);
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001615 if (windowHandles.empty()) {
1616 return;
1617 }
1618 const std::vector<InputTarget> inputTargets =
1619 getInputTargetsFromWindowHandlesLocked(windowHandles);
1620 if (inputTargets.empty()) {
1621 return;
1622 }
1623 entry->dispatchInProgress = true;
1624 dispatchEventLocked(currentTime, entry, inputTargets);
1625}
1626
1627std::vector<InputTarget> InputDispatcher::getInputTargetsFromWindowHandlesLocked(
1628 const std::vector<sp<WindowInfoHandle>>& windowHandles) const {
1629 std::vector<InputTarget> inputTargets;
1630 for (const sp<WindowInfoHandle>& handle : windowHandles) {
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001631 const sp<IBinder>& token = handle->getToken();
1632 if (token == nullptr) {
1633 continue;
1634 }
1635 std::shared_ptr<InputChannel> channel = getInputChannelLocked(token);
1636 if (channel == nullptr) {
1637 continue; // Window has gone away
1638 }
1639 InputTarget target;
1640 target.inputChannel = channel;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08001641 target.flags = InputTarget::Flags::DISPATCH_AS_IS;
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001642 inputTargets.push_back(target);
1643 }
1644 return inputTargets;
1645}
1646
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001647bool InputDispatcher::dispatchKeyLocked(nsecs_t currentTime, std::shared_ptr<KeyEntry> entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001648 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001649 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001650 if (!entry->dispatchInProgress) {
1651 if (entry->repeatCount == 0 && entry->action == AKEY_EVENT_ACTION_DOWN &&
1652 (entry->policyFlags & POLICY_FLAG_TRUSTED) &&
1653 (!(entry->policyFlags & POLICY_FLAG_DISABLE_KEY_REPEAT))) {
1654 if (mKeyRepeatState.lastKeyEntry &&
Chris Ye2ad95392020-09-01 13:44:44 -07001655 mKeyRepeatState.lastKeyEntry->keyCode == entry->keyCode &&
Michael Wrightd02c5b62014-02-10 15:10:22 -08001656 // We have seen two identical key downs in a row which indicates that the device
1657 // driver is automatically generating key repeats itself. We take note of the
1658 // repeat here, but we disable our own next key repeat timer since it is clear that
1659 // we will not need to synthesize key repeats ourselves.
Chris Ye2ad95392020-09-01 13:44:44 -07001660 mKeyRepeatState.lastKeyEntry->deviceId == entry->deviceId) {
1661 // Make sure we don't get key down from a different device. If a different
1662 // device Id has same key pressed down, the new device Id will replace the
1663 // current one to hold the key repeat with repeat count reset.
1664 // In the future when got a KEY_UP on the device id, drop it and do not
1665 // stop the key repeat on current device.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001666 entry->repeatCount = mKeyRepeatState.lastKeyEntry->repeatCount + 1;
1667 resetKeyRepeatLocked();
Colin Cross5b799302022-10-18 21:52:41 -07001668 mKeyRepeatState.nextRepeatTime = LLONG_MAX; // don't generate repeats ourselves
Michael Wrightd02c5b62014-02-10 15:10:22 -08001669 } else {
1670 // Not a repeat. Save key down state in case we do see a repeat later.
1671 resetKeyRepeatLocked();
1672 mKeyRepeatState.nextRepeatTime = entry->eventTime + mConfig.keyRepeatTimeout;
1673 }
1674 mKeyRepeatState.lastKeyEntry = entry;
Chris Ye2ad95392020-09-01 13:44:44 -07001675 } else if (entry->action == AKEY_EVENT_ACTION_UP && mKeyRepeatState.lastKeyEntry &&
1676 mKeyRepeatState.lastKeyEntry->deviceId != entry->deviceId) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001677 // The key on device 'deviceId' is still down, do not stop key repeat
Prabir Pradhan65613802023-02-22 23:36:58 +00001678 if (debugInboundEventDetails()) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001679 ALOGD("deviceId=%d got KEY_UP as stale", entry->deviceId);
1680 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001681 } else if (!entry->syntheticRepeat) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001682 resetKeyRepeatLocked();
1683 }
1684
1685 if (entry->repeatCount == 1) {
1686 entry->flags |= AKEY_EVENT_FLAG_LONG_PRESS;
1687 } else {
1688 entry->flags &= ~AKEY_EVENT_FLAG_LONG_PRESS;
1689 }
1690
1691 entry->dispatchInProgress = true;
1692
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001693 logOutboundKeyDetails("dispatchKey - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001694 }
1695
1696 // Handle case where the policy asked us to try again later last time.
Michael Wright5caf55a2022-11-24 22:31:42 +00001697 if (entry->interceptKeyResult == KeyEntry::InterceptKeyResult::TRY_AGAIN_LATER) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001698 if (currentTime < entry->interceptKeyWakeupTime) {
1699 if (entry->interceptKeyWakeupTime < *nextWakeupTime) {
1700 *nextWakeupTime = entry->interceptKeyWakeupTime;
1701 }
1702 return false; // wait until next wakeup
1703 }
Michael Wright5caf55a2022-11-24 22:31:42 +00001704 entry->interceptKeyResult = KeyEntry::InterceptKeyResult::UNKNOWN;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001705 entry->interceptKeyWakeupTime = 0;
1706 }
1707
1708 // Give the policy a chance to intercept the key.
Michael Wright5caf55a2022-11-24 22:31:42 +00001709 if (entry->interceptKeyResult == KeyEntry::InterceptKeyResult::UNKNOWN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001710 if (entry->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07001711 sp<IBinder> focusedWindowToken =
Vishnu Nairc519ff72021-01-21 08:23:08 -08001712 mFocusResolver.getFocusedWindowToken(getTargetDisplayId(*entry));
Prabir Pradhancef936d2021-07-21 16:17:52 +00001713
1714 auto command = [this, focusedWindowToken, entry]() REQUIRES(mLock) {
1715 doInterceptKeyBeforeDispatchingCommand(focusedWindowToken, *entry);
1716 };
1717 postCommandLocked(std::move(command));
Josep del Riob3981622023-04-18 15:49:45 +00001718 // Poke user activity for keys not passed to user
1719 pokeUserActivityLocked(*entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001720 return false; // wait for the command to run
1721 } else {
Michael Wright5caf55a2022-11-24 22:31:42 +00001722 entry->interceptKeyResult = KeyEntry::InterceptKeyResult::CONTINUE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001723 }
Michael Wright5caf55a2022-11-24 22:31:42 +00001724 } else if (entry->interceptKeyResult == KeyEntry::InterceptKeyResult::SKIP) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001725 if (*dropReason == DropReason::NOT_DROPPED) {
1726 *dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001727 }
1728 }
1729
1730 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001731 if (*dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001732 setInjectionResult(*entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001733 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
1734 : InputEventInjectionResult::FAILED);
Garfield Tan6a5a14e2020-01-28 13:24:04 -08001735 mReporter->reportDroppedKey(entry->id);
Josep del Riob3981622023-04-18 15:49:45 +00001736 // Poke user activity for undispatched keys
1737 pokeUserActivityLocked(*entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001738 return true;
1739 }
1740
1741 // Identify targets.
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001742 InputEventInjectionResult injectionResult;
1743 sp<WindowInfoHandle> focusedWindow =
1744 findFocusedWindowTargetLocked(currentTime, *entry, nextWakeupTime,
1745 /*byref*/ injectionResult);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001746 if (injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001747 return false;
1748 }
1749
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001750 setInjectionResult(*entry, injectionResult);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001751 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001752 return true;
1753 }
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001754 LOG_ALWAYS_FATAL_IF(focusedWindow == nullptr);
1755
1756 std::vector<InputTarget> inputTargets;
1757 addWindowTargetLocked(focusedWindow,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08001758 InputTarget::Flags::FOREGROUND | InputTarget::Flags::DISPATCH_AS_IS,
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08001759 /*pointerIds=*/{}, getDownTime(*entry), inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001760
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001761 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001762 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001763
1764 // Dispatch the key.
1765 dispatchEventLocked(currentTime, entry, inputTargets);
1766 return true;
1767}
1768
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001769void InputDispatcher::logOutboundKeyDetails(const char* prefix, const KeyEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001770 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1771 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32 ", "
1772 "policyFlags=0x%x, action=0x%x, flags=0x%x, keyCode=0x%x, scanCode=0x%x, "
1773 "metaState=0x%x, repeatCount=%d, downTime=%" PRId64,
1774 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId,
1775 entry.policyFlags, entry.action, entry.flags, entry.keyCode, entry.scanCode,
1776 entry.metaState, entry.repeatCount, entry.downTime);
1777 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001778}
1779
Prabir Pradhancef936d2021-07-21 16:17:52 +00001780void InputDispatcher::dispatchSensorLocked(nsecs_t currentTime,
1781 const std::shared_ptr<SensorEntry>& entry,
Chris Yef59a2f42020-10-16 12:55:26 -07001782 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001783 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1784 ALOGD("notifySensorEvent eventTime=%" PRId64 ", hwTimestamp=%" PRId64 ", deviceId=%d, "
1785 "source=0x%x, sensorType=%s",
1786 entry->eventTime, entry->hwTimestamp, entry->deviceId, entry->source,
Dominik Laskowski75788452021-02-09 18:51:25 -08001787 ftl::enum_string(entry->sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001788 }
Prabir Pradhancef936d2021-07-21 16:17:52 +00001789 auto command = [this, entry]() REQUIRES(mLock) {
1790 scoped_unlock unlock(mLock);
1791
1792 if (entry->accuracyChanged) {
Prabir Pradhana41d2442023-04-20 21:30:40 +00001793 mPolicy.notifySensorAccuracy(entry->deviceId, entry->sensorType, entry->accuracy);
Prabir Pradhancef936d2021-07-21 16:17:52 +00001794 }
Prabir Pradhana41d2442023-04-20 21:30:40 +00001795 mPolicy.notifySensorEvent(entry->deviceId, entry->sensorType, entry->accuracy,
1796 entry->hwTimestamp, entry->values);
Prabir Pradhancef936d2021-07-21 16:17:52 +00001797 };
1798 postCommandLocked(std::move(command));
Chris Yef59a2f42020-10-16 12:55:26 -07001799}
1800
1801bool InputDispatcher::flushSensor(int deviceId, InputDeviceSensorType sensorType) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001802 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1803 ALOGD("flushSensor deviceId=%d, sensorType=%s", deviceId,
Dominik Laskowski75788452021-02-09 18:51:25 -08001804 ftl::enum_string(sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001805 }
Chris Yef59a2f42020-10-16 12:55:26 -07001806 { // acquire lock
1807 std::scoped_lock _l(mLock);
1808
1809 for (auto it = mInboundQueue.begin(); it != mInboundQueue.end(); it++) {
1810 std::shared_ptr<EventEntry> entry = *it;
1811 if (entry->type == EventEntry::Type::SENSOR) {
1812 it = mInboundQueue.erase(it);
1813 releaseInboundEventLocked(entry);
1814 }
1815 }
1816 }
1817 return true;
1818}
1819
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001820bool InputDispatcher::dispatchMotionLocked(nsecs_t currentTime, std::shared_ptr<MotionEntry> entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001821 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001822 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001823 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001824 if (!entry->dispatchInProgress) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001825 entry->dispatchInProgress = true;
1826
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001827 logOutboundMotionDetails("dispatchMotion - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001828 }
1829
1830 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001831 if (*dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001832 setInjectionResult(*entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001833 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
1834 : InputEventInjectionResult::FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001835 return true;
1836 }
1837
Prabir Pradhanaa561d12021-09-24 06:57:33 -07001838 const bool isPointerEvent = isFromSource(entry->source, AINPUT_SOURCE_CLASS_POINTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001839
1840 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001841 std::vector<InputTarget> inputTargets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001842
1843 bool conflictingPointerActions = false;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001844 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001845 if (isPointerEvent) {
1846 // Pointer event. (eg. touchscreen)
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00001847
1848 if (mDragState &&
1849 (entry->action & AMOTION_EVENT_ACTION_MASK) == AMOTION_EVENT_ACTION_POINTER_DOWN) {
1850 // If drag and drop ongoing and pointer down occur: pilfer drag window pointers
1851 pilferPointersLocked(mDragState->dragWindow->getToken());
1852 }
1853
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08001854 inputTargets =
Siarhei Vishniakou4fe57392022-10-25 13:44:30 -07001855 findTouchedWindowTargetsLocked(currentTime, *entry, &conflictingPointerActions,
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001856 /*byref*/ injectionResult);
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08001857 LOG_ALWAYS_FATAL_IF(injectionResult != InputEventInjectionResult::SUCCEEDED &&
1858 !inputTargets.empty());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001859 } else {
1860 // Non touch event. (eg. trackball)
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001861 sp<WindowInfoHandle> focusedWindow =
1862 findFocusedWindowTargetLocked(currentTime, *entry, nextWakeupTime, injectionResult);
1863 if (injectionResult == InputEventInjectionResult::SUCCEEDED) {
1864 LOG_ALWAYS_FATAL_IF(focusedWindow == nullptr);
1865 addWindowTargetLocked(focusedWindow,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08001866 InputTarget::Flags::FOREGROUND |
1867 InputTarget::Flags::DISPATCH_AS_IS,
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08001868 /*pointerIds=*/{}, getDownTime(*entry), inputTargets);
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001869 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001870 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001871 if (injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001872 return false;
1873 }
1874
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001875 setInjectionResult(*entry, injectionResult);
Prabir Pradhan5735a322022-04-11 17:23:34 +00001876 if (injectionResult == InputEventInjectionResult::TARGET_MISMATCH) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001877 return true;
1878 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001879 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001880 CancelationOptions::Mode mode(
1881 isPointerEvent ? CancelationOptions::Mode::CANCEL_POINTER_EVENTS
1882 : CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS);
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001883 CancelationOptions options(mode, "input event injection failed");
1884 synthesizeCancelationEventsForMonitorsLocked(options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001885 return true;
1886 }
1887
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001888 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001889 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001890
1891 // Dispatch the motion.
1892 if (conflictingPointerActions) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001893 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001894 "conflicting pointer actions");
Michael Wrightd02c5b62014-02-10 15:10:22 -08001895 synthesizeCancelationEventsForAllConnectionsLocked(options);
1896 }
1897 dispatchEventLocked(currentTime, entry, inputTargets);
1898 return true;
1899}
1900
chaviw98318de2021-05-19 16:45:23 -05001901void InputDispatcher::enqueueDragEventLocked(const sp<WindowInfoHandle>& windowHandle,
Arthur Hung54745652022-04-20 07:17:41 +00001902 bool isExiting, const int32_t rawX,
1903 const int32_t rawY) {
1904 const vec2 xy = windowHandle->getInfo()->transform.transform(vec2(rawX, rawY));
arthurhungb89ccb02020-12-30 16:19:01 +08001905 std::unique_ptr<DragEntry> dragEntry =
Arthur Hung54745652022-04-20 07:17:41 +00001906 std::make_unique<DragEntry>(mIdGenerator.nextId(), now(), windowHandle->getToken(),
1907 isExiting, xy.x, xy.y);
arthurhungb89ccb02020-12-30 16:19:01 +08001908
1909 enqueueInboundEventLocked(std::move(dragEntry));
1910}
1911
1912void InputDispatcher::dispatchDragLocked(nsecs_t currentTime, std::shared_ptr<DragEntry> entry) {
1913 std::shared_ptr<InputChannel> channel = getInputChannelLocked(entry->connectionToken);
1914 if (channel == nullptr) {
1915 return; // Window has gone away
1916 }
1917 InputTarget target;
1918 target.inputChannel = channel;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08001919 target.flags = InputTarget::Flags::DISPATCH_AS_IS;
arthurhungb89ccb02020-12-30 16:19:01 +08001920 entry->dispatchInProgress = true;
1921 dispatchEventLocked(currentTime, entry, {target});
1922}
1923
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001924void InputDispatcher::logOutboundMotionDetails(const char* prefix, const MotionEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001925 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -08001926 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=%s, displayId=%" PRId32
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001927 ", policyFlags=0x%x, "
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001928 "action=%s, actionButton=0x%x, flags=0x%x, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001929 "metaState=0x%x, buttonState=0x%x,"
1930 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%" PRId64,
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -08001931 prefix, entry.eventTime, entry.deviceId,
1932 inputEventSourceToString(entry.source).c_str(), entry.displayId, entry.policyFlags,
1933 MotionEvent::actionToString(entry.action).c_str(), entry.actionButton, entry.flags,
1934 entry.metaState, entry.buttonState, entry.edgeFlags, entry.xPrecision,
1935 entry.yPrecision, entry.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001936
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001937 for (uint32_t i = 0; i < entry.pointerCount; i++) {
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07001938 ALOGD(" Pointer %d: id=%d, toolType=%s, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001939 "x=%f, y=%f, pressure=%f, size=%f, "
1940 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
1941 "orientation=%f",
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07001942 i, entry.pointerProperties[i].id,
1943 ftl::enum_string(entry.pointerProperties[i].toolType).c_str(),
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001944 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
1945 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
1946 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
1947 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
1948 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
1949 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
1950 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
1951 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
1952 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
1953 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001954 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001955}
1956
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001957void InputDispatcher::dispatchEventLocked(nsecs_t currentTime,
1958 std::shared_ptr<EventEntry> eventEntry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001959 const std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001960 ATRACE_CALL();
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001961 if (DEBUG_DISPATCH_CYCLE) {
1962 ALOGD("dispatchEventToCurrentInputTargets");
1963 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001964
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00001965 processInteractionsLocked(*eventEntry, inputTargets);
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00001966
Michael Wrightd02c5b62014-02-10 15:10:22 -08001967 ALOG_ASSERT(eventEntry->dispatchInProgress); // should already have been set to true
1968
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001969 pokeUserActivityLocked(*eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001970
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001971 for (const InputTarget& inputTarget : inputTargets) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07001972 std::shared_ptr<Connection> connection =
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07001973 getConnectionLocked(inputTarget.inputChannel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07001974 if (connection != nullptr) {
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08001975 prepareDispatchCycleLocked(currentTime, connection, eventEntry, inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001976 } else {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001977 if (DEBUG_FOCUS) {
1978 ALOGD("Dropping event delivery to target with channel '%s' because it "
1979 "is no longer registered with the input dispatcher.",
1980 inputTarget.inputChannel->getName().c_str());
1981 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001982 }
1983 }
1984}
1985
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07001986void InputDispatcher::cancelEventsForAnrLocked(const std::shared_ptr<Connection>& connection) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001987 // We will not be breaking any connections here, even if the policy wants us to abort dispatch.
1988 // If the policy decides to close the app, we will get a channel removal event via
1989 // unregisterInputChannel, and will clean up the connection that way. We are already not
1990 // sending new pointers to the connection when it blocked, but focused events will continue to
1991 // pile up.
1992 ALOGW("Canceling events for %s because it is unresponsive",
1993 connection->inputChannel->getName().c_str());
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08001994 if (connection->status == Connection::Status::NORMAL) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001995 CancelationOptions options(CancelationOptions::Mode::CANCEL_ALL_EVENTS,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001996 "application not responding");
1997 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001998 }
1999}
2000
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002001void InputDispatcher::resetNoFocusedWindowTimeoutLocked() {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002002 if (DEBUG_FOCUS) {
2003 ALOGD("Resetting ANR timeouts.");
2004 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002005
2006 // Reset input target wait timeout.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002007 mNoFocusedWindowTimeoutTime = std::nullopt;
Chris Yea209fde2020-07-22 13:54:51 -07002008 mAwaitedFocusedApplication.reset();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002009}
2010
Tiger Huang721e26f2018-07-24 22:26:19 +08002011/**
2012 * Get the display id that the given event should go to. If this event specifies a valid display id,
2013 * then it should be dispatched to that display. Otherwise, the event goes to the focused display.
2014 * Focused display is the display that the user most recently interacted with.
2015 */
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002016int32_t InputDispatcher::getTargetDisplayId(const EventEntry& entry) {
Tiger Huang721e26f2018-07-24 22:26:19 +08002017 int32_t displayId;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002018 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002019 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002020 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
2021 displayId = keyEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002022 break;
2023 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002024 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002025 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
2026 displayId = motionEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002027 break;
2028 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00002029 case EventEntry::Type::TOUCH_MODE_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08002030 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002031 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002032 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07002033 case EventEntry::Type::DEVICE_RESET:
arthurhungb89ccb02020-12-30 16:19:01 +08002034 case EventEntry::Type::SENSOR:
2035 case EventEntry::Type::DRAG: {
Dominik Laskowski75788452021-02-09 18:51:25 -08002036 ALOGE("%s events do not have a target display", ftl::enum_string(entry.type).c_str());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002037 return ADISPLAY_ID_NONE;
2038 }
Tiger Huang721e26f2018-07-24 22:26:19 +08002039 }
2040 return displayId == ADISPLAY_ID_NONE ? mFocusedDisplayId : displayId;
2041}
2042
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002043bool InputDispatcher::shouldWaitToSendKeyLocked(nsecs_t currentTime,
2044 const char* focusedWindowName) {
2045 if (mAnrTracker.empty()) {
2046 // already processed all events that we waited for
2047 mKeyIsWaitingForEventsTimeout = std::nullopt;
2048 return false;
2049 }
2050
2051 if (!mKeyIsWaitingForEventsTimeout.has_value()) {
2052 // Start the timer
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00002053 // Wait to send key because there are unprocessed events that may cause focus to change
Siarhei Vishniakou70622952020-07-30 11:17:23 -05002054 mKeyIsWaitingForEventsTimeout = currentTime +
2055 std::chrono::duration_cast<std::chrono::nanoseconds>(KEY_WAITING_FOR_EVENTS_TIMEOUT)
2056 .count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002057 return true;
2058 }
2059
2060 // We still have pending events, and already started the timer
2061 if (currentTime < *mKeyIsWaitingForEventsTimeout) {
2062 return true; // Still waiting
2063 }
2064
2065 // Waited too long, and some connection still hasn't processed all motions
2066 // Just send the key to the focused window
2067 ALOGW("Dispatching key to %s even though there are other unprocessed events",
2068 focusedWindowName);
2069 mKeyIsWaitingForEventsTimeout = std::nullopt;
2070 return false;
2071}
2072
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002073sp<WindowInfoHandle> InputDispatcher::findFocusedWindowTargetLocked(
2074 nsecs_t currentTime, const EventEntry& entry, nsecs_t* nextWakeupTime,
2075 InputEventInjectionResult& outInjectionResult) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002076 std::string reason;
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002077 outInjectionResult = InputEventInjectionResult::FAILED; // Default result
Michael Wrightd02c5b62014-02-10 15:10:22 -08002078
Tiger Huang721e26f2018-07-24 22:26:19 +08002079 int32_t displayId = getTargetDisplayId(entry);
chaviw98318de2021-05-19 16:45:23 -05002080 sp<WindowInfoHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Chris Yea209fde2020-07-22 13:54:51 -07002081 std::shared_ptr<InputApplicationHandle> focusedApplicationHandle =
Tiger Huang721e26f2018-07-24 22:26:19 +08002082 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
2083
Michael Wrightd02c5b62014-02-10 15:10:22 -08002084 // If there is no currently focused window and no focused application
2085 // then drop the event.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002086 if (focusedWindowHandle == nullptr && focusedApplicationHandle == nullptr) {
2087 ALOGI("Dropping %s event because there is no focused window or focused application in "
2088 "display %" PRId32 ".",
Dominik Laskowski75788452021-02-09 18:51:25 -08002089 ftl::enum_string(entry.type).c_str(), displayId);
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002090 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002091 }
2092
Vishnu Nair062a8672021-09-03 16:07:44 -07002093 // Drop key events if requested by input feature
2094 if (focusedWindowHandle != nullptr && shouldDropInput(entry, focusedWindowHandle)) {
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002095 return nullptr;
Vishnu Nair062a8672021-09-03 16:07:44 -07002096 }
2097
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002098 // Compatibility behavior: raise ANR if there is a focused application, but no focused window.
2099 // Only start counting when we have a focused event to dispatch. The ANR is canceled if we
2100 // start interacting with another application via touch (app switch). This code can be removed
2101 // if the "no focused window ANR" is moved to the policy. Input doesn't know whether
2102 // an app is expected to have a focused window.
2103 if (focusedWindowHandle == nullptr && focusedApplicationHandle != nullptr) {
2104 if (!mNoFocusedWindowTimeoutTime.has_value()) {
2105 // We just discovered that there's no focused window. Start the ANR timer
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05002106 std::chrono::nanoseconds timeout = focusedApplicationHandle->getDispatchingTimeout(
2107 DEFAULT_INPUT_DISPATCHING_TIMEOUT);
2108 mNoFocusedWindowTimeoutTime = currentTime + timeout.count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002109 mAwaitedFocusedApplication = focusedApplicationHandle;
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05002110 mAwaitedApplicationDisplayId = displayId;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002111 ALOGW("Waiting because no window has focus but %s may eventually add a "
2112 "window when it finishes starting up. Will wait for %" PRId64 "ms",
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05002113 mAwaitedFocusedApplication->getName().c_str(), millis(timeout));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002114 *nextWakeupTime = *mNoFocusedWindowTimeoutTime;
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002115 outInjectionResult = InputEventInjectionResult::PENDING;
2116 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002117 } else if (currentTime > *mNoFocusedWindowTimeoutTime) {
2118 // Already raised ANR. Drop the event
2119 ALOGE("Dropping %s event because there is no focused window",
Dominik Laskowski75788452021-02-09 18:51:25 -08002120 ftl::enum_string(entry.type).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002121 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002122 } else {
2123 // Still waiting for the focused window
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002124 outInjectionResult = InputEventInjectionResult::PENDING;
2125 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002126 }
2127 }
2128
2129 // we have a valid, non-null focused window
2130 resetNoFocusedWindowTimeoutLocked();
2131
Prabir Pradhan5735a322022-04-11 17:23:34 +00002132 // Verify targeted injection.
2133 if (const auto err = verifyTargetedInjection(focusedWindowHandle, entry); err) {
2134 ALOGW("Dropping injected event: %s", (*err).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002135 outInjectionResult = InputEventInjectionResult::TARGET_MISMATCH;
2136 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002137 }
2138
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002139 if (focusedWindowHandle->getInfo()->inputConfig.test(
2140 WindowInfo::InputConfig::PAUSE_DISPATCHING)) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002141 ALOGI("Waiting because %s is paused", focusedWindowHandle->getName().c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002142 outInjectionResult = InputEventInjectionResult::PENDING;
2143 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002144 }
2145
2146 // If the event is a key event, then we must wait for all previous events to
2147 // complete before delivering it because previous events may have the
2148 // side-effect of transferring focus to a different window and we want to
2149 // ensure that the following keys are sent to the new window.
2150 //
2151 // Suppose the user touches a button in a window then immediately presses "A".
2152 // If the button causes a pop-up window to appear then we want to ensure that
2153 // the "A" key is delivered to the new pop-up window. This is because users
2154 // often anticipate pending UI changes when typing on a keyboard.
2155 // To obtain this behavior, we must serialize key events with respect to all
2156 // prior input events.
2157 if (entry.type == EventEntry::Type::KEY) {
2158 if (shouldWaitToSendKeyLocked(currentTime, focusedWindowHandle->getName().c_str())) {
2159 *nextWakeupTime = *mKeyIsWaitingForEventsTimeout;
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002160 outInjectionResult = InputEventInjectionResult::PENDING;
2161 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002162 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002163 }
2164
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002165 outInjectionResult = InputEventInjectionResult::SUCCEEDED;
2166 return focusedWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002167}
2168
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002169/**
2170 * Given a list of monitors, remove the ones we cannot find a connection for, and the ones
2171 * that are currently unresponsive.
2172 */
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002173std::vector<Monitor> InputDispatcher::selectResponsiveMonitorsLocked(
2174 const std::vector<Monitor>& monitors) const {
2175 std::vector<Monitor> responsiveMonitors;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002176 std::copy_if(monitors.begin(), monitors.end(), std::back_inserter(responsiveMonitors),
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002177 [this](const Monitor& monitor) REQUIRES(mLock) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07002178 std::shared_ptr<Connection> connection =
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002179 getConnectionLocked(monitor.inputChannel->getConnectionToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002180 if (connection == nullptr) {
2181 ALOGE("Could not find connection for monitor %s",
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002182 monitor.inputChannel->getName().c_str());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002183 return false;
2184 }
2185 if (!connection->responsive) {
2186 ALOGW("Unresponsive monitor %s will not get the new gesture",
2187 connection->inputChannel->getName().c_str());
2188 return false;
2189 }
2190 return true;
2191 });
2192 return responsiveMonitors;
2193}
2194
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07002195/**
2196 * In general, touch should be always split between windows. Some exceptions:
2197 * 1. Don't split touch is if we have an active pointer down, and a new pointer is going down that's
2198 * from the same device, *and* the window that's receiving the current pointer does not support
2199 * split touch.
2200 * 2. Don't split mouse events
2201 */
2202bool InputDispatcher::shouldSplitTouch(const TouchState& touchState,
2203 const MotionEntry& entry) const {
2204 if (isFromSource(entry.source, AINPUT_SOURCE_MOUSE)) {
2205 // We should never split mouse events
2206 return false;
2207 }
2208 for (const TouchedWindow& touchedWindow : touchState.windows) {
2209 if (touchedWindow.windowHandle->getInfo()->isSpy()) {
2210 // Spy windows should not affect whether or not touch is split.
2211 continue;
2212 }
2213 if (touchedWindow.windowHandle->getInfo()->supportsSplitTouch()) {
2214 continue;
2215 }
Arthur Hungc539dbb2022-12-08 07:45:36 +00002216 if (touchedWindow.windowHandle->getInfo()->inputConfig.test(
2217 gui::WindowInfo::InputConfig::IS_WALLPAPER)) {
2218 // Wallpaper window should not affect whether or not touch is split
2219 continue;
2220 }
2221
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07002222 // Eventually, touchedWindow will contain the deviceId of each pointer that's currently
2223 // being sent there. For now, use deviceId from touch state.
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08002224 if (entry.deviceId == touchState.deviceId && touchedWindow.pointerIds.any()) {
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07002225 return false;
2226 }
2227 }
2228 return true;
2229}
2230
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002231std::vector<InputTarget> InputDispatcher::findTouchedWindowTargetsLocked(
Siarhei Vishniakou4fe57392022-10-25 13:44:30 -07002232 nsecs_t currentTime, const MotionEntry& entry, bool* outConflictingPointerActions,
2233 InputEventInjectionResult& outInjectionResult) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002234 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002235
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002236 std::vector<InputTarget> targets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002237 // For security reasons, we defer updating the touch state until we are sure that
2238 // event injection will be allowed.
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002239 const int32_t displayId = entry.displayId;
2240 const int32_t action = entry.action;
Siarhei Vishniakoubf880522023-05-01 11:03:22 -07002241 const int32_t maskedAction = MotionEvent::getActionMasked(action);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002242
2243 // Update the touch state as needed based on the properties of the touch event.
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002244 outInjectionResult = InputEventInjectionResult::PENDING;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002245
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002246 // Copy current touch state into tempTouchState.
2247 // This state will be used to update mTouchStatesByDisplay at the end of this function.
2248 // If no state for the specified display exists, then our initial state will be empty.
Yi Kong9b14ac62018-07-17 13:48:38 -07002249 const TouchState* oldState = nullptr;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002250 TouchState tempTouchState;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002251 if (const auto it = mTouchStatesByDisplay.find(displayId); it != mTouchStatesByDisplay.end()) {
2252 oldState = &(it->second);
Prabir Pradhane680f9b2022-02-04 04:24:00 -08002253 tempTouchState = *oldState;
Jeff Brownf086ddb2014-02-11 14:28:48 -08002254 }
2255
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07002256 bool isSplit = shouldSplitTouch(tempTouchState, entry);
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07002257 const bool switchedDevice = (oldState != nullptr) &&
Siarhei Vishniakou5cee1e32022-11-29 12:35:39 -08002258 (oldState->deviceId != entry.deviceId || oldState->source != entry.source);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002259
2260 const bool isHoverAction = (maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE ||
2261 maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2262 maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT);
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002263 // A DOWN could be generated from POINTER_DOWN if the initial pointers did not land into any
2264 // touchable windows.
2265 const bool wasDown = oldState != nullptr && oldState->isDown();
2266 const bool isDown = (maskedAction == AMOTION_EVENT_ACTION_DOWN) ||
2267 (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN && !wasDown);
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07002268 const bool newGesture = isDown || maskedAction == AMOTION_EVENT_ACTION_SCROLL ||
2269 maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2270 maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE;
Prabir Pradhanaa561d12021-09-24 06:57:33 -07002271 const bool isFromMouse = isFromSource(entry.source, AINPUT_SOURCE_MOUSE);
Siarhei Vishniakou5cee1e32022-11-29 12:35:39 -08002272
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002273 // If pointers are already down, let's finish the current gesture and ignore the new events
2274 // from another device. However, if the new event is a down event, let's cancel the current
2275 // touch and let the new one take over.
2276 if (switchedDevice && wasDown && !isDown) {
2277 LOG(INFO) << "Dropping event because a pointer for device " << oldState->deviceId
2278 << " is already down in display " << displayId << ": " << entry.getDescription();
2279 // TODO(b/211379801): test multiple simultaneous input streams.
2280 outInjectionResult = InputEventInjectionResult::FAILED;
2281 return {}; // wrong device
2282 }
2283
Michael Wrightd02c5b62014-02-10 15:10:22 -08002284 if (newGesture) {
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002285 // If a new gesture is starting, clear the touch state completely.
2286 tempTouchState.reset();
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002287 tempTouchState.deviceId = entry.deviceId;
2288 tempTouchState.source = entry.source;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002289 isSplit = false;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04002290 } else if (switchedDevice && maskedAction == AMOTION_EVENT_ACTION_MOVE) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07002291 ALOGI("Dropping move event because a pointer for a different device is already active "
2292 "in display %" PRId32,
2293 displayId);
Siarhei Vishniakou16e4fa02023-02-16 17:48:56 -08002294 // TODO(b/211379801): test multiple simultaneous input streams.
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002295 outInjectionResult = InputEventInjectionResult::FAILED;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002296 return {}; // wrong device
Michael Wrightd02c5b62014-02-10 15:10:22 -08002297 }
2298
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002299 if (isHoverAction) {
2300 // For hover actions, we will treat 'tempTouchState' as a new state, so let's erase
2301 // all of the existing hovering pointers and recompute.
2302 tempTouchState.clearHoveringPointers();
2303 }
2304
Michael Wrightd02c5b62014-02-10 15:10:22 -08002305 if (newGesture || (isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN)) {
2306 /* Case 1: New splittable pointer going down, or need target for hover or scroll. */
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07002307 const auto [x, y] = resolveTouchedPosition(entry);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002308 const int32_t pointerIndex = getMotionEventActionPointerIndex(action);
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002309 // Outside targets should be added upon first dispatched DOWN event. That means, this should
2310 // be a pointer that would generate ACTION_DOWN, *and* touch should not already be down.
Prabir Pradhand65552b2021-10-07 11:23:50 -07002311 const bool isStylus = isPointerFromStylus(entry, pointerIndex);
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002312 auto [newTouchedWindowHandle, outsideTargets] =
2313 findTouchedWindowAtLocked(displayId, x, y, isStylus);
Michael Wright3dd60e22019-03-27 22:06:44 +00002314
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002315 if (isDown) {
2316 targets += outsideTargets;
2317 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002318 // Handle the case where we did not find a window.
Yi Kong9b14ac62018-07-17 13:48:38 -07002319 if (newTouchedWindowHandle == nullptr) {
Prabir Pradhan82e081e2022-12-06 09:50:09 +00002320 ALOGD("No new touched window at (%.1f, %.1f) in display %" PRId32, x, y, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002321 // Try to assign the pointer to the first foreground window we find, if there is one.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002322 newTouchedWindowHandle = tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002323 }
2324
Prabir Pradhan5735a322022-04-11 17:23:34 +00002325 // Verify targeted injection.
2326 if (const auto err = verifyTargetedInjection(newTouchedWindowHandle, entry); err) {
2327 ALOGW("Dropping injected touch event: %s", (*err).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002328 outInjectionResult = os::InputEventInjectionResult::TARGET_MISMATCH;
Prabir Pradhan5735a322022-04-11 17:23:34 +00002329 newTouchedWindowHandle = nullptr;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002330 return {};
Prabir Pradhan5735a322022-04-11 17:23:34 +00002331 }
2332
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002333 // Figure out whether splitting will be allowed for this window.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002334 if (newTouchedWindowHandle != nullptr) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002335 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
2336 // New window supports splitting, but we should never split mouse events.
2337 isSplit = !isFromMouse;
2338 } else if (isSplit) {
2339 // New window does not support splitting but we have already split events.
2340 // Ignore the new window.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002341 newTouchedWindowHandle = nullptr;
2342 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002343 } else {
2344 // No window is touched, so set split to true. This will allow the next pointer down to
Prabir Pradhan713bb3e2021-12-20 02:07:40 -08002345 // be delivered to a new window which supports split touch. Pointers from a mouse device
2346 // should never be split.
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07002347 isSplit = !isFromMouse;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002348 }
2349
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002350 std::vector<sp<WindowInfoHandle>> newTouchedWindows =
Prabir Pradhand65552b2021-10-07 11:23:50 -07002351 findTouchedSpyWindowsAtLocked(displayId, x, y, isStylus);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002352 if (newTouchedWindowHandle != nullptr) {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002353 // Process the foreground window first so that it is the first to receive the event.
2354 newTouchedWindows.insert(newTouchedWindows.begin(), newTouchedWindowHandle);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002355 }
2356
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002357 if (newTouchedWindows.empty()) {
Prabir Pradhan82e081e2022-12-06 09:50:09 +00002358 ALOGI("Dropping event because there is no touchable window at (%.1f, %.1f) on display "
2359 "%d.",
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002360 x, y, displayId);
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002361 outInjectionResult = InputEventInjectionResult::FAILED;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002362 return {};
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002363 }
2364
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002365 for (const sp<WindowInfoHandle>& windowHandle : newTouchedWindows) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07002366 if (!canWindowReceiveMotionLocked(windowHandle, entry)) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002367 continue;
2368 }
2369
Siarhei Vishniakoub681c202023-05-01 11:22:33 -07002370 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2371 maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE) {
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002372 const int32_t pointerId = entry.pointerProperties[0].id;
Siarhei Vishniakoub681c202023-05-01 11:22:33 -07002373 // The "windowHandle" is the target of this hovering pointer.
2374 tempTouchState.addHoveringPointerToWindow(windowHandle, entry.deviceId, pointerId);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002375 }
2376
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002377 // Set target flags.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002378 ftl::Flags<InputTarget::Flags> targetFlags = InputTarget::Flags::DISPATCH_AS_IS;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002379
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002380 if (canReceiveForegroundTouches(*windowHandle->getInfo())) {
2381 // There should only be one touched window that can be "foreground" for the pointer.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002382 targetFlags |= InputTarget::Flags::FOREGROUND;
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002383 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002384
2385 if (isSplit) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002386 targetFlags |= InputTarget::Flags::SPLIT;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002387 }
2388 if (isWindowObscuredAtPointLocked(windowHandle, x, y)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002389 targetFlags |= InputTarget::Flags::WINDOW_IS_OBSCURED;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002390 } else if (isWindowObscuredLocked(windowHandle)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002391 targetFlags |= InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002392 }
Michael Wright3dd60e22019-03-27 22:06:44 +00002393
2394 // Update the temporary touch state.
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08002395 std::bitset<MAX_POINTER_ID + 1> pointerIds;
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002396 if (!isHoverAction) {
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08002397 pointerIds.set(entry.pointerProperties[pointerIndex].id);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002398 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002399
Siarhei Vishniakoue0431e42023-01-28 17:01:39 -08002400 const bool isDownOrPointerDown = maskedAction == AMOTION_EVENT_ACTION_DOWN ||
2401 maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN;
2402
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002403 // TODO(b/211379801): Currently, even if pointerIds are empty (hover case), we would
2404 // still add a window to the touch state. We should avoid doing that, but some of the
2405 // later checks ("at least one foreground window") rely on this in order to dispatch
2406 // the event properly, so that needs to be updated, possibly by looking at InputTargets.
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002407 tempTouchState.addOrUpdateWindow(windowHandle, targetFlags, pointerIds,
Siarhei Vishniakoue0431e42023-01-28 17:01:39 -08002408 isDownOrPointerDown
2409 ? std::make_optional(entry.eventTime)
2410 : std::nullopt);
Arthur Hungc539dbb2022-12-08 07:45:36 +00002411
2412 // If this is the pointer going down and the touched window has a wallpaper
2413 // then also add the touched wallpaper windows so they are locked in for the duration
2414 // of the touch gesture.
2415 // We do not collect wallpapers during HOVER_MOVE or SCROLL because the wallpaper
2416 // engine only supports touch events. We would need to add a mechanism similar
2417 // to View.onGenericMotionEvent to enable wallpapers to handle these events.
Siarhei Vishniakoue0431e42023-01-28 17:01:39 -08002418 if (isDownOrPointerDown) {
Arthur Hungc539dbb2022-12-08 07:45:36 +00002419 if (targetFlags.test(InputTarget::Flags::FOREGROUND) &&
2420 windowHandle->getInfo()->inputConfig.test(
2421 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER)) {
2422 sp<WindowInfoHandle> wallpaper = findWallpaperWindowBelow(windowHandle);
2423 if (wallpaper != nullptr) {
2424 ftl::Flags<InputTarget::Flags> wallpaperFlags =
2425 InputTarget::Flags::WINDOW_IS_OBSCURED |
2426 InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED |
2427 InputTarget::Flags::DISPATCH_AS_IS;
2428 if (isSplit) {
2429 wallpaperFlags |= InputTarget::Flags::SPLIT;
2430 }
2431 tempTouchState.addOrUpdateWindow(wallpaper, wallpaperFlags, pointerIds,
2432 entry.eventTime);
2433 }
2434 }
2435 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002436 }
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00002437
Siarhei Vishniakou060f82b2023-01-27 06:39:14 -08002438 // If a window is already pilfering some pointers, give it this new pointer as well and
2439 // make it pilfering. This will prevent other non-spy windows from getting this pointer,
2440 // which is a specific behaviour that we want.
2441 const int32_t pointerId = entry.pointerProperties[pointerIndex].id;
2442 for (TouchedWindow& touchedWindow : tempTouchState.windows) {
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08002443 if (touchedWindow.pointerIds.test(pointerId) &&
Siarhei Vishniakou060f82b2023-01-27 06:39:14 -08002444 touchedWindow.pilferedPointerIds.count() > 0) {
2445 // This window is already pilfering some pointers, and this new pointer is also
2446 // going to it. Therefore, take over this pointer and don't give it to anyone
2447 // else.
2448 touchedWindow.pilferedPointerIds.set(pointerId);
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00002449 }
2450 }
Siarhei Vishniakou060f82b2023-01-27 06:39:14 -08002451
2452 // Restrict all pilfered pointers to the pilfering windows.
2453 tempTouchState.cancelPointersForNonPilferingWindows();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002454 } else {
2455 /* Case 2: Pointer move, up, cancel or non-splittable pointer down. */
2456
2457 // If the pointer is not currently down, then ignore the event.
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07002458 if (!tempTouchState.isDown() && maskedAction != AMOTION_EVENT_ACTION_HOVER_EXIT) {
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002459 LOG(INFO) << "Dropping event because the pointer is not down or we previously "
2460 "dropped the pointer down event in display "
2461 << displayId << ": " << entry.getDescription();
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002462 outInjectionResult = InputEventInjectionResult::FAILED;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002463 return {};
Michael Wrightd02c5b62014-02-10 15:10:22 -08002464 }
2465
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07002466 // If the pointer is not currently hovering, then ignore the event.
2467 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT) {
2468 const int32_t pointerId = entry.pointerProperties[0].id;
2469 if (oldState == nullptr ||
2470 oldState->getWindowsWithHoveringPointer(entry.deviceId, pointerId).empty()) {
2471 LOG(INFO) << "Dropping event because the hovering pointer is not in any windows in "
2472 "display "
2473 << displayId << ": " << entry.getDescription();
2474 outInjectionResult = InputEventInjectionResult::FAILED;
2475 return {};
2476 }
2477 tempTouchState.removeHoveringPointer(entry.deviceId, pointerId);
2478 }
2479
arthurhung6d4bed92021-03-17 11:59:33 +08002480 addDragEventLocked(entry);
arthurhungb89ccb02020-12-30 16:19:01 +08002481
Michael Wrightd02c5b62014-02-10 15:10:22 -08002482 // Check whether touches should slip outside of the current foreground window.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002483 if (maskedAction == AMOTION_EVENT_ACTION_MOVE && entry.pointerCount == 1 &&
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002484 tempTouchState.isSlippery()) {
Siarhei Vishniakou9306c382022-09-30 15:30:31 -07002485 const auto [x, y] = resolveTouchedPosition(entry);
Harry Cutts33476232023-01-30 19:57:29 +00002486 const bool isStylus = isPointerFromStylus(entry, /*pointerIndex=*/0);
chaviw98318de2021-05-19 16:45:23 -05002487 sp<WindowInfoHandle> oldTouchedWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002488 tempTouchState.getFirstForegroundWindowHandle();
Siarhei Vishniakou0f6558d2023-04-21 12:05:13 -07002489 LOG_ALWAYS_FATAL_IF(oldTouchedWindowHandle == nullptr);
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002490 auto [newTouchedWindowHandle, _] = findTouchedWindowAtLocked(displayId, x, y, isStylus);
Vishnu Nair062a8672021-09-03 16:07:44 -07002491
Prabir Pradhan5735a322022-04-11 17:23:34 +00002492 // Verify targeted injection.
2493 if (const auto err = verifyTargetedInjection(newTouchedWindowHandle, entry); err) {
2494 ALOGW("Dropping injected event: %s", (*err).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002495 outInjectionResult = os::InputEventInjectionResult::TARGET_MISMATCH;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002496 return {};
Prabir Pradhan5735a322022-04-11 17:23:34 +00002497 }
2498
Vishnu Nair062a8672021-09-03 16:07:44 -07002499 // Drop touch events if requested by input feature
2500 if (newTouchedWindowHandle != nullptr &&
2501 shouldDropInput(entry, newTouchedWindowHandle)) {
2502 newTouchedWindowHandle = nullptr;
2503 }
2504
Siarhei Vishniakouafa08cc2023-05-08 22:35:50 -07002505 if (newTouchedWindowHandle != nullptr &&
2506 !haveSameToken(oldTouchedWindowHandle, newTouchedWindowHandle)) {
Siarhei Vishniakou0f6558d2023-04-21 12:05:13 -07002507 ALOGD("Touch is slipping out of window %s into window %s in display %" PRId32,
2508 oldTouchedWindowHandle->getName().c_str(),
2509 newTouchedWindowHandle->getName().c_str(), displayId);
2510
Michael Wrightd02c5b62014-02-10 15:10:22 -08002511 // Make a slippery exit from the old window.
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08002512 std::bitset<MAX_POINTER_ID + 1> pointerIds;
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002513 const int32_t pointerId = entry.pointerProperties[0].id;
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08002514 pointerIds.set(pointerId);
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002515
2516 const TouchedWindow& touchedWindow =
2517 tempTouchState.getTouchedWindow(oldTouchedWindowHandle);
2518 addWindowTargetLocked(oldTouchedWindowHandle,
2519 InputTarget::Flags::DISPATCH_AS_SLIPPERY_EXIT, pointerIds,
2520 touchedWindow.firstDownTimeInTarget, targets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002521
2522 // Make a slippery entrance into the new window.
2523 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
Prabir Pradhan713bb3e2021-12-20 02:07:40 -08002524 isSplit = !isFromMouse;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002525 }
2526
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002527 ftl::Flags<InputTarget::Flags> targetFlags =
2528 InputTarget::Flags::DISPATCH_AS_SLIPPERY_ENTER;
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002529 if (canReceiveForegroundTouches(*newTouchedWindowHandle->getInfo())) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002530 targetFlags |= InputTarget::Flags::FOREGROUND;
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002531 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002532 if (isSplit) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002533 targetFlags |= InputTarget::Flags::SPLIT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002534 }
2535 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002536 targetFlags |= InputTarget::Flags::WINDOW_IS_OBSCURED;
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002537 } else if (isWindowObscuredLocked(newTouchedWindowHandle)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002538 targetFlags |= InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002539 }
2540
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002541 tempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds,
2542 entry.eventTime);
Arthur Hungc539dbb2022-12-08 07:45:36 +00002543
2544 // Check if the wallpaper window should deliver the corresponding event.
2545 slipWallpaperTouch(targetFlags, oldTouchedWindowHandle, newTouchedWindowHandle,
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002546 tempTouchState, pointerId, targets);
2547 tempTouchState.removeTouchedPointerFromWindow(pointerId, oldTouchedWindowHandle);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002548 }
2549 }
Arthur Hung96483742022-11-15 03:30:48 +00002550
2551 // Update the pointerIds for non-splittable when it received pointer down.
2552 if (!isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN) {
2553 // If no split, we suppose all touched windows should receive pointer down.
2554 const int32_t pointerIndex = getMotionEventActionPointerIndex(action);
2555 for (size_t i = 0; i < tempTouchState.windows.size(); i++) {
2556 TouchedWindow& touchedWindow = tempTouchState.windows[i];
2557 // Ignore drag window for it should just track one pointer.
2558 if (mDragState && mDragState->dragWindow == touchedWindow.windowHandle) {
2559 continue;
2560 }
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08002561 touchedWindow.pointerIds.set(entry.pointerProperties[pointerIndex].id);
Arthur Hung96483742022-11-15 03:30:48 +00002562 }
2563 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002564 }
2565
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002566 // Update dispatching for hover enter and exit.
Sam Dubeyf886dec2023-01-27 13:28:19 +00002567 {
2568 std::vector<TouchedWindow> hoveringWindows =
2569 getHoveringWindowsLocked(oldState, tempTouchState, entry);
2570 for (const TouchedWindow& touchedWindow : hoveringWindows) {
Siarhei Vishniakoud5876ba2023-05-15 17:58:34 -07002571 std::optional<InputTarget> target =
2572 createInputTargetLocked(touchedWindow.windowHandle, touchedWindow.targetFlags,
2573 touchedWindow.firstDownTimeInTarget);
2574 if (!target) {
2575 continue;
2576 }
2577 // Hardcode to single hovering pointer for now.
2578 std::bitset<MAX_POINTER_ID + 1> pointerIds;
2579 pointerIds.set(entry.pointerProperties[0].id);
2580 target->addPointers(pointerIds, touchedWindow.windowHandle->getInfo()->transform);
2581 targets.push_back(*target);
Sam Dubeyf886dec2023-01-27 13:28:19 +00002582 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002583 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002584
Prabir Pradhan5735a322022-04-11 17:23:34 +00002585 // Ensure that all touched windows are valid for injection.
2586 if (entry.injectionState != nullptr) {
2587 std::string errs;
2588 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Prabir Pradhan5735a322022-04-11 17:23:34 +00002589 const auto err = verifyTargetedInjection(touchedWindow.windowHandle, entry);
2590 if (err) errs += "\n - " + *err;
2591 }
2592 if (!errs.empty()) {
2593 ALOGW("Dropping targeted injection: At least one touched window is not owned by uid "
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00002594 "%s:%s",
2595 entry.injectionState->targetUid->toString().c_str(), errs.c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002596 outInjectionResult = InputEventInjectionResult::TARGET_MISMATCH;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002597 return {};
Prabir Pradhan5735a322022-04-11 17:23:34 +00002598 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002599 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002600
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002601 // Check whether windows listening for outside touches are owned by the same UID. If the owner
2602 // has a different UID, then we will not reveal coordinate information to this window.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002603 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
chaviw98318de2021-05-19 16:45:23 -05002604 sp<WindowInfoHandle> foregroundWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002605 tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002606 if (foregroundWindowHandle) {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00002607 const auto foregroundWindowUid = foregroundWindowHandle->getInfo()->ownerUid;
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002608 for (InputTarget& target : targets) {
2609 if (target.flags.test(InputTarget::Flags::DISPATCH_AS_OUTSIDE)) {
2610 sp<WindowInfoHandle> targetWindow =
2611 getWindowHandleLocked(target.inputChannel->getConnectionToken());
2612 if (targetWindow->getInfo()->ownerUid != foregroundWindowUid) {
2613 target.flags |= InputTarget::Flags::ZERO_COORDS;
Michael Wright3dd60e22019-03-27 22:06:44 +00002614 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002615 }
2616 }
2617 }
2618 }
2619
Harry Cuttsb166c002023-05-09 13:06:05 +00002620 // If this is a touchpad navigation gesture, it needs to only be sent to trusted targets, as we
2621 // only want the system UI to handle these gestures.
2622 const bool isTouchpadNavGesture = isFromSource(entry.source, AINPUT_SOURCE_MOUSE) &&
2623 entry.classification == MotionClassification::MULTI_FINGER_SWIPE;
2624 if (isTouchpadNavGesture) {
2625 filterUntrustedTargets(/* byref */ tempTouchState, /* byref */ targets);
2626 }
2627
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07002628 // Output targets from the touch state.
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002629 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08002630 if (touchedWindow.pointerIds.none() && !touchedWindow.hasHoveringPointers(entry.deviceId)) {
Siarhei Vishniakoue0431e42023-01-28 17:01:39 -08002631 // Windows with hovering pointers are getting persisted inside TouchState.
2632 // Do not send this event to those windows.
2633 continue;
2634 }
Harry Cuttsb166c002023-05-09 13:06:05 +00002635
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002636 addWindowTargetLocked(touchedWindow.windowHandle, touchedWindow.targetFlags,
2637 touchedWindow.pointerIds, touchedWindow.firstDownTimeInTarget,
2638 targets);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002639 }
Sam Dubey39d37cf2022-12-07 18:05:35 +00002640
Siarhei Vishniakou580fb3a2023-05-05 15:02:20 -07002641 // During targeted injection, only allow owned targets to receive events
2642 std::erase_if(targets, [&](const InputTarget& target) {
2643 LOG_ALWAYS_FATAL_IF(target.windowHandle == nullptr);
2644 const auto err = verifyTargetedInjection(target.windowHandle, entry);
2645 if (err) {
2646 LOG(WARNING) << "Dropping injected event from " << target.windowHandle->getName()
2647 << ": " << (*err);
2648 return true;
2649 }
2650 return false;
2651 });
2652
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07002653 if (targets.empty()) {
2654 LOG(INFO) << "Dropping event because no targets were found: " << entry.getDescription();
2655 outInjectionResult = InputEventInjectionResult::FAILED;
2656 return {};
2657 }
2658
2659 // If we only have windows getting ACTION_OUTSIDE, then drop the event, because there is no
2660 // window that is actually receiving the entire gesture.
2661 if (std::all_of(targets.begin(), targets.end(), [](const InputTarget& target) {
2662 return target.flags.test(InputTarget::Flags::DISPATCH_AS_OUTSIDE);
2663 })) {
2664 LOG(INFO) << "Dropping event because all windows would just receive ACTION_OUTSIDE: "
2665 << entry.getDescription();
2666 outInjectionResult = InputEventInjectionResult::FAILED;
2667 return {};
2668 }
2669
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002670 outInjectionResult = InputEventInjectionResult::SUCCEEDED;
Sam Dubeyf886dec2023-01-27 13:28:19 +00002671 // Drop the outside or hover touch windows since we will not care about them
2672 // in the next iteration.
2673 tempTouchState.filterNonAsIsTouchWindows();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002674
Michael Wrightd02c5b62014-02-10 15:10:22 -08002675 // Update final pieces of touch state if the injector had permission.
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002676 if (switchedDevice) {
2677 if (DEBUG_FOCUS) {
2678 ALOGD("Conflicting pointer actions: Switched to a different device.");
2679 }
2680 *outConflictingPointerActions = true;
2681 }
2682
2683 if (isHoverAction) {
2684 // Started hovering, therefore no longer down.
Siarhei Vishniakou3ad385b2022-11-04 10:09:53 -07002685 if (oldState && oldState->isDown()) {
Siarhei Vishniakou6e1e9872022-11-08 17:51:35 -08002686 ALOGD_IF(DEBUG_FOCUS,
2687 "Conflicting pointer actions: Hover received while pointer was down.");
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002688 *outConflictingPointerActions = true;
2689 }
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002690 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2691 maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE) {
2692 tempTouchState.deviceId = entry.deviceId;
2693 tempTouchState.source = entry.source;
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002694 }
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002695 } else if (maskedAction == AMOTION_EVENT_ACTION_UP) {
2696 // Pointer went up.
2697 tempTouchState.removeTouchedPointer(entry.pointerProperties[0].id);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002698 } else if (maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002699 // All pointers up or canceled.
2700 tempTouchState.reset();
2701 } else if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
2702 // First pointer went down.
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002703 if (oldState && (oldState->isDown() || oldState->hasHoveringPointers())) {
2704 ALOGD("Conflicting pointer actions: Down received while already down or hovering.");
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002705 *outConflictingPointerActions = true;
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002706 }
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002707 } else if (maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
2708 // One pointer went up.
2709 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
2710 uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002711
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002712 for (size_t i = 0; i < tempTouchState.windows.size();) {
2713 TouchedWindow& touchedWindow = tempTouchState.windows[i];
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08002714 touchedWindow.pointerIds.reset(pointerId);
2715 if (touchedWindow.pointerIds.none()) {
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002716 tempTouchState.windows.erase(tempTouchState.windows.begin() + i);
2717 continue;
2718 }
2719 i += 1;
2720 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002721 }
2722
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002723 // Save changes unless the action was scroll in which case the temporary touch
2724 // state was only valid for this one action.
2725 if (maskedAction != AMOTION_EVENT_ACTION_SCROLL) {
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07002726 if (displayId >= 0) {
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002727 tempTouchState.clearWindowsWithoutPointers();
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002728 mTouchStatesByDisplay[displayId] = tempTouchState;
2729 } else {
2730 mTouchStatesByDisplay.erase(displayId);
2731 }
2732 }
2733
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -08002734 if (tempTouchState.windows.empty()) {
2735 mTouchStatesByDisplay.erase(displayId);
2736 }
2737
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002738 return targets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002739}
2740
arthurhung6d4bed92021-03-17 11:59:33 +08002741void InputDispatcher::finishDragAndDrop(int32_t displayId, float x, float y) {
Prabir Pradhand65552b2021-10-07 11:23:50 -07002742 // Prevent stylus interceptor windows from affecting drag and drop behavior for now, until we
2743 // have an explicit reason to support it.
2744 constexpr bool isStylus = false;
2745
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002746 auto [dropWindow, _] =
Harry Cutts33476232023-01-30 19:57:29 +00002747 findTouchedWindowAtLocked(displayId, x, y, isStylus, /*ignoreDragWindow=*/true);
arthurhung6d4bed92021-03-17 11:59:33 +08002748 if (dropWindow) {
2749 vec2 local = dropWindow->getInfo()->transform.transform(x, y);
Prabir Pradhancef936d2021-07-21 16:17:52 +00002750 sendDropWindowCommandLocked(dropWindow->getToken(), local.x, local.y);
Arthur Hung6d0571e2021-04-09 20:18:16 +08002751 } else {
Arthur Hung54745652022-04-20 07:17:41 +00002752 ALOGW("No window found when drop.");
Prabir Pradhancef936d2021-07-21 16:17:52 +00002753 sendDropWindowCommandLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08002754 }
2755 mDragState.reset();
2756}
2757
2758void InputDispatcher::addDragEventLocked(const MotionEntry& entry) {
Arthur Hung3915c1f2022-05-31 07:17:17 +00002759 if (!mDragState || mDragState->dragWindow->getInfo()->displayId != entry.displayId) {
arthurhungb89ccb02020-12-30 16:19:01 +08002760 return;
2761 }
2762
arthurhung6d4bed92021-03-17 11:59:33 +08002763 if (!mDragState->isStartDrag) {
2764 mDragState->isStartDrag = true;
2765 mDragState->isStylusButtonDownAtStart =
2766 (entry.buttonState & AMOTION_EVENT_BUTTON_STYLUS_PRIMARY) != 0;
2767 }
2768
Arthur Hung54745652022-04-20 07:17:41 +00002769 // Find the pointer index by id.
2770 int32_t pointerIndex = 0;
2771 for (; static_cast<uint32_t>(pointerIndex) < entry.pointerCount; pointerIndex++) {
2772 const PointerProperties& pointerProperties = entry.pointerProperties[pointerIndex];
2773 if (pointerProperties.id == mDragState->pointerId) {
2774 break;
arthurhung6d4bed92021-03-17 11:59:33 +08002775 }
Arthur Hung54745652022-04-20 07:17:41 +00002776 }
arthurhung6d4bed92021-03-17 11:59:33 +08002777
Arthur Hung54745652022-04-20 07:17:41 +00002778 if (uint32_t(pointerIndex) == entry.pointerCount) {
2779 LOG_ALWAYS_FATAL("Should find a valid pointer index by id %d", mDragState->pointerId);
Arthur Hung54745652022-04-20 07:17:41 +00002780 }
2781
2782 const int32_t maskedAction = entry.action & AMOTION_EVENT_ACTION_MASK;
2783 const int32_t x = entry.pointerCoords[pointerIndex].getX();
2784 const int32_t y = entry.pointerCoords[pointerIndex].getY();
2785
2786 switch (maskedAction) {
2787 case AMOTION_EVENT_ACTION_MOVE: {
2788 // Handle the special case : stylus button no longer pressed.
2789 bool isStylusButtonDown =
2790 (entry.buttonState & AMOTION_EVENT_BUTTON_STYLUS_PRIMARY) != 0;
2791 if (mDragState->isStylusButtonDownAtStart && !isStylusButtonDown) {
2792 finishDragAndDrop(entry.displayId, x, y);
2793 return;
2794 }
2795
2796 // Prevent stylus interceptor windows from affecting drag and drop behavior for now,
2797 // until we have an explicit reason to support it.
2798 constexpr bool isStylus = false;
2799
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002800 auto [hoverWindowHandle, _] = findTouchedWindowAtLocked(entry.displayId, x, y, isStylus,
Harry Cutts33476232023-01-30 19:57:29 +00002801 /*ignoreDragWindow=*/true);
Arthur Hung54745652022-04-20 07:17:41 +00002802 // enqueue drag exit if needed.
2803 if (hoverWindowHandle != mDragState->dragHoverWindowHandle &&
2804 !haveSameToken(hoverWindowHandle, mDragState->dragHoverWindowHandle)) {
2805 if (mDragState->dragHoverWindowHandle != nullptr) {
Harry Cutts33476232023-01-30 19:57:29 +00002806 enqueueDragEventLocked(mDragState->dragHoverWindowHandle, /*isExiting=*/true, x,
Arthur Hung54745652022-04-20 07:17:41 +00002807 y);
2808 }
2809 mDragState->dragHoverWindowHandle = hoverWindowHandle;
2810 }
2811 // enqueue drag location if needed.
2812 if (hoverWindowHandle != nullptr) {
Harry Cutts33476232023-01-30 19:57:29 +00002813 enqueueDragEventLocked(hoverWindowHandle, /*isExiting=*/false, x, y);
Arthur Hung54745652022-04-20 07:17:41 +00002814 }
2815 break;
2816 }
2817
2818 case AMOTION_EVENT_ACTION_POINTER_UP:
2819 if (getMotionEventActionPointerIndex(entry.action) != pointerIndex) {
2820 break;
2821 }
2822 // The drag pointer is up.
2823 [[fallthrough]];
2824 case AMOTION_EVENT_ACTION_UP:
2825 finishDragAndDrop(entry.displayId, x, y);
2826 break;
2827 case AMOTION_EVENT_ACTION_CANCEL: {
2828 ALOGD("Receiving cancel when drag and drop.");
2829 sendDropWindowCommandLocked(nullptr, 0, 0);
2830 mDragState.reset();
2831 break;
2832 }
arthurhungb89ccb02020-12-30 16:19:01 +08002833 }
2834}
2835
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002836std::optional<InputTarget> InputDispatcher::createInputTargetLocked(
2837 const sp<android::gui::WindowInfoHandle>& windowHandle,
2838 ftl::Flags<InputTarget::Flags> targetFlags,
2839 std::optional<nsecs_t> firstDownTimeInTarget) const {
2840 std::shared_ptr<InputChannel> inputChannel = getInputChannelLocked(windowHandle->getToken());
2841 if (inputChannel == nullptr) {
2842 ALOGW("Not creating InputTarget for %s, no input channel", windowHandle->getName().c_str());
2843 return {};
2844 }
2845 InputTarget inputTarget;
2846 inputTarget.inputChannel = inputChannel;
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00002847 inputTarget.windowHandle = windowHandle;
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002848 inputTarget.flags = targetFlags;
2849 inputTarget.globalScaleFactor = windowHandle->getInfo()->globalScaleFactor;
2850 inputTarget.firstDownTimeInTarget = firstDownTimeInTarget;
2851 const auto& displayInfoIt = mDisplayInfos.find(windowHandle->getInfo()->displayId);
2852 if (displayInfoIt != mDisplayInfos.end()) {
2853 inputTarget.displayTransform = displayInfoIt->second.transform;
2854 } else {
Siarhei Vishniakou580fb3a2023-05-05 15:02:20 -07002855 // DisplayInfo not found for this window on display windowHandle->getInfo()->displayId.
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002856 // TODO(b/198444055): Make this an error message after 'setInputWindows' API is removed.
2857 }
2858 return inputTarget;
2859}
2860
chaviw98318de2021-05-19 16:45:23 -05002861void InputDispatcher::addWindowTargetLocked(const sp<WindowInfoHandle>& windowHandle,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002862 ftl::Flags<InputTarget::Flags> targetFlags,
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08002863 std::bitset<MAX_POINTER_ID + 1> pointerIds,
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002864 std::optional<nsecs_t> firstDownTimeInTarget,
Siarhei Vishniakouf75cddb2022-10-25 10:42:16 -07002865 std::vector<InputTarget>& inputTargets) const {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002866 std::vector<InputTarget>::iterator it =
2867 std::find_if(inputTargets.begin(), inputTargets.end(),
2868 [&windowHandle](const InputTarget& inputTarget) {
2869 return inputTarget.inputChannel->getConnectionToken() ==
2870 windowHandle->getToken();
2871 });
Chavi Weingarten97b8eec2020-01-09 18:09:08 +00002872
chaviw98318de2021-05-19 16:45:23 -05002873 const WindowInfo* windowInfo = windowHandle->getInfo();
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002874
2875 if (it == inputTargets.end()) {
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002876 std::optional<InputTarget> target =
2877 createInputTargetLocked(windowHandle, targetFlags, firstDownTimeInTarget);
2878 if (!target) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002879 return;
2880 }
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002881 inputTargets.push_back(*target);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002882 it = inputTargets.end() - 1;
2883 }
2884
2885 ALOG_ASSERT(it->flags == targetFlags);
2886 ALOG_ASSERT(it->globalScaleFactor == windowInfo->globalScaleFactor);
2887
chaviw1ff3d1e2020-07-01 15:53:47 -07002888 it->addPointers(pointerIds, windowInfo->transform);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002889}
2890
Michael Wright3dd60e22019-03-27 22:06:44 +00002891void InputDispatcher::addGlobalMonitoringTargetsLocked(std::vector<InputTarget>& inputTargets,
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002892 int32_t displayId) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002893 auto monitorsIt = mGlobalMonitorsByDisplay.find(displayId);
2894 if (monitorsIt == mGlobalMonitorsByDisplay.end()) return;
Michael Wright3dd60e22019-03-27 22:06:44 +00002895
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002896 for (const Monitor& monitor : selectResponsiveMonitorsLocked(monitorsIt->second)) {
2897 InputTarget target;
2898 target.inputChannel = monitor.inputChannel;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002899 target.flags = InputTarget::Flags::DISPATCH_AS_IS;
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002900 // target.firstDownTimeInTarget is not set for global monitors. It is only required in split
2901 // touch and global monitoring works as intended even without setting firstDownTimeInTarget
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002902 if (const auto& it = mDisplayInfos.find(displayId); it != mDisplayInfos.end()) {
2903 target.displayTransform = it->second.transform;
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002904 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002905 target.setDefaultPointerTransform(target.displayTransform);
2906 inputTargets.push_back(target);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002907 }
2908}
2909
Robert Carrc9bf1d32020-04-13 17:21:08 -07002910/**
2911 * Indicate whether one window handle should be considered as obscuring
2912 * another window handle. We only check a few preconditions. Actually
2913 * checking the bounds is left to the caller.
2914 */
chaviw98318de2021-05-19 16:45:23 -05002915static bool canBeObscuredBy(const sp<WindowInfoHandle>& windowHandle,
2916 const sp<WindowInfoHandle>& otherHandle) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002917 // Compare by token so cloned layers aren't counted
2918 if (haveSameToken(windowHandle, otherHandle)) {
2919 return false;
2920 }
2921 auto info = windowHandle->getInfo();
2922 auto otherInfo = otherHandle->getInfo();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002923 if (otherInfo->inputConfig.test(WindowInfo::InputConfig::NOT_VISIBLE)) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002924 return false;
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002925 } else if (otherInfo->alpha == 0 &&
2926 otherInfo->inputConfig.test(WindowInfo::InputConfig::NOT_TOUCHABLE)) {
Bernardo Rufino653d2e02020-10-20 17:32:40 +00002927 // Those act as if they were invisible, so we don't need to flag them.
2928 // We do want to potentially flag touchable windows even if they have 0
2929 // opacity, since they can consume touches and alter the effects of the
2930 // user interaction (eg. apps that rely on
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002931 // Flags::WINDOW_IS_PARTIALLY_OBSCURED should still be told about those
Bernardo Rufino653d2e02020-10-20 17:32:40 +00002932 // windows), hence we also check for FLAG_NOT_TOUCHABLE.
2933 return false;
Bernardo Rufino8007daf2020-09-22 09:40:01 +00002934 } else if (info->ownerUid == otherInfo->ownerUid) {
2935 // If ownerUid is the same we don't generate occlusion events as there
2936 // is no security boundary within an uid.
Robert Carrc9bf1d32020-04-13 17:21:08 -07002937 return false;
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002938 } else if (otherInfo->inputConfig.test(gui::WindowInfo::InputConfig::TRUSTED_OVERLAY)) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002939 return false;
2940 } else if (otherInfo->displayId != info->displayId) {
2941 return false;
2942 }
2943 return true;
2944}
2945
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002946/**
2947 * Returns touch occlusion information in the form of TouchOcclusionInfo. To check if the touch is
2948 * untrusted, one should check:
2949 *
2950 * 1. If result.hasBlockingOcclusion is true.
2951 * If it's, it means the touch should be blocked due to a window with occlusion mode of
2952 * BLOCK_UNTRUSTED.
2953 *
2954 * 2. If result.obscuringOpacity > mMaximumObscuringOpacityForTouch.
2955 * If it is (and 1 is false), then the touch should be blocked because a stack of windows
2956 * (possibly only one) with occlusion mode of USE_OPACITY from one UID resulted in a composed
2957 * obscuring opacity above the threshold. Note that if there was no window of occlusion mode
2958 * USE_OPACITY, result.obscuringOpacity would've been 0 and since
2959 * mMaximumObscuringOpacityForTouch >= 0, the condition above would never be true.
2960 *
2961 * If neither of those is true, then it means the touch can be allowed.
2962 */
2963InputDispatcher::TouchOcclusionInfo InputDispatcher::computeTouchOcclusionInfoLocked(
chaviw98318de2021-05-19 16:45:23 -05002964 const sp<WindowInfoHandle>& windowHandle, int32_t x, int32_t y) const {
2965 const WindowInfo* windowInfo = windowHandle->getInfo();
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002966 int32_t displayId = windowInfo->displayId;
chaviw98318de2021-05-19 16:45:23 -05002967 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002968 TouchOcclusionInfo info;
2969 info.hasBlockingOcclusion = false;
2970 info.obscuringOpacity = 0;
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00002971 info.obscuringUid = gui::Uid::INVALID;
2972 std::map<gui::Uid, float> opacityByUid;
chaviw98318de2021-05-19 16:45:23 -05002973 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002974 if (windowHandle == otherHandle) {
2975 break; // All future windows are below us. Exit early.
2976 }
chaviw98318de2021-05-19 16:45:23 -05002977 const WindowInfo* otherInfo = otherHandle->getInfo();
Bernardo Rufino1ff9d592021-01-18 16:58:57 +00002978 if (canBeObscuredBy(windowHandle, otherHandle) && otherInfo->frameContainsPoint(x, y) &&
2979 !haveSameApplicationToken(windowInfo, otherInfo)) {
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002980 if (DEBUG_TOUCH_OCCLUSION) {
2981 info.debugInfo.push_back(
2982 dumpWindowForTouchOcclusion(otherInfo, /* isTouchedWindow */ false));
2983 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002984 // canBeObscuredBy() has returned true above, which means this window is untrusted, so
2985 // we perform the checks below to see if the touch can be propagated or not based on the
2986 // window's touch occlusion mode
2987 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::BLOCK_UNTRUSTED) {
2988 info.hasBlockingOcclusion = true;
2989 info.obscuringUid = otherInfo->ownerUid;
2990 info.obscuringPackage = otherInfo->packageName;
2991 break;
2992 }
2993 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::USE_OPACITY) {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00002994 const auto uid = otherInfo->ownerUid;
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002995 float opacity =
2996 (opacityByUid.find(uid) == opacityByUid.end()) ? 0 : opacityByUid[uid];
2997 // Given windows A and B:
2998 // opacity(A, B) = 1 - [1 - opacity(A)] * [1 - opacity(B)]
2999 opacity = 1 - (1 - opacity) * (1 - otherInfo->alpha);
3000 opacityByUid[uid] = opacity;
3001 if (opacity > info.obscuringOpacity) {
3002 info.obscuringOpacity = opacity;
3003 info.obscuringUid = uid;
3004 info.obscuringPackage = otherInfo->packageName;
3005 }
3006 }
3007 }
3008 }
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00003009 if (DEBUG_TOUCH_OCCLUSION) {
3010 info.debugInfo.push_back(
3011 dumpWindowForTouchOcclusion(windowInfo, /* isTouchedWindow */ true));
3012 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003013 return info;
3014}
3015
chaviw98318de2021-05-19 16:45:23 -05003016std::string InputDispatcher::dumpWindowForTouchOcclusion(const WindowInfo* info,
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00003017 bool isTouchedWindow) const {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003018 return StringPrintf(INDENT2 "* %spackage=%s/%s, id=%" PRId32 ", mode=%s, alpha=%.2f, "
Prabir Pradhan51e7db02022-02-07 06:02:57 -08003019 "frame=[%" PRId32 ",%" PRId32 "][%" PRId32 ",%" PRId32
3020 "], touchableRegion=%s, window={%s}, inputConfig={%s}, "
3021 "hasToken=%s, applicationInfo.name=%s, applicationInfo.token=%s\n",
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08003022 isTouchedWindow ? "[TOUCHED] " : "", info->packageName.c_str(),
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003023 info->ownerUid.toString().c_str(), info->id,
3024 toString(info->touchOcclusionMode).c_str(), info->alpha, info->frameLeft,
3025 info->frameTop, info->frameRight, info->frameBottom,
3026 dumpRegion(info->touchableRegion).c_str(), info->name.c_str(),
3027 info->inputConfig.string().c_str(), toString(info->token != nullptr),
3028 info->applicationInfo.name.c_str(),
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07003029 binderToString(info->applicationInfo.token).c_str());
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00003030}
3031
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003032bool InputDispatcher::isTouchTrustedLocked(const TouchOcclusionInfo& occlusionInfo) const {
3033 if (occlusionInfo.hasBlockingOcclusion) {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003034 ALOGW("Untrusted touch due to occlusion by %s/%s", occlusionInfo.obscuringPackage.c_str(),
3035 occlusionInfo.obscuringUid.toString().c_str());
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003036 return false;
3037 }
3038 if (occlusionInfo.obscuringOpacity > mMaximumObscuringOpacityForTouch) {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003039 ALOGW("Untrusted touch due to occlusion by %s/%s (obscuring opacity = "
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003040 "%.2f, maximum allowed = %.2f)",
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003041 occlusionInfo.obscuringPackage.c_str(), occlusionInfo.obscuringUid.toString().c_str(),
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003042 occlusionInfo.obscuringOpacity, mMaximumObscuringOpacityForTouch);
3043 return false;
3044 }
3045 return true;
3046}
3047
chaviw98318de2021-05-19 16:45:23 -05003048bool InputDispatcher::isWindowObscuredAtPointLocked(const sp<WindowInfoHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003049 int32_t x, int32_t y) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003050 int32_t displayId = windowHandle->getInfo()->displayId;
chaviw98318de2021-05-19 16:45:23 -05003051 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
3052 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07003053 if (windowHandle == otherHandle) {
3054 break; // All future windows are below us. Exit early.
Michael Wrightd02c5b62014-02-10 15:10:22 -08003055 }
chaviw98318de2021-05-19 16:45:23 -05003056 const WindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07003057 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08003058 otherInfo->frameContainsPoint(x, y)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003059 return true;
3060 }
3061 }
3062 return false;
3063}
3064
chaviw98318de2021-05-19 16:45:23 -05003065bool InputDispatcher::isWindowObscuredLocked(const sp<WindowInfoHandle>& windowHandle) const {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07003066 int32_t displayId = windowHandle->getInfo()->displayId;
chaviw98318de2021-05-19 16:45:23 -05003067 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
3068 const WindowInfo* windowInfo = windowHandle->getInfo();
3069 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07003070 if (windowHandle == otherHandle) {
3071 break; // All future windows are below us. Exit early.
Michael Wrightcdcd8f22016-03-22 16:52:13 -07003072 }
chaviw98318de2021-05-19 16:45:23 -05003073 const WindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07003074 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08003075 otherInfo->overlaps(windowInfo)) {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07003076 return true;
3077 }
3078 }
3079 return false;
3080}
3081
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08003082std::string InputDispatcher::getApplicationWindowLabel(
chaviw98318de2021-05-19 16:45:23 -05003083 const InputApplicationHandle* applicationHandle, const sp<WindowInfoHandle>& windowHandle) {
Yi Kong9b14ac62018-07-17 13:48:38 -07003084 if (applicationHandle != nullptr) {
3085 if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07003086 return applicationHandle->getName() + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003087 } else {
3088 return applicationHandle->getName();
3089 }
Yi Kong9b14ac62018-07-17 13:48:38 -07003090 } else if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07003091 return windowHandle->getInfo()->applicationInfo.name + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003092 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003093 return "<unknown application or window>";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003094 }
3095}
3096
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003097void InputDispatcher::pokeUserActivityLocked(const EventEntry& eventEntry) {
Antonio Kantekf16f2832021-09-28 04:39:20 +00003098 if (!isUserActivityEvent(eventEntry)) {
3099 // Not poking user activity if the event type does not represent a user activity
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003100 return;
3101 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003102 int32_t displayId = getTargetDisplayId(eventEntry);
chaviw98318de2021-05-19 16:45:23 -05003103 sp<WindowInfoHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Josep del Riob3981622023-04-18 15:49:45 +00003104 const WindowInfo* windowDisablingUserActivityInfo = nullptr;
Tiger Huang721e26f2018-07-24 22:26:19 +08003105 if (focusedWindowHandle != nullptr) {
chaviw98318de2021-05-19 16:45:23 -05003106 const WindowInfo* info = focusedWindowHandle->getInfo();
Prabir Pradhan51e7db02022-02-07 06:02:57 -08003107 if (info->inputConfig.test(WindowInfo::InputConfig::DISABLE_USER_ACTIVITY)) {
Josep del Riob3981622023-04-18 15:49:45 +00003108 windowDisablingUserActivityInfo = info;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003109 }
3110 }
3111
3112 int32_t eventType = USER_ACTIVITY_EVENT_OTHER;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003113 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003114 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003115 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
3116 if (motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003117 return;
3118 }
Josep del Riob3981622023-04-18 15:49:45 +00003119 if (windowDisablingUserActivityInfo != nullptr) {
3120 if (DEBUG_DISPATCH_CYCLE) {
3121 ALOGD("Not poking user activity: disabled by window '%s'.",
3122 windowDisablingUserActivityInfo->name.c_str());
3123 }
3124 return;
3125 }
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003126 if (MotionEvent::isTouchEvent(motionEntry.source, motionEntry.action)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003127 eventType = USER_ACTIVITY_EVENT_TOUCH;
3128 }
3129 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003130 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003131 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003132 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
3133 if (keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003134 return;
3135 }
Josep del Riob3981622023-04-18 15:49:45 +00003136 // If the key code is unknown, we don't consider it user activity
3137 if (keyEntry.keyCode == AKEYCODE_UNKNOWN) {
3138 return;
3139 }
3140 // Don't inhibit events that were intercepted or are not passed to
3141 // the apps, like system shortcuts
3142 if (windowDisablingUserActivityInfo != nullptr &&
3143 keyEntry.interceptKeyResult != KeyEntry::InterceptKeyResult::SKIP &&
3144 keyEntry.policyFlags & POLICY_FLAG_PASS_TO_USER) {
3145 if (DEBUG_DISPATCH_CYCLE) {
3146 ALOGD("Not poking user activity: disabled by window '%s'.",
3147 windowDisablingUserActivityInfo->name.c_str());
3148 }
3149 return;
3150 }
3151
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003152 eventType = USER_ACTIVITY_EVENT_BUTTON;
3153 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003154 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00003155 default: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003156 LOG_ALWAYS_FATAL("%s events are not user activity",
Dominik Laskowski75788452021-02-09 18:51:25 -08003157 ftl::enum_string(eventEntry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003158 break;
3159 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003160 }
3161
Prabir Pradhancef936d2021-07-21 16:17:52 +00003162 auto command = [this, eventTime = eventEntry.eventTime, eventType, displayId]()
3163 REQUIRES(mLock) {
3164 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00003165 mPolicy.pokeUserActivity(eventTime, eventType, displayId);
Prabir Pradhancef936d2021-07-21 16:17:52 +00003166 };
3167 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003168}
3169
3170void InputDispatcher::prepareDispatchCycleLocked(nsecs_t currentTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003171 const std::shared_ptr<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003172 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003173 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003174 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003175 std::string message =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003176 StringPrintf("prepareDispatchCycleLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003177 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00003178 ATRACE_NAME(message.c_str());
3179 }
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003180 if (DEBUG_DISPATCH_CYCLE) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003181 ALOGD("channel '%s' ~ prepareDispatchCycle - flags=%s, "
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08003182 "globalScaleFactor=%f, pointerIds=%s %s",
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003183 connection->getInputChannelName().c_str(), inputTarget.flags.string().c_str(),
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08003184 inputTarget.globalScaleFactor, bitsetToString(inputTarget.pointerIds).c_str(),
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003185 inputTarget.getPointerInfoString().c_str());
3186 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003187
3188 // Skip this event if the connection status is not normal.
3189 // We don't want to enqueue additional outbound events if the connection is broken.
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003190 if (connection->status != Connection::Status::NORMAL) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003191 if (DEBUG_DISPATCH_CYCLE) {
3192 ALOGD("channel '%s' ~ Dropping event because the channel status is %s",
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003193 connection->getInputChannelName().c_str(),
3194 ftl::enum_string(connection->status).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003195 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003196 return;
3197 }
3198
3199 // Split a motion event if needed.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003200 if (inputTarget.flags.test(InputTarget::Flags::SPLIT)) {
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003201 LOG_ALWAYS_FATAL_IF(eventEntry->type != EventEntry::Type::MOTION,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003202 "Entry type %s should not have Flags::SPLIT",
Dominik Laskowski75788452021-02-09 18:51:25 -08003203 ftl::enum_string(eventEntry->type).c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003204
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003205 const MotionEntry& originalMotionEntry = static_cast<const MotionEntry&>(*eventEntry);
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003206 if (inputTarget.pointerIds.count() != originalMotionEntry.pointerCount) {
Siarhei Vishniakou16e4fa02023-02-16 17:48:56 -08003207 if (!inputTarget.firstDownTimeInTarget.has_value()) {
3208 logDispatchStateLocked();
3209 LOG(FATAL) << "Splitting motion events requires a down time to be set for the "
3210 "target on connection "
3211 << connection->getInputChannelName() << " for "
3212 << originalMotionEntry.getDescription();
3213 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003214 std::unique_ptr<MotionEntry> splitMotionEntry =
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00003215 splitMotionEvent(originalMotionEntry, inputTarget.pointerIds,
3216 inputTarget.firstDownTimeInTarget.value());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003217 if (!splitMotionEntry) {
3218 return; // split event was dropped
3219 }
Arthur Hungb3307ee2021-10-14 10:57:37 +00003220 if (splitMotionEntry->action == AMOTION_EVENT_ACTION_CANCEL) {
3221 std::string reason = std::string("reason=pointer cancel on split window");
3222 android_log_event_list(LOGTAG_INPUT_CANCEL)
3223 << connection->getInputChannelName().c_str() << reason << LOG_ID_EVENTS;
3224 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003225 if (DEBUG_FOCUS) {
3226 ALOGD("channel '%s' ~ Split motion event.",
3227 connection->getInputChannelName().c_str());
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003228 logOutboundMotionDetails(" ", *splitMotionEntry);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003229 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003230 enqueueDispatchEntriesLocked(currentTime, connection, std::move(splitMotionEntry),
3231 inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003232 return;
3233 }
3234 }
3235
3236 // Not splitting. Enqueue dispatch entries for the event as is.
3237 enqueueDispatchEntriesLocked(currentTime, connection, eventEntry, inputTarget);
3238}
3239
3240void InputDispatcher::enqueueDispatchEntriesLocked(nsecs_t currentTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003241 const std::shared_ptr<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003242 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003243 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003244 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003245 std::string message =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003246 StringPrintf("enqueueDispatchEntriesLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003247 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00003248 ATRACE_NAME(message.c_str());
3249 }
Siarhei Vishniakou5cee1e32022-11-29 12:35:39 -08003250 LOG_ALWAYS_FATAL_IF(!inputTarget.flags.any(InputTarget::DISPATCH_MASK),
3251 "No dispatch flags are set for %s", eventEntry->getDescription().c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00003252
hongzuo liu95785e22022-09-06 02:51:35 +00003253 const bool wasEmpty = connection->outboundQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003254
3255 // Enqueue dispatch entries for the requested modes.
chaviw8c9cf542019-03-25 13:02:48 -07003256 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003257 InputTarget::Flags::DISPATCH_AS_HOVER_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07003258 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003259 InputTarget::Flags::DISPATCH_AS_OUTSIDE);
chaviw8c9cf542019-03-25 13:02:48 -07003260 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003261 InputTarget::Flags::DISPATCH_AS_HOVER_ENTER);
chaviw8c9cf542019-03-25 13:02:48 -07003262 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003263 InputTarget::Flags::DISPATCH_AS_IS);
chaviw8c9cf542019-03-25 13:02:48 -07003264 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003265 InputTarget::Flags::DISPATCH_AS_SLIPPERY_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07003266 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003267 InputTarget::Flags::DISPATCH_AS_SLIPPERY_ENTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003268
3269 // If the outbound queue was previously empty, start the dispatch cycle going.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003270 if (wasEmpty && !connection->outboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003271 startDispatchCycleLocked(currentTime, connection);
3272 }
3273}
3274
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003275void InputDispatcher::enqueueDispatchEntryLocked(const std::shared_ptr<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003276 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003277 const InputTarget& inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003278 ftl::Flags<InputTarget::Flags> dispatchMode) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003279 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003280 std::string message = StringPrintf("enqueueDispatchEntry(inputChannel=%s, dispatchMode=%s)",
3281 connection->getInputChannelName().c_str(),
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003282 dispatchMode.string().c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00003283 ATRACE_NAME(message.c_str());
3284 }
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003285 ftl::Flags<InputTarget::Flags> inputTargetFlags = inputTarget.flags;
3286 if (!inputTargetFlags.any(dispatchMode)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003287 return;
3288 }
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003289
3290 inputTargetFlags.clear(InputTarget::DISPATCH_MASK);
3291 inputTargetFlags |= dispatchMode;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003292
3293 // This is a new event.
3294 // Enqueue a new dispatch entry onto the outbound queue for this connection.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003295 std::unique_ptr<DispatchEntry> dispatchEntry =
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003296 createDispatchEntry(inputTarget, eventEntry, inputTargetFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003297
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003298 // Use the eventEntry from dispatchEntry since the entry may have changed and can now be a
3299 // different EventEntry than what was passed in.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003300 EventEntry& newEntry = *(dispatchEntry->eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003301 // Apply target flags and update the connection's input state.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003302 switch (newEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003303 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003304 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003305 dispatchEntry->resolvedEventId = keyEntry.id;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003306 dispatchEntry->resolvedAction = keyEntry.action;
3307 dispatchEntry->resolvedFlags = keyEntry.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003308
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003309 if (!connection->inputState.trackKey(keyEntry, dispatchEntry->resolvedAction,
3310 dispatchEntry->resolvedFlags)) {
Siarhei Vishniakouc94dafe2023-05-26 10:24:19 -07003311 LOG(WARNING) << "channel " << connection->getInputChannelName()
3312 << "~ dropping inconsistent event: " << *dispatchEntry;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003313 return; // skip the inconsistent event
3314 }
3315 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003316 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003317
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003318 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003319 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003320 // Assign a default value to dispatchEntry that will never be generated by InputReader,
3321 // and assign a InputDispatcher value if it doesn't change in the if-else chain below.
3322 constexpr int32_t DEFAULT_RESOLVED_EVENT_ID =
3323 static_cast<int32_t>(IdGenerator::Source::OTHER);
3324 dispatchEntry->resolvedEventId = DEFAULT_RESOLVED_EVENT_ID;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003325 if (dispatchMode.test(InputTarget::Flags::DISPATCH_AS_OUTSIDE)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003326 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_OUTSIDE;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003327 } else if (dispatchMode.test(InputTarget::Flags::DISPATCH_AS_HOVER_EXIT)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003328 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_EXIT;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003329 } else if (dispatchMode.test(InputTarget::Flags::DISPATCH_AS_HOVER_ENTER)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003330 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003331 } else if (dispatchMode.test(InputTarget::Flags::DISPATCH_AS_SLIPPERY_EXIT)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003332 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_CANCEL;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003333 } else if (dispatchMode.test(InputTarget::Flags::DISPATCH_AS_SLIPPERY_ENTER)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003334 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_DOWN;
3335 } else {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003336 dispatchEntry->resolvedAction = motionEntry.action;
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003337 dispatchEntry->resolvedEventId = motionEntry.id;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003338 }
3339 if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_HOVER_MOVE &&
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003340 !connection->inputState.isHovering(motionEntry.deviceId, motionEntry.source,
3341 motionEntry.displayId)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003342 if (DEBUG_DISPATCH_CYCLE) {
3343 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: filling in missing hover "
3344 "enter event",
3345 connection->getInputChannelName().c_str());
3346 }
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00003347 // We keep the 'resolvedEventId' here equal to the original 'motionEntry.id' because
3348 // this is a one-to-one event conversion.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003349 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
3350 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003351
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003352 dispatchEntry->resolvedFlags = motionEntry.flags;
Siarhei Vishniakou1ae72f12023-01-29 12:55:30 -08003353 if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_CANCEL) {
3354 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_CANCELED;
3355 }
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003356 if (dispatchEntry->targetFlags.test(InputTarget::Flags::WINDOW_IS_OBSCURED)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003357 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED;
3358 }
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003359 if (dispatchEntry->targetFlags.test(InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003360 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
3361 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003362
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003363 if (!connection->inputState.trackMotion(motionEntry, dispatchEntry->resolvedAction,
3364 dispatchEntry->resolvedFlags)) {
Siarhei Vishniakouc94dafe2023-05-26 10:24:19 -07003365 LOG(WARNING) << "channel " << connection->getInputChannelName()
3366 << "~ dropping inconsistent event: " << *dispatchEntry;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003367 return; // skip the inconsistent event
3368 }
3369
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003370 dispatchEntry->resolvedEventId =
3371 dispatchEntry->resolvedEventId == DEFAULT_RESOLVED_EVENT_ID
3372 ? mIdGenerator.nextId()
3373 : motionEntry.id;
3374 if (ATRACE_ENABLED() && dispatchEntry->resolvedEventId != motionEntry.id) {
3375 std::string message = StringPrintf("Transmute MotionEvent(id=0x%" PRIx32
3376 ") to MotionEvent(id=0x%" PRIx32 ").",
3377 motionEntry.id, dispatchEntry->resolvedEventId);
3378 ATRACE_NAME(message.c_str());
3379 }
3380
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08003381 if ((motionEntry.flags & AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE) &&
3382 (motionEntry.policyFlags & POLICY_FLAG_TRUSTED)) {
3383 // Skip reporting pointer down outside focus to the policy.
3384 break;
3385 }
3386
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003387 dispatchPointerDownOutsideFocus(motionEntry.source, dispatchEntry->resolvedAction,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003388 inputTarget.inputChannel->getConnectionToken());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003389
3390 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003391 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003392 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003393 case EventEntry::Type::TOUCH_MODE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08003394 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
3395 case EventEntry::Type::DRAG: {
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003396 break;
3397 }
Chris Yef59a2f42020-10-16 12:55:26 -07003398 case EventEntry::Type::SENSOR: {
3399 LOG_ALWAYS_FATAL("SENSOR events should not go to apps via input channel");
3400 break;
3401 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003402 case EventEntry::Type::CONFIGURATION_CHANGED:
3403 case EventEntry::Type::DEVICE_RESET: {
3404 LOG_ALWAYS_FATAL("%s events should not go to apps",
Dominik Laskowski75788452021-02-09 18:51:25 -08003405 ftl::enum_string(newEntry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003406 break;
3407 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003408 }
3409
3410 // Remember that we are waiting for this dispatch to complete.
3411 if (dispatchEntry->hasForegroundTarget()) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003412 incrementPendingForegroundDispatches(newEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003413 }
3414
3415 // Enqueue the dispatch entry.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003416 connection->outboundQueue.push_back(dispatchEntry.release());
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003417 traceOutboundQueueLength(*connection);
chaviw8c9cf542019-03-25 13:02:48 -07003418}
3419
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003420/**
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003421 * This function is for debugging and metrics collection. It has two roles.
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003422 *
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003423 * The first role is to log input interaction with windows, which helps determine what the user was
3424 * interacting with. For example, if user is touching launcher, we will see an input_interaction log
3425 * that user started interacting with launcher window, as well as any other window that received
3426 * that gesture, such as the wallpaper or other spy windows. A new input_interaction is only logged
3427 * when the set of tokens that received the event changes. It is not logged again as long as the
3428 * user is interacting with the same windows.
3429 *
3430 * The second role is to track input device activity for metrics collection. For each input event,
3431 * we report the set of UIDs that the input device interacted with to the policy. Unlike for the
3432 * input_interaction logs, the device interaction is reported even when the set of interaction
3433 * tokens do not change.
3434 *
3435 * For these purposes, we do not count ACTION_OUTSIDE, ACTION_UP and ACTION_CANCEL actions as
3436 * interaction. This includes up and cancel events for both keys and motions.
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003437 */
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003438void InputDispatcher::processInteractionsLocked(const EventEntry& entry,
3439 const std::vector<InputTarget>& targets) {
3440 int32_t deviceId;
3441 nsecs_t eventTime;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003442 // Skip ACTION_UP events, and all events other than keys and motions
3443 if (entry.type == EventEntry::Type::KEY) {
3444 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
3445 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
3446 return;
3447 }
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003448 deviceId = keyEntry.deviceId;
3449 eventTime = keyEntry.eventTime;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003450 } else if (entry.type == EventEntry::Type::MOTION) {
3451 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
3452 if (motionEntry.action == AMOTION_EVENT_ACTION_UP ||
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003453 motionEntry.action == AMOTION_EVENT_ACTION_CANCEL ||
3454 MotionEvent::getActionMasked(motionEntry.action) == AMOTION_EVENT_ACTION_POINTER_UP) {
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003455 return;
3456 }
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003457 deviceId = motionEntry.deviceId;
3458 eventTime = motionEntry.eventTime;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003459 } else {
3460 return; // Not a key or a motion
3461 }
3462
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003463 std::set<gui::Uid> interactionUids;
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07003464 std::unordered_set<sp<IBinder>, StrongPointerHash<IBinder>> newConnectionTokens;
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003465 std::vector<std::shared_ptr<Connection>> newConnections;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003466 for (const InputTarget& target : targets) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003467 if (target.flags.test(InputTarget::Flags::DISPATCH_AS_OUTSIDE)) {
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003468 continue; // Skip windows that receive ACTION_OUTSIDE
3469 }
3470
3471 sp<IBinder> token = target.inputChannel->getConnectionToken();
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003472 std::shared_ptr<Connection> connection = getConnectionLocked(token);
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003473 if (connection == nullptr) {
3474 continue;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003475 }
3476 newConnectionTokens.insert(std::move(token));
3477 newConnections.emplace_back(connection);
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003478 if (target.windowHandle) {
3479 interactionUids.emplace(target.windowHandle->getInfo()->ownerUid);
3480 }
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003481 }
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003482
3483 auto command = [this, deviceId, eventTime, uids = std::move(interactionUids)]()
3484 REQUIRES(mLock) {
3485 scoped_unlock unlock(mLock);
3486 mPolicy.notifyDeviceInteraction(deviceId, eventTime, uids);
3487 };
3488 postCommandLocked(std::move(command));
3489
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003490 if (newConnectionTokens == mInteractionConnectionTokens) {
3491 return; // no change
3492 }
3493 mInteractionConnectionTokens = newConnectionTokens;
3494
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003495 std::string targetList;
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003496 for (const std::shared_ptr<Connection>& connection : newConnections) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003497 targetList += connection->getWindowName() + ", ";
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003498 }
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003499 std::string message = "Interaction with: " + targetList;
3500 if (targetList.empty()) {
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003501 message += "<none>";
3502 }
3503 android_log_event_list(LOGTAG_INPUT_INTERACTION) << message << LOG_ID_EVENTS;
3504}
3505
chaviwfd6d3512019-03-25 13:23:49 -07003506void InputDispatcher::dispatchPointerDownOutsideFocus(uint32_t source, int32_t action,
Vishnu Nairad321cd2020-08-20 16:40:21 -07003507 const sp<IBinder>& token) {
chaviw8c9cf542019-03-25 13:02:48 -07003508 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
chaviwfd6d3512019-03-25 13:23:49 -07003509 uint32_t maskedSource = source & AINPUT_SOURCE_CLASS_MASK;
3510 if (maskedSource != AINPUT_SOURCE_CLASS_POINTER || maskedAction != AMOTION_EVENT_ACTION_DOWN) {
chaviw8c9cf542019-03-25 13:02:48 -07003511 return;
3512 }
3513
Vishnu Nairc519ff72021-01-21 08:23:08 -08003514 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07003515 if (focusedToken == token) {
3516 // ignore since token is focused
chaviw8c9cf542019-03-25 13:02:48 -07003517 return;
3518 }
3519
Prabir Pradhancef936d2021-07-21 16:17:52 +00003520 auto command = [this, token]() REQUIRES(mLock) {
3521 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00003522 mPolicy.onPointerDownOutsideFocus(token);
Prabir Pradhancef936d2021-07-21 16:17:52 +00003523 };
3524 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003525}
3526
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003527status_t InputDispatcher::publishMotionEvent(Connection& connection,
3528 DispatchEntry& dispatchEntry) const {
3529 const EventEntry& eventEntry = *(dispatchEntry.eventEntry);
3530 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
3531
3532 PointerCoords scaledCoords[MAX_POINTERS];
3533 const PointerCoords* usingCoords = motionEntry.pointerCoords;
3534
3535 // Set the X and Y offset and X and Y scale depending on the input source.
3536 if ((motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) &&
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003537 !(dispatchEntry.targetFlags.test(InputTarget::Flags::ZERO_COORDS))) {
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003538 float globalScaleFactor = dispatchEntry.globalScaleFactor;
3539 if (globalScaleFactor != 1.0f) {
3540 for (uint32_t i = 0; i < motionEntry.pointerCount; i++) {
3541 scaledCoords[i] = motionEntry.pointerCoords[i];
3542 // Don't apply window scale here since we don't want scale to affect raw
3543 // coordinates. The scale will be sent back to the client and applied
3544 // later when requesting relative coordinates.
Harry Cutts33476232023-01-30 19:57:29 +00003545 scaledCoords[i].scale(globalScaleFactor, /*windowXScale=*/1, /*windowYScale=*/1);
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003546 }
3547 usingCoords = scaledCoords;
3548 }
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003549 } else if (dispatchEntry.targetFlags.test(InputTarget::Flags::ZERO_COORDS)) {
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003550 // We don't want the dispatch target to know the coordinates
3551 for (uint32_t i = 0; i < motionEntry.pointerCount; i++) {
3552 scaledCoords[i].clear();
3553 }
3554 usingCoords = scaledCoords;
3555 }
3556
3557 std::array<uint8_t, 32> hmac = getSignature(motionEntry, dispatchEntry);
3558
3559 // Publish the motion event.
3560 return connection.inputPublisher
3561 .publishMotionEvent(dispatchEntry.seq, dispatchEntry.resolvedEventId,
3562 motionEntry.deviceId, motionEntry.source, motionEntry.displayId,
3563 std::move(hmac), dispatchEntry.resolvedAction,
3564 motionEntry.actionButton, dispatchEntry.resolvedFlags,
3565 motionEntry.edgeFlags, motionEntry.metaState,
3566 motionEntry.buttonState, motionEntry.classification,
3567 dispatchEntry.transform, motionEntry.xPrecision,
3568 motionEntry.yPrecision, motionEntry.xCursorPosition,
3569 motionEntry.yCursorPosition, dispatchEntry.rawTransform,
3570 motionEntry.downTime, motionEntry.eventTime,
3571 motionEntry.pointerCount, motionEntry.pointerProperties,
3572 usingCoords);
3573}
3574
Michael Wrightd02c5b62014-02-10 15:10:22 -08003575void InputDispatcher::startDispatchCycleLocked(nsecs_t currentTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003576 const std::shared_ptr<Connection>& connection) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003577 if (ATRACE_ENABLED()) {
3578 std::string message = StringPrintf("startDispatchCycleLocked(inputChannel=%s)",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003579 connection->getInputChannelName().c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00003580 ATRACE_NAME(message.c_str());
3581 }
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003582 if (DEBUG_DISPATCH_CYCLE) {
3583 ALOGD("channel '%s' ~ startDispatchCycle", connection->getInputChannelName().c_str());
3584 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003585
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003586 while (connection->status == Connection::Status::NORMAL && !connection->outboundQueue.empty()) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003587 DispatchEntry* dispatchEntry = connection->outboundQueue.front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003588 dispatchEntry->deliveryTime = currentTime;
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003589 const std::chrono::nanoseconds timeout = getDispatchingTimeoutLocked(connection);
Siarhei Vishniakou70622952020-07-30 11:17:23 -05003590 dispatchEntry->timeoutTime = currentTime + timeout.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003591
3592 // Publish the event.
3593 status_t status;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003594 const EventEntry& eventEntry = *(dispatchEntry->eventEntry);
3595 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003596 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003597 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
3598 std::array<uint8_t, 32> hmac = getSignature(keyEntry, *dispatchEntry);
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08003599 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
3600 LOG(DEBUG) << "Publishing " << *dispatchEntry << " to "
3601 << connection->getInputChannelName();
3602 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003603
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003604 // Publish the key event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003605 status = connection->inputPublisher
3606 .publishKeyEvent(dispatchEntry->seq,
3607 dispatchEntry->resolvedEventId, keyEntry.deviceId,
3608 keyEntry.source, keyEntry.displayId,
3609 std::move(hmac), dispatchEntry->resolvedAction,
3610 dispatchEntry->resolvedFlags, keyEntry.keyCode,
3611 keyEntry.scanCode, keyEntry.metaState,
3612 keyEntry.repeatCount, keyEntry.downTime,
3613 keyEntry.eventTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003614 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003615 }
3616
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003617 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08003618 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
3619 LOG(DEBUG) << "Publishing " << *dispatchEntry << " to "
3620 << connection->getInputChannelName();
3621 }
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003622 status = publishMotionEvent(*connection, *dispatchEntry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003623 break;
3624 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003625
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003626 case EventEntry::Type::FOCUS: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003627 const FocusEntry& focusEntry = static_cast<const FocusEntry&>(eventEntry);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003628 status = connection->inputPublisher.publishFocusEvent(dispatchEntry->seq,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003629 focusEntry.id,
Antonio Kantek3cfec7b2021-11-05 18:26:17 -07003630 focusEntry.hasFocus);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003631 break;
3632 }
3633
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003634 case EventEntry::Type::TOUCH_MODE_CHANGED: {
3635 const TouchModeEntry& touchModeEntry =
3636 static_cast<const TouchModeEntry&>(eventEntry);
3637 status = connection->inputPublisher
3638 .publishTouchModeEvent(dispatchEntry->seq, touchModeEntry.id,
3639 touchModeEntry.inTouchMode);
3640
3641 break;
3642 }
3643
Prabir Pradhan99987712020-11-10 18:43:05 -08003644 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
3645 const auto& captureEntry =
3646 static_cast<const PointerCaptureChangedEntry&>(eventEntry);
3647 status = connection->inputPublisher
3648 .publishCaptureEvent(dispatchEntry->seq, captureEntry.id,
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00003649 captureEntry.pointerCaptureRequest.enable);
Prabir Pradhan99987712020-11-10 18:43:05 -08003650 break;
3651 }
3652
arthurhungb89ccb02020-12-30 16:19:01 +08003653 case EventEntry::Type::DRAG: {
3654 const DragEntry& dragEntry = static_cast<const DragEntry&>(eventEntry);
3655 status = connection->inputPublisher.publishDragEvent(dispatchEntry->seq,
3656 dragEntry.id, dragEntry.x,
3657 dragEntry.y,
3658 dragEntry.isExiting);
3659 break;
3660 }
3661
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003662 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07003663 case EventEntry::Type::DEVICE_RESET:
3664 case EventEntry::Type::SENSOR: {
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003665 LOG_ALWAYS_FATAL("Should never start dispatch cycles for %s events",
Dominik Laskowski75788452021-02-09 18:51:25 -08003666 ftl::enum_string(eventEntry.type).c_str());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003667 return;
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003668 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003669 }
3670
3671 // Check the result.
3672 if (status) {
3673 if (status == WOULD_BLOCK) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003674 if (connection->waitQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003675 ALOGE("channel '%s' ~ Could not publish event because the pipe is full. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003676 "This is unexpected because the wait queue is empty, so the pipe "
3677 "should be empty and we shouldn't have any problems writing an "
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +00003678 "event to it, status=%s(%d)",
3679 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3680 status);
Harry Cutts33476232023-01-30 19:57:29 +00003681 abortBrokenDispatchCycleLocked(currentTime, connection, /*notify=*/true);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003682 } else {
3683 // Pipe is full and we are waiting for the app to finish process some events
3684 // before sending more events to it.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003685 if (DEBUG_DISPATCH_CYCLE) {
3686 ALOGD("channel '%s' ~ Could not publish event because the pipe is full, "
3687 "waiting for the application to catch up",
3688 connection->getInputChannelName().c_str());
3689 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003690 }
3691 } else {
3692 ALOGE("channel '%s' ~ Could not publish event due to an unexpected error, "
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +00003693 "status=%s(%d)",
3694 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3695 status);
Harry Cutts33476232023-01-30 19:57:29 +00003696 abortBrokenDispatchCycleLocked(currentTime, connection, /*notify=*/true);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003697 }
3698 return;
3699 }
3700
3701 // Re-enqueue the event on the wait queue.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003702 connection->outboundQueue.erase(std::remove(connection->outboundQueue.begin(),
3703 connection->outboundQueue.end(),
3704 dispatchEntry));
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003705 traceOutboundQueueLength(*connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003706 connection->waitQueue.push_back(dispatchEntry);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003707 if (connection->responsive) {
3708 mAnrTracker.insert(dispatchEntry->timeoutTime,
3709 connection->inputChannel->getConnectionToken());
3710 }
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003711 traceWaitQueueLength(*connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003712 }
3713}
3714
chaviw09c8d2d2020-08-24 15:48:26 -07003715std::array<uint8_t, 32> InputDispatcher::sign(const VerifiedInputEvent& event) const {
3716 size_t size;
3717 switch (event.type) {
3718 case VerifiedInputEvent::Type::KEY: {
3719 size = sizeof(VerifiedKeyEvent);
3720 break;
3721 }
3722 case VerifiedInputEvent::Type::MOTION: {
3723 size = sizeof(VerifiedMotionEvent);
3724 break;
3725 }
3726 }
3727 const uint8_t* start = reinterpret_cast<const uint8_t*>(&event);
3728 return mHmacKeyManager.sign(start, size);
3729}
3730
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003731const std::array<uint8_t, 32> InputDispatcher::getSignature(
3732 const MotionEntry& motionEntry, const DispatchEntry& dispatchEntry) const {
Siarhei Vishniakoubf880522023-05-01 11:03:22 -07003733 const int32_t actionMasked = MotionEvent::getActionMasked(dispatchEntry.resolvedAction);
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003734 if (actionMasked != AMOTION_EVENT_ACTION_UP && actionMasked != AMOTION_EVENT_ACTION_DOWN) {
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003735 // Only sign events up and down events as the purely move events
3736 // are tied to their up/down counterparts so signing would be redundant.
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003737 return INVALID_HMAC;
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003738 }
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003739
3740 VerifiedMotionEvent verifiedEvent =
3741 verifiedMotionEventFromMotionEntry(motionEntry, dispatchEntry.rawTransform);
3742 verifiedEvent.actionMasked = actionMasked;
3743 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_MOTION_EVENT_FLAGS;
3744 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003745}
3746
3747const std::array<uint8_t, 32> InputDispatcher::getSignature(
3748 const KeyEntry& keyEntry, const DispatchEntry& dispatchEntry) const {
3749 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEntry(keyEntry);
3750 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_KEY_EVENT_FLAGS;
3751 verifiedEvent.action = dispatchEntry.resolvedAction;
chaviw09c8d2d2020-08-24 15:48:26 -07003752 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003753}
3754
Michael Wrightd02c5b62014-02-10 15:10:22 -08003755void InputDispatcher::finishDispatchCycleLocked(nsecs_t currentTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003756 const std::shared_ptr<Connection>& connection,
3757 uint32_t seq, bool handled, nsecs_t consumeTime) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003758 if (DEBUG_DISPATCH_CYCLE) {
3759 ALOGD("channel '%s' ~ finishDispatchCycle - seq=%u, handled=%s",
3760 connection->getInputChannelName().c_str(), seq, toString(handled));
3761 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003762
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003763 if (connection->status == Connection::Status::BROKEN ||
3764 connection->status == Connection::Status::ZOMBIE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003765 return;
3766 }
3767
3768 // Notify other system components and prepare to start the next dispatch cycle.
Prabir Pradhancef936d2021-07-21 16:17:52 +00003769 auto command = [this, currentTime, connection, seq, handled, consumeTime]() REQUIRES(mLock) {
3770 doDispatchCycleFinishedCommand(currentTime, connection, seq, handled, consumeTime);
3771 };
3772 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003773}
3774
3775void InputDispatcher::abortBrokenDispatchCycleLocked(nsecs_t currentTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003776 const std::shared_ptr<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003777 bool notify) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003778 if (DEBUG_DISPATCH_CYCLE) {
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07003779 LOG(DEBUG) << "channel '" << connection->getInputChannelName() << "'~ " << __func__
3780 << " - notify=" << toString(notify);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003781 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003782
3783 // Clear the dispatch queues.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003784 drainDispatchQueue(connection->outboundQueue);
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003785 traceOutboundQueueLength(*connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003786 drainDispatchQueue(connection->waitQueue);
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003787 traceWaitQueueLength(*connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003788
3789 // The connection appears to be unrecoverably broken.
3790 // Ignore already broken or zombie connections.
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003791 if (connection->status == Connection::Status::NORMAL) {
3792 connection->status = Connection::Status::BROKEN;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003793
3794 if (notify) {
3795 // Notify other system components.
Prabir Pradhancef936d2021-07-21 16:17:52 +00003796 ALOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
3797 connection->getInputChannelName().c_str());
3798
3799 auto command = [this, connection]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00003800 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00003801 mPolicy.notifyInputChannelBroken(connection->inputChannel->getConnectionToken());
Prabir Pradhancef936d2021-07-21 16:17:52 +00003802 };
3803 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003804 }
3805 }
3806}
3807
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003808void InputDispatcher::drainDispatchQueue(std::deque<DispatchEntry*>& queue) {
3809 while (!queue.empty()) {
3810 DispatchEntry* dispatchEntry = queue.front();
3811 queue.pop_front();
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003812 releaseDispatchEntry(dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003813 }
3814}
3815
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003816void InputDispatcher::releaseDispatchEntry(DispatchEntry* dispatchEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003817 if (dispatchEntry->hasForegroundTarget()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003818 decrementPendingForegroundDispatches(*(dispatchEntry->eventEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003819 }
3820 delete dispatchEntry;
3821}
3822
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003823int InputDispatcher::handleReceiveCallback(int events, sp<IBinder> connectionToken) {
3824 std::scoped_lock _l(mLock);
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003825 std::shared_ptr<Connection> connection = getConnectionLocked(connectionToken);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003826 if (connection == nullptr) {
3827 ALOGW("Received looper callback for unknown input channel token %p. events=0x%x",
3828 connectionToken.get(), events);
3829 return 0; // remove the callback
3830 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003831
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003832 bool notify;
3833 if (!(events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP))) {
3834 if (!(events & ALOOPER_EVENT_INPUT)) {
3835 ALOGW("channel '%s' ~ Received spurious callback for unhandled poll event. "
3836 "events=0x%x",
3837 connection->getInputChannelName().c_str(), events);
3838 return 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003839 }
3840
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003841 nsecs_t currentTime = now();
3842 bool gotOne = false;
3843 status_t status = OK;
3844 for (;;) {
3845 Result<InputPublisher::ConsumerResponse> result =
3846 connection->inputPublisher.receiveConsumerResponse();
3847 if (!result.ok()) {
3848 status = result.error().code();
3849 break;
3850 }
3851
3852 if (std::holds_alternative<InputPublisher::Finished>(*result)) {
3853 const InputPublisher::Finished& finish =
3854 std::get<InputPublisher::Finished>(*result);
3855 finishDispatchCycleLocked(currentTime, connection, finish.seq, finish.handled,
3856 finish.consumeTime);
3857 } else if (std::holds_alternative<InputPublisher::Timeline>(*result)) {
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00003858 if (shouldReportMetricsForConnection(*connection)) {
3859 const InputPublisher::Timeline& timeline =
3860 std::get<InputPublisher::Timeline>(*result);
3861 mLatencyTracker
3862 .trackGraphicsLatency(timeline.inputEventId,
3863 connection->inputChannel->getConnectionToken(),
3864 std::move(timeline.graphicsTimeline));
3865 }
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003866 }
3867 gotOne = true;
3868 }
3869 if (gotOne) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00003870 runCommandsLockedInterruptable();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003871 if (status == WOULD_BLOCK) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003872 return 1;
3873 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003874 }
3875
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003876 notify = status != DEAD_OBJECT || !connection->monitor;
3877 if (notify) {
3878 ALOGE("channel '%s' ~ Failed to receive finished signal. status=%s(%d)",
3879 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3880 status);
3881 }
3882 } else {
3883 // Monitor channels are never explicitly unregistered.
3884 // We do it automatically when the remote endpoint is closed so don't warn about them.
3885 const bool stillHaveWindowHandle =
3886 getWindowHandleLocked(connection->inputChannel->getConnectionToken()) != nullptr;
3887 notify = !connection->monitor && stillHaveWindowHandle;
3888 if (notify) {
3889 ALOGW("channel '%s' ~ Consumer closed input channel or an error occurred. events=0x%x",
3890 connection->getInputChannelName().c_str(), events);
3891 }
3892 }
3893
3894 // Remove the channel.
3895 removeInputChannelLocked(connection->inputChannel->getConnectionToken(), notify);
3896 return 0; // remove the callback
Michael Wrightd02c5b62014-02-10 15:10:22 -08003897}
3898
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003899void InputDispatcher::synthesizeCancelationEventsForAllConnectionsLocked(
Michael Wrightd02c5b62014-02-10 15:10:22 -08003900 const CancelationOptions& options) {
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003901 for (const auto& [token, connection] : mConnectionsByToken) {
Siarhei Vishniakou2e2ea992020-12-15 02:57:19 +00003902 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003903 }
3904}
3905
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003906void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
Michael Wrightfa13dcf2015-06-12 13:25:11 +01003907 const CancelationOptions& options) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08003908 for (const auto& [_, monitors] : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003909 for (const Monitor& monitor : monitors) {
3910 synthesizeCancelationEventsForInputChannelLocked(monitor.inputChannel, options);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003911 }
Michael Wrightfa13dcf2015-06-12 13:25:11 +01003912 }
3913}
3914
Michael Wrightd02c5b62014-02-10 15:10:22 -08003915void InputDispatcher::synthesizeCancelationEventsForInputChannelLocked(
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05003916 const std::shared_ptr<InputChannel>& channel, const CancelationOptions& options) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003917 std::shared_ptr<Connection> connection = getConnectionLocked(channel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003918 if (connection == nullptr) {
3919 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003920 }
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003921
3922 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003923}
3924
3925void InputDispatcher::synthesizeCancelationEventsForConnectionLocked(
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003926 const std::shared_ptr<Connection>& connection, const CancelationOptions& options) {
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003927 if (connection->status == Connection::Status::BROKEN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003928 return;
3929 }
3930
3931 nsecs_t currentTime = now();
3932
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003933 std::vector<std::unique_ptr<EventEntry>> cancelationEvents =
Siarhei Vishniakou00fca7c2019-10-29 13:05:57 -07003934 connection->inputState.synthesizeCancelationEvents(currentTime, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003935
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003936 if (cancelationEvents.empty()) {
3937 return;
3938 }
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003939 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
3940 ALOGD("channel '%s' ~ Synthesized %zu cancelation events to bring channel back in sync "
Siarhei Vishniakou2e3e4432023-02-09 18:34:11 -08003941 "with reality: %s, mode=%s.",
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003942 connection->getInputChannelName().c_str(), cancelationEvents.size(), options.reason,
Siarhei Vishniakou2e3e4432023-02-09 18:34:11 -08003943 ftl::enum_string(options.mode).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003944 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08003945
Arthur Hungb3307ee2021-10-14 10:57:37 +00003946 std::string reason = std::string("reason=").append(options.reason);
3947 android_log_event_list(LOGTAG_INPUT_CANCEL)
3948 << connection->getInputChannelName().c_str() << reason << LOG_ID_EVENTS;
3949
Svet Ganov5d3bc372020-01-26 23:11:07 -08003950 InputTarget target;
chaviw98318de2021-05-19 16:45:23 -05003951 sp<WindowInfoHandle> windowHandle =
Svet Ganov5d3bc372020-01-26 23:11:07 -08003952 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
3953 if (windowHandle != nullptr) {
chaviw98318de2021-05-19 16:45:23 -05003954 const WindowInfo* windowInfo = windowHandle->getInfo();
chaviw1ff3d1e2020-07-01 15:53:47 -07003955 target.setDefaultPointerTransform(windowInfo->transform);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003956 target.globalScaleFactor = windowInfo->globalScaleFactor;
3957 }
3958 target.inputChannel = connection->inputChannel;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003959 target.flags = InputTarget::Flags::DISPATCH_AS_IS;
Svet Ganov5d3bc372020-01-26 23:11:07 -08003960
hongzuo liu95785e22022-09-06 02:51:35 +00003961 const bool wasEmpty = connection->outboundQueue.empty();
3962
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003963 for (size_t i = 0; i < cancelationEvents.size(); i++) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003964 std::unique_ptr<EventEntry> cancelationEventEntry = std::move(cancelationEvents[i]);
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003965 switch (cancelationEventEntry->type) {
3966 case EventEntry::Type::KEY: {
3967 logOutboundKeyDetails("cancel - ",
3968 static_cast<const KeyEntry&>(*cancelationEventEntry));
3969 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003970 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003971 case EventEntry::Type::MOTION: {
3972 logOutboundMotionDetails("cancel - ",
3973 static_cast<const MotionEntry&>(*cancelationEventEntry));
3974 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003975 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003976 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003977 case EventEntry::Type::TOUCH_MODE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08003978 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
3979 case EventEntry::Type::DRAG: {
Prabir Pradhan99987712020-11-10 18:43:05 -08003980 LOG_ALWAYS_FATAL("Canceling %s events is not supported",
Dominik Laskowski75788452021-02-09 18:51:25 -08003981 ftl::enum_string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003982 break;
3983 }
3984 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07003985 case EventEntry::Type::DEVICE_RESET:
3986 case EventEntry::Type::SENSOR: {
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003987 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Dominik Laskowski75788452021-02-09 18:51:25 -08003988 ftl::enum_string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003989 break;
3990 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003991 }
3992
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003993 enqueueDispatchEntryLocked(connection, std::move(cancelationEventEntry), target,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003994 InputTarget::Flags::DISPATCH_AS_IS);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003995 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003996
hongzuo liu95785e22022-09-06 02:51:35 +00003997 // If the outbound queue was previously empty, start the dispatch cycle going.
3998 if (wasEmpty && !connection->outboundQueue.empty()) {
3999 startDispatchCycleLocked(currentTime, connection);
4000 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004001}
4002
Svet Ganov5d3bc372020-01-26 23:11:07 -08004003void InputDispatcher::synthesizePointerDownEventsForConnectionLocked(
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07004004 const nsecs_t downTime, const std::shared_ptr<Connection>& connection,
Arthur Hungc539dbb2022-12-08 07:45:36 +00004005 ftl::Flags<InputTarget::Flags> targetFlags) {
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08004006 if (connection->status == Connection::Status::BROKEN) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08004007 return;
4008 }
4009
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004010 std::vector<std::unique_ptr<EventEntry>> downEvents =
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00004011 connection->inputState.synthesizePointerDownEvents(downTime);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004012
4013 if (downEvents.empty()) {
4014 return;
4015 }
4016
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004017 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08004018 ALOGD("channel '%s' ~ Synthesized %zu down events to ensure consistent event stream.",
4019 connection->getInputChannelName().c_str(), downEvents.size());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004020 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08004021
4022 InputTarget target;
chaviw98318de2021-05-19 16:45:23 -05004023 sp<WindowInfoHandle> windowHandle =
Svet Ganov5d3bc372020-01-26 23:11:07 -08004024 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
4025 if (windowHandle != nullptr) {
chaviw98318de2021-05-19 16:45:23 -05004026 const WindowInfo* windowInfo = windowHandle->getInfo();
chaviw1ff3d1e2020-07-01 15:53:47 -07004027 target.setDefaultPointerTransform(windowInfo->transform);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004028 target.globalScaleFactor = windowInfo->globalScaleFactor;
4029 }
4030 target.inputChannel = connection->inputChannel;
Arthur Hungc539dbb2022-12-08 07:45:36 +00004031 target.flags = targetFlags;
Svet Ganov5d3bc372020-01-26 23:11:07 -08004032
hongzuo liu95785e22022-09-06 02:51:35 +00004033 const bool wasEmpty = connection->outboundQueue.empty();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004034 for (std::unique_ptr<EventEntry>& downEventEntry : downEvents) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08004035 switch (downEventEntry->type) {
4036 case EventEntry::Type::MOTION: {
4037 logOutboundMotionDetails("down - ",
4038 static_cast<const MotionEntry&>(*downEventEntry));
4039 break;
4040 }
4041
4042 case EventEntry::Type::KEY:
4043 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07004044 case EventEntry::Type::TOUCH_MODE_CHANGED:
Svet Ganov5d3bc372020-01-26 23:11:07 -08004045 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08004046 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07004047 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08004048 case EventEntry::Type::SENSOR:
4049 case EventEntry::Type::DRAG: {
Svet Ganov5d3bc372020-01-26 23:11:07 -08004050 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Dominik Laskowski75788452021-02-09 18:51:25 -08004051 ftl::enum_string(downEventEntry->type).c_str());
Svet Ganov5d3bc372020-01-26 23:11:07 -08004052 break;
4053 }
4054 }
4055
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004056 enqueueDispatchEntryLocked(connection, std::move(downEventEntry), target,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08004057 InputTarget::Flags::DISPATCH_AS_IS);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004058 }
4059
hongzuo liu95785e22022-09-06 02:51:35 +00004060 // If the outbound queue was previously empty, start the dispatch cycle going.
4061 if (wasEmpty && !connection->outboundQueue.empty()) {
4062 startDispatchCycleLocked(downTime, connection);
4063 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08004064}
4065
Arthur Hungc539dbb2022-12-08 07:45:36 +00004066void InputDispatcher::synthesizeCancelationEventsForWindowLocked(
4067 const sp<WindowInfoHandle>& windowHandle, const CancelationOptions& options) {
4068 if (windowHandle != nullptr) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07004069 std::shared_ptr<Connection> wallpaperConnection =
4070 getConnectionLocked(windowHandle->getToken());
Arthur Hungc539dbb2022-12-08 07:45:36 +00004071 if (wallpaperConnection != nullptr) {
4072 synthesizeCancelationEventsForConnectionLocked(wallpaperConnection, options);
4073 }
4074 }
4075}
4076
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004077std::unique_ptr<MotionEntry> InputDispatcher::splitMotionEvent(
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08004078 const MotionEntry& originalMotionEntry, std::bitset<MAX_POINTER_ID + 1> pointerIds,
4079 nsecs_t splitDownTime) {
4080 ALOG_ASSERT(pointerIds.any());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004081
4082 uint32_t splitPointerIndexMap[MAX_POINTERS];
4083 PointerProperties splitPointerProperties[MAX_POINTERS];
4084 PointerCoords splitPointerCoords[MAX_POINTERS];
4085
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07004086 uint32_t originalPointerCount = originalMotionEntry.pointerCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004087 uint32_t splitPointerCount = 0;
4088
4089 for (uint32_t originalPointerIndex = 0; originalPointerIndex < originalPointerCount;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004090 originalPointerIndex++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004091 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07004092 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08004093 uint32_t pointerId = uint32_t(pointerProperties.id);
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08004094 if (pointerIds.test(pointerId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004095 splitPointerIndexMap[splitPointerCount] = originalPointerIndex;
4096 splitPointerProperties[splitPointerCount].copyFrom(pointerProperties);
4097 splitPointerCoords[splitPointerCount].copyFrom(
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07004098 originalMotionEntry.pointerCoords[originalPointerIndex]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004099 splitPointerCount += 1;
4100 }
4101 }
4102
4103 if (splitPointerCount != pointerIds.count()) {
4104 // This is bad. We are missing some of the pointers that we expected to deliver.
4105 // Most likely this indicates that we received an ACTION_MOVE events that has
4106 // different pointer ids than we expected based on the previous ACTION_DOWN
4107 // or ACTION_POINTER_DOWN events that caused us to decide to split the pointers
4108 // in this way.
4109 ALOGW("Dropping split motion event because the pointer count is %d but "
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08004110 "we expected there to be %zu pointers. This probably means we received "
Siarhei Vishniakou16e4fa02023-02-16 17:48:56 -08004111 "a broken sequence of pointer ids from the input device: %s",
4112 splitPointerCount, pointerIds.count(), originalMotionEntry.getDescription().c_str());
Yi Kong9b14ac62018-07-17 13:48:38 -07004113 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004114 }
4115
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07004116 int32_t action = originalMotionEntry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004117 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004118 if (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN ||
4119 maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004120 int32_t originalPointerIndex = getMotionEventActionPointerIndex(action);
4121 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07004122 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08004123 uint32_t pointerId = uint32_t(pointerProperties.id);
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08004124 if (pointerIds.test(pointerId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004125 if (pointerIds.count() == 1) {
4126 // The first/last pointer went down/up.
4127 action = maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004128 ? AMOTION_EVENT_ACTION_DOWN
arthurhungea3f4fc2020-12-21 23:18:53 +08004129 : (originalMotionEntry.flags & AMOTION_EVENT_FLAG_CANCELED) != 0
4130 ? AMOTION_EVENT_ACTION_CANCEL
4131 : AMOTION_EVENT_ACTION_UP;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004132 } else {
4133 // A secondary pointer went down/up.
4134 uint32_t splitPointerIndex = 0;
4135 while (pointerId != uint32_t(splitPointerProperties[splitPointerIndex].id)) {
4136 splitPointerIndex += 1;
4137 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004138 action = maskedAction |
4139 (splitPointerIndex << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004140 }
4141 } else {
4142 // An unrelated pointer changed.
4143 action = AMOTION_EVENT_ACTION_MOVE;
4144 }
4145 }
4146
Siarhei Vishniakou59e302b2023-06-05 08:04:53 -07004147 if (action == AMOTION_EVENT_ACTION_DOWN && splitDownTime != originalMotionEntry.eventTime) {
4148 logDispatchStateLocked();
4149 LOG_ALWAYS_FATAL("Split motion event has mismatching downTime and eventTime for "
4150 "ACTION_DOWN, motionEntry=%s, splitDownTime=%" PRId64,
4151 originalMotionEntry.getDescription().c_str(), splitDownTime);
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00004152 }
4153
Garfield Tanff1f1bb2020-01-28 13:24:04 -08004154 int32_t newId = mIdGenerator.nextId();
4155 if (ATRACE_ENABLED()) {
4156 std::string message = StringPrintf("Split MotionEvent(id=0x%" PRIx32
4157 ") to MotionEvent(id=0x%" PRIx32 ").",
4158 originalMotionEntry.id, newId);
4159 ATRACE_NAME(message.c_str());
4160 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004161 std::unique_ptr<MotionEntry> splitMotionEntry =
4162 std::make_unique<MotionEntry>(newId, originalMotionEntry.eventTime,
4163 originalMotionEntry.deviceId, originalMotionEntry.source,
4164 originalMotionEntry.displayId,
4165 originalMotionEntry.policyFlags, action,
4166 originalMotionEntry.actionButton,
4167 originalMotionEntry.flags, originalMotionEntry.metaState,
4168 originalMotionEntry.buttonState,
4169 originalMotionEntry.classification,
4170 originalMotionEntry.edgeFlags,
4171 originalMotionEntry.xPrecision,
4172 originalMotionEntry.yPrecision,
4173 originalMotionEntry.xCursorPosition,
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00004174 originalMotionEntry.yCursorPosition, splitDownTime,
4175 splitPointerCount, splitPointerProperties,
4176 splitPointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004177
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07004178 if (originalMotionEntry.injectionState) {
4179 splitMotionEntry->injectionState = originalMotionEntry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004180 splitMotionEntry->injectionState->refCount += 1;
4181 }
4182
4183 return splitMotionEntry;
4184}
4185
Prabir Pradhan678438e2023-04-13 19:32:51 +00004186void InputDispatcher::notifyConfigurationChanged(const NotifyConfigurationChangedArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004187 if (debugInboundEventDetails()) {
Prabir Pradhan678438e2023-04-13 19:32:51 +00004188 ALOGD("notifyConfigurationChanged - eventTime=%" PRId64, args.eventTime);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004189 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004190
Antonio Kantekf16f2832021-09-28 04:39:20 +00004191 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004192 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004193 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004194
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004195 std::unique_ptr<ConfigurationChangedEntry> newEntry =
Prabir Pradhan678438e2023-04-13 19:32:51 +00004196 std::make_unique<ConfigurationChangedEntry>(args.id, args.eventTime);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004197 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004198 } // release lock
4199
4200 if (needWake) {
4201 mLooper->wake();
4202 }
4203}
4204
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05004205/**
4206 * If one of the meta shortcuts is detected, process them here:
Vaibhav Devmurari34cd5b02023-02-23 14:51:18 +00004207 * Meta + Backspace; Meta + Grave; Meta + Left arrow -> generate BACK
4208 * Most System shortcuts are handled in PhoneWindowManager.java except 'Back' shortcuts. Unlike
4209 * Back, other shortcuts DO NOT need to be sent to applications and are fully handled by the system.
4210 * But for Back key and Back shortcuts, we need to send KEYCODE_BACK to applications which can
4211 * potentially handle the back key presses.
4212 * Note: We don't send any Meta based KeyEvents to applications, so we need to convert to a KeyEvent
4213 * where meta modifier is off before sending. Currently only use case is 'Back'.
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05004214 */
4215void InputDispatcher::accelerateMetaShortcuts(const int32_t deviceId, const int32_t action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004216 int32_t& keyCode, int32_t& metaState) {
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05004217 if (metaState & AMETA_META_ON && action == AKEY_EVENT_ACTION_DOWN) {
4218 int32_t newKeyCode = AKEYCODE_UNKNOWN;
Vaibhav Devmurari34cd5b02023-02-23 14:51:18 +00004219 if (keyCode == AKEYCODE_DEL || keyCode == AKEYCODE_GRAVE || keyCode == AKEYCODE_DPAD_LEFT) {
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05004220 newKeyCode = AKEYCODE_BACK;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05004221 }
4222 if (newKeyCode != AKEYCODE_UNKNOWN) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004223 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05004224 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004225 mReplacedKeys[replacement] = newKeyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05004226 keyCode = newKeyCode;
4227 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
4228 }
4229 } else if (action == AKEY_EVENT_ACTION_UP) {
4230 // In order to maintain a consistent stream of up and down events, check to see if the key
4231 // going up is one we've replaced in a down event and haven't yet replaced in an up event,
4232 // even if the modifier was released between the down and the up events.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004233 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05004234 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004235 auto replacementIt = mReplacedKeys.find(replacement);
4236 if (replacementIt != mReplacedKeys.end()) {
4237 keyCode = replacementIt->second;
4238 mReplacedKeys.erase(replacementIt);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05004239 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
4240 }
4241 }
4242}
4243
Prabir Pradhan678438e2023-04-13 19:32:51 +00004244void InputDispatcher::notifyKey(const NotifyKeyArgs& args) {
Prabir Pradhan96282b02023-02-24 22:36:17 +00004245 ALOGD_IF(debugInboundEventDetails(),
4246 "notifyKey - id=%" PRIx32 ", eventTime=%" PRId64
4247 ", deviceId=%d, source=%s, displayId=%" PRId32
4248 "policyFlags=0x%x, action=%s, flags=0x%x, keyCode=%s, scanCode=0x%x, metaState=0x%x, "
4249 "downTime=%" PRId64,
Prabir Pradhan678438e2023-04-13 19:32:51 +00004250 args.id, args.eventTime, args.deviceId, inputEventSourceToString(args.source).c_str(),
4251 args.displayId, args.policyFlags, KeyEvent::actionToString(args.action), args.flags,
4252 KeyEvent::getLabel(args.keyCode), args.scanCode, args.metaState, args.downTime);
Siarhei Vishniakou6773db62023-04-21 11:30:20 -07004253 Result<void> keyCheck = validateKeyEvent(args.action);
4254 if (!keyCheck.ok()) {
4255 LOG(ERROR) << "invalid key event: " << keyCheck.error();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004256 return;
4257 }
4258
Prabir Pradhan678438e2023-04-13 19:32:51 +00004259 uint32_t policyFlags = args.policyFlags;
4260 int32_t flags = args.flags;
4261 int32_t metaState = args.metaState;
Siarhei Vishniakou622bd322018-10-29 18:02:27 -07004262 // InputDispatcher tracks and generates key repeats on behalf of
4263 // whatever notifies it, so repeatCount should always be set to 0
4264 constexpr int32_t repeatCount = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004265 if ((policyFlags & POLICY_FLAG_VIRTUAL) || (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY)) {
4266 policyFlags |= POLICY_FLAG_VIRTUAL;
4267 flags |= AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
4268 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004269 if (policyFlags & POLICY_FLAG_FUNCTION) {
4270 metaState |= AMETA_FUNCTION_ON;
4271 }
4272
4273 policyFlags |= POLICY_FLAG_TRUSTED;
4274
Prabir Pradhan678438e2023-04-13 19:32:51 +00004275 int32_t keyCode = args.keyCode;
4276 accelerateMetaShortcuts(args.deviceId, args.action, keyCode, metaState);
Michael Wright78f24442014-08-06 15:55:28 -07004277
Michael Wrightd02c5b62014-02-10 15:10:22 -08004278 KeyEvent event;
Prabir Pradhan678438e2023-04-13 19:32:51 +00004279 event.initialize(args.id, args.deviceId, args.source, args.displayId, INVALID_HMAC, args.action,
4280 flags, keyCode, args.scanCode, metaState, repeatCount, args.downTime,
4281 args.eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004282
Michael Wright2b3c3302018-03-02 17:19:13 +00004283 android::base::Timer t;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004284 mPolicy.interceptKeyBeforeQueueing(event, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00004285 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4286 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004287 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00004288 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004289
Antonio Kantekf16f2832021-09-28 04:39:20 +00004290 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004291 { // acquire lock
4292 mLock.lock();
4293
4294 if (shouldSendKeyToInputFilterLocked(args)) {
4295 mLock.unlock();
4296
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004297 policyFlags |= POLICY_FLAG_FILTERED;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004298 if (!mPolicy.filterInputEvent(event, policyFlags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004299 return; // event was consumed by the filter
4300 }
4301
4302 mLock.lock();
4303 }
4304
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004305 std::unique_ptr<KeyEntry> newEntry =
Prabir Pradhan678438e2023-04-13 19:32:51 +00004306 std::make_unique<KeyEntry>(args.id, args.eventTime, args.deviceId, args.source,
4307 args.displayId, policyFlags, args.action, flags, keyCode,
4308 args.scanCode, metaState, repeatCount, args.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004309
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004310 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004311 mLock.unlock();
4312 } // release lock
4313
4314 if (needWake) {
4315 mLooper->wake();
4316 }
4317}
4318
Prabir Pradhan678438e2023-04-13 19:32:51 +00004319bool InputDispatcher::shouldSendKeyToInputFilterLocked(const NotifyKeyArgs& args) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004320 return mInputFilterEnabled;
4321}
4322
Prabir Pradhan678438e2023-04-13 19:32:51 +00004323void InputDispatcher::notifyMotion(const NotifyMotionArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004324 if (debugInboundEventDetails()) {
Prabir Pradhan96282b02023-02-24 22:36:17 +00004325 ALOGD("notifyMotion - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=%s, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004326 "displayId=%" PRId32 ", policyFlags=0x%x, "
Siarhei Vishniakou6ebd0692022-10-20 15:05:45 -07004327 "action=%s, actionButton=0x%x, flags=0x%x, metaState=0x%x, buttonState=0x%x, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004328 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, xCursorPosition=%f, "
4329 "yCursorPosition=%f, downTime=%" PRId64,
Prabir Pradhan678438e2023-04-13 19:32:51 +00004330 args.id, args.eventTime, args.deviceId, inputEventSourceToString(args.source).c_str(),
4331 args.displayId, args.policyFlags, MotionEvent::actionToString(args.action).c_str(),
4332 args.actionButton, args.flags, args.metaState, args.buttonState, args.edgeFlags,
4333 args.xPrecision, args.yPrecision, args.xCursorPosition, args.yCursorPosition,
4334 args.downTime);
Siarhei Vishniakou3218fc02023-06-15 20:41:02 -07004335 for (uint32_t i = 0; i < args.getPointerCount(); i++) {
Prabir Pradhan96282b02023-02-24 22:36:17 +00004336 ALOGD(" Pointer %d: id=%d, toolType=%s, x=%f, y=%f, pressure=%f, size=%f, "
4337 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, orientation=%f",
Prabir Pradhan678438e2023-04-13 19:32:51 +00004338 i, args.pointerProperties[i].id,
4339 ftl::enum_string(args.pointerProperties[i].toolType).c_str(),
4340 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
4341 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
4342 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
4343 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
4344 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
4345 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
4346 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
4347 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
4348 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004349 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004350 }
Siarhei Vishniakou4ca97272023-03-01 11:31:35 -08004351
Siarhei Vishniakou3218fc02023-06-15 20:41:02 -07004352 Result<void> motionCheck =
4353 validateMotionEvent(args.action, args.actionButton, args.getPointerCount(),
4354 args.pointerProperties.data());
Siarhei Vishniakou6773db62023-04-21 11:30:20 -07004355 if (!motionCheck.ok()) {
4356 LOG(ERROR) << "Invalid event: " << args.dump() << "; reason: " << motionCheck.error();
Siarhei Vishniakou4ca97272023-03-01 11:31:35 -08004357 return;
4358 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004359
Siarhei Vishniakou5c02a712023-05-15 15:45:02 -07004360 if (DEBUG_VERIFY_EVENTS) {
4361 auto [it, _] =
4362 mVerifiersByDisplay.try_emplace(args.displayId,
4363 StringPrintf("display %" PRId32, args.displayId));
4364 Result<void> result =
Siarhei Vishniakou3218fc02023-06-15 20:41:02 -07004365 it->second.processMovement(args.deviceId, args.action, args.getPointerCount(),
4366 args.pointerProperties.data(), args.pointerCoords.data(),
4367 args.flags);
Siarhei Vishniakou5c02a712023-05-15 15:45:02 -07004368 if (!result.ok()) {
4369 LOG(FATAL) << "Bad stream: " << result.error() << " caused by " << args.dump();
4370 }
4371 }
4372
Prabir Pradhan678438e2023-04-13 19:32:51 +00004373 uint32_t policyFlags = args.policyFlags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004374 policyFlags |= POLICY_FLAG_TRUSTED;
Michael Wright2b3c3302018-03-02 17:19:13 +00004375
4376 android::base::Timer t;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004377 mPolicy.interceptMotionBeforeQueueing(args.displayId, args.eventTime, policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00004378 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4379 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004380 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00004381 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004382
Antonio Kantekf16f2832021-09-28 04:39:20 +00004383 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004384 { // acquire lock
4385 mLock.lock();
Siarhei Vishniakou5bf25d92023-02-08 15:43:38 -08004386 if (!(policyFlags & POLICY_FLAG_PASS_TO_USER)) {
4387 // Set the flag anyway if we already have an ongoing gesture. That would allow us to
4388 // complete the processing of the current stroke.
Prabir Pradhan678438e2023-04-13 19:32:51 +00004389 const auto touchStateIt = mTouchStatesByDisplay.find(args.displayId);
Siarhei Vishniakou5bf25d92023-02-08 15:43:38 -08004390 if (touchStateIt != mTouchStatesByDisplay.end()) {
4391 const TouchState& touchState = touchStateIt->second;
Prabir Pradhan678438e2023-04-13 19:32:51 +00004392 if (touchState.deviceId == args.deviceId && touchState.isDown()) {
Siarhei Vishniakou5bf25d92023-02-08 15:43:38 -08004393 policyFlags |= POLICY_FLAG_PASS_TO_USER;
4394 }
4395 }
4396 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004397
4398 if (shouldSendMotionToInputFilterLocked(args)) {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004399 ui::Transform displayTransform;
Prabir Pradhan678438e2023-04-13 19:32:51 +00004400 if (const auto it = mDisplayInfos.find(args.displayId); it != mDisplayInfos.end()) {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004401 displayTransform = it->second.transform;
4402 }
4403
Michael Wrightd02c5b62014-02-10 15:10:22 -08004404 mLock.unlock();
4405
4406 MotionEvent event;
Prabir Pradhan678438e2023-04-13 19:32:51 +00004407 event.initialize(args.id, args.deviceId, args.source, args.displayId, INVALID_HMAC,
4408 args.action, args.actionButton, args.flags, args.edgeFlags,
4409 args.metaState, args.buttonState, args.classification,
4410 displayTransform, args.xPrecision, args.yPrecision,
4411 args.xCursorPosition, args.yCursorPosition, displayTransform,
Siarhei Vishniakou3218fc02023-06-15 20:41:02 -07004412 args.downTime, args.eventTime, args.getPointerCount(),
4413 args.pointerProperties.data(), args.pointerCoords.data());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004414
4415 policyFlags |= POLICY_FLAG_FILTERED;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004416 if (!mPolicy.filterInputEvent(event, policyFlags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004417 return; // event was consumed by the filter
4418 }
4419
4420 mLock.lock();
4421 }
4422
4423 // Just enqueue a new motion event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004424 std::unique_ptr<MotionEntry> newEntry =
Prabir Pradhan678438e2023-04-13 19:32:51 +00004425 std::make_unique<MotionEntry>(args.id, args.eventTime, args.deviceId, args.source,
4426 args.displayId, policyFlags, args.action,
4427 args.actionButton, args.flags, args.metaState,
4428 args.buttonState, args.classification, args.edgeFlags,
4429 args.xPrecision, args.yPrecision,
4430 args.xCursorPosition, args.yCursorPosition,
Siarhei Vishniakou3218fc02023-06-15 20:41:02 -07004431 args.downTime, args.getPointerCount(),
4432 args.pointerProperties.data(),
4433 args.pointerCoords.data());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004434
Prabir Pradhan678438e2023-04-13 19:32:51 +00004435 if (args.id != android::os::IInputConstants::INVALID_INPUT_EVENT_ID &&
4436 IdGenerator::getSource(args.id) == IdGenerator::Source::INPUT_READER &&
Siarhei Vishniakou363e7292021-07-09 03:22:42 +00004437 !mInputFilterEnabled) {
Prabir Pradhan678438e2023-04-13 19:32:51 +00004438 const bool isDown = args.action == AMOTION_EVENT_ACTION_DOWN;
4439 mLatencyTracker.trackListener(args.id, isDown, args.eventTime, args.readTime);
Siarhei Vishniakou363e7292021-07-09 03:22:42 +00004440 }
4441
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004442 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004443 mLock.unlock();
4444 } // release lock
4445
4446 if (needWake) {
4447 mLooper->wake();
4448 }
4449}
4450
Prabir Pradhan678438e2023-04-13 19:32:51 +00004451void InputDispatcher::notifySensor(const NotifySensorArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004452 if (debugInboundEventDetails()) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004453 ALOGD("notifySensor - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=0x%x, "
4454 " sensorType=%s",
Prabir Pradhan678438e2023-04-13 19:32:51 +00004455 args.id, args.eventTime, args.deviceId, args.source,
4456 ftl::enum_string(args.sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004457 }
Chris Yef59a2f42020-10-16 12:55:26 -07004458
Antonio Kantekf16f2832021-09-28 04:39:20 +00004459 bool needWake = false;
Chris Yef59a2f42020-10-16 12:55:26 -07004460 { // acquire lock
4461 mLock.lock();
4462
4463 // Just enqueue a new sensor event.
4464 std::unique_ptr<SensorEntry> newEntry =
Prabir Pradhan678438e2023-04-13 19:32:51 +00004465 std::make_unique<SensorEntry>(args.id, args.eventTime, args.deviceId, args.source,
4466 /* policyFlags=*/0, args.hwTimestamp, args.sensorType,
4467 args.accuracy, args.accuracyChanged, args.values);
Chris Yef59a2f42020-10-16 12:55:26 -07004468
4469 needWake = enqueueInboundEventLocked(std::move(newEntry));
4470 mLock.unlock();
4471 } // release lock
4472
4473 if (needWake) {
4474 mLooper->wake();
4475 }
4476}
4477
Prabir Pradhan678438e2023-04-13 19:32:51 +00004478void InputDispatcher::notifyVibratorState(const NotifyVibratorStateArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004479 if (debugInboundEventDetails()) {
Prabir Pradhan678438e2023-04-13 19:32:51 +00004480 ALOGD("notifyVibratorState - eventTime=%" PRId64 ", device=%d, isOn=%d", args.eventTime,
4481 args.deviceId, args.isOn);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004482 }
Prabir Pradhana41d2442023-04-20 21:30:40 +00004483 mPolicy.notifyVibratorState(args.deviceId, args.isOn);
Chris Yefb552902021-02-03 17:18:37 -08004484}
4485
Prabir Pradhan678438e2023-04-13 19:32:51 +00004486bool InputDispatcher::shouldSendMotionToInputFilterLocked(const NotifyMotionArgs& args) {
Jackal Guof9696682018-10-05 12:23:23 +08004487 return mInputFilterEnabled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004488}
4489
Prabir Pradhan678438e2023-04-13 19:32:51 +00004490void InputDispatcher::notifySwitch(const NotifySwitchArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004491 if (debugInboundEventDetails()) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004492 ALOGD("notifySwitch - eventTime=%" PRId64 ", policyFlags=0x%x, switchValues=0x%08x, "
4493 "switchMask=0x%08x",
Prabir Pradhan678438e2023-04-13 19:32:51 +00004494 args.eventTime, args.policyFlags, args.switchValues, args.switchMask);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004495 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004496
Prabir Pradhan678438e2023-04-13 19:32:51 +00004497 uint32_t policyFlags = args.policyFlags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004498 policyFlags |= POLICY_FLAG_TRUSTED;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004499 mPolicy.notifySwitch(args.eventTime, args.switchValues, args.switchMask, policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004500}
4501
Prabir Pradhan678438e2023-04-13 19:32:51 +00004502void InputDispatcher::notifyDeviceReset(const NotifyDeviceResetArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004503 if (debugInboundEventDetails()) {
Prabir Pradhan678438e2023-04-13 19:32:51 +00004504 ALOGD("notifyDeviceReset - eventTime=%" PRId64 ", deviceId=%d", args.eventTime,
4505 args.deviceId);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004506 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004507
Antonio Kantekf16f2832021-09-28 04:39:20 +00004508 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004509 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004510 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004511
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004512 std::unique_ptr<DeviceResetEntry> newEntry =
Prabir Pradhan678438e2023-04-13 19:32:51 +00004513 std::make_unique<DeviceResetEntry>(args.id, args.eventTime, args.deviceId);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004514 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004515 } // release lock
4516
4517 if (needWake) {
4518 mLooper->wake();
4519 }
4520}
4521
Prabir Pradhan678438e2023-04-13 19:32:51 +00004522void InputDispatcher::notifyPointerCaptureChanged(const NotifyPointerCaptureChangedArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004523 if (debugInboundEventDetails()) {
Prabir Pradhan678438e2023-04-13 19:32:51 +00004524 ALOGD("notifyPointerCaptureChanged - eventTime=%" PRId64 ", enabled=%s", args.eventTime,
4525 args.request.enable ? "true" : "false");
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004526 }
Prabir Pradhan7e186182020-11-10 13:56:45 -08004527
Antonio Kantekf16f2832021-09-28 04:39:20 +00004528 bool needWake = false;
Prabir Pradhan99987712020-11-10 18:43:05 -08004529 { // acquire lock
4530 std::scoped_lock _l(mLock);
Prabir Pradhan678438e2023-04-13 19:32:51 +00004531 auto entry =
4532 std::make_unique<PointerCaptureChangedEntry>(args.id, args.eventTime, args.request);
Prabir Pradhan99987712020-11-10 18:43:05 -08004533 needWake = enqueueInboundEventLocked(std::move(entry));
4534 } // release lock
4535
4536 if (needWake) {
4537 mLooper->wake();
4538 }
Prabir Pradhan7e186182020-11-10 13:56:45 -08004539}
4540
Prabir Pradhan5735a322022-04-11 17:23:34 +00004541InputEventInjectionResult InputDispatcher::injectInputEvent(const InputEvent* event,
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00004542 std::optional<gui::Uid> targetUid,
Prabir Pradhan5735a322022-04-11 17:23:34 +00004543 InputEventInjectionSync syncMode,
4544 std::chrono::milliseconds timeout,
4545 uint32_t policyFlags) {
Siarhei Vishniakou6773db62023-04-21 11:30:20 -07004546 Result<void> eventValidation = validateInputEvent(*event);
4547 if (!eventValidation.ok()) {
4548 LOG(INFO) << "Injection failed: invalid event: " << eventValidation.error();
4549 return InputEventInjectionResult::FAILED;
4550 }
4551
Prabir Pradhan65613802023-02-22 23:36:58 +00004552 if (debugInboundEventDetails()) {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00004553 LOG(DEBUG) << __func__ << ": targetUid=" << toString(targetUid, &uidString)
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004554 << ", syncMode=" << ftl::enum_string(syncMode) << ", timeout=" << timeout.count()
4555 << "ms, policyFlags=0x" << std::hex << policyFlags << std::dec
4556 << ", event=" << *event;
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004557 }
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07004558 nsecs_t endTime = now() + std::chrono::duration_cast<std::chrono::nanoseconds>(timeout).count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004559
Prabir Pradhan5735a322022-04-11 17:23:34 +00004560 policyFlags |= POLICY_FLAG_INJECTED | POLICY_FLAG_TRUSTED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004561
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004562 // For all injected events, set device id = VIRTUAL_KEYBOARD_ID. The only exception is events
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004563 // that have gone through the InputFilter. If the event passed through the InputFilter, assign
4564 // the provided device id. If the InputFilter is accessibility, and it modifies or synthesizes
4565 // the injected event, it is responsible for setting POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY.
4566 // For those events, we will set FLAG_IS_ACCESSIBILITY_EVENT to allow apps to distinguish them
4567 // from events that originate from actual hardware.
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004568 int32_t resolvedDeviceId = VIRTUAL_KEYBOARD_ID;
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004569 if (policyFlags & POLICY_FLAG_FILTERED) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004570 resolvedDeviceId = event->getDeviceId();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004571 }
4572
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004573 std::queue<std::unique_ptr<EventEntry>> injectedEntries;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004574 switch (event->getType()) {
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004575 case InputEventType::KEY: {
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004576 const KeyEvent& incomingKey = static_cast<const KeyEvent&>(*event);
Siarhei Vishniakou6773db62023-04-21 11:30:20 -07004577 const int32_t action = incomingKey.getAction();
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004578 int32_t flags = incomingKey.getFlags();
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004579 if (policyFlags & POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY) {
4580 flags |= AKEY_EVENT_FLAG_IS_ACCESSIBILITY_EVENT;
4581 }
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004582 int32_t keyCode = incomingKey.getKeyCode();
4583 int32_t metaState = incomingKey.getMetaState();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004584 accelerateMetaShortcuts(resolvedDeviceId, action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004585 /*byref*/ keyCode, /*byref*/ metaState);
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004586 KeyEvent keyEvent;
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004587 keyEvent.initialize(incomingKey.getId(), resolvedDeviceId, incomingKey.getSource(),
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004588 incomingKey.getDisplayId(), INVALID_HMAC, action, flags, keyCode,
4589 incomingKey.getScanCode(), metaState, incomingKey.getRepeatCount(),
4590 incomingKey.getDownTime(), incomingKey.getEventTime());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004591
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004592 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
4593 policyFlags |= POLICY_FLAG_VIRTUAL;
Michael Wright2b3c3302018-03-02 17:19:13 +00004594 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004595
4596 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
4597 android::base::Timer t;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004598 mPolicy.interceptKeyBeforeQueueing(keyEvent, /*byref*/ policyFlags);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004599 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4600 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
4601 std::to_string(t.duration().count()).c_str());
4602 }
4603 }
4604
4605 mLock.lock();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004606 std::unique_ptr<KeyEntry> injectedEntry =
4607 std::make_unique<KeyEntry>(incomingKey.getId(), incomingKey.getEventTime(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004608 resolvedDeviceId, incomingKey.getSource(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004609 incomingKey.getDisplayId(), policyFlags, action,
4610 flags, keyCode, incomingKey.getScanCode(), metaState,
4611 incomingKey.getRepeatCount(),
4612 incomingKey.getDownTime());
4613 injectedEntries.push(std::move(injectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004614 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004615 }
4616
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004617 case InputEventType::MOTION: {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004618 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(*event);
Prabir Pradhanaa561d12021-09-24 06:57:33 -07004619 const bool isPointerEvent =
4620 isFromSource(event->getSource(), AINPUT_SOURCE_CLASS_POINTER);
4621 // If a pointer event has no displayId specified, inject it to the default display.
4622 const uint32_t displayId = isPointerEvent && (event->getDisplayId() == ADISPLAY_ID_NONE)
4623 ? ADISPLAY_ID_DEFAULT
4624 : event->getDisplayId();
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004625 int32_t flags = motionEvent.getFlags();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004626
4627 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004628 nsecs_t eventTime = motionEvent.getEventTime();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004629 android::base::Timer t;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004630 mPolicy.interceptMotionBeforeQueueing(displayId, eventTime, /*byref*/ policyFlags);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004631 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4632 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
4633 std::to_string(t.duration().count()).c_str());
4634 }
4635 }
4636
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004637 if (policyFlags & POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY) {
4638 flags |= AMOTION_EVENT_FLAG_IS_ACCESSIBILITY_EVENT;
4639 }
4640
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004641 mLock.lock();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004642 const nsecs_t* sampleEventTimes = motionEvent.getSampleEventTimes();
4643 const PointerCoords* samplePointerCoords = motionEvent.getSamplePointerCoords();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004644 std::unique_ptr<MotionEntry> injectedEntry =
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004645 std::make_unique<MotionEntry>(motionEvent.getId(), *sampleEventTimes,
4646 resolvedDeviceId, motionEvent.getSource(),
Siarhei Vishniakou6773db62023-04-21 11:30:20 -07004647 displayId, policyFlags, motionEvent.getAction(),
4648 motionEvent.getActionButton(), flags,
4649 motionEvent.getMetaState(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004650 motionEvent.getButtonState(),
4651 motionEvent.getClassification(),
4652 motionEvent.getEdgeFlags(),
4653 motionEvent.getXPrecision(),
4654 motionEvent.getYPrecision(),
4655 motionEvent.getRawXCursorPosition(),
4656 motionEvent.getRawYCursorPosition(),
Siarhei Vishniakou6773db62023-04-21 11:30:20 -07004657 motionEvent.getDownTime(),
4658 motionEvent.getPointerCount(),
4659 motionEvent.getPointerProperties(),
4660 samplePointerCoords);
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004661 transformMotionEntryForInjectionLocked(*injectedEntry, motionEvent.getTransform());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004662 injectedEntries.push(std::move(injectedEntry));
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004663 for (size_t i = motionEvent.getHistorySize(); i > 0; i--) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004664 sampleEventTimes += 1;
Siarhei Vishniakou6773db62023-04-21 11:30:20 -07004665 samplePointerCoords += motionEvent.getPointerCount();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004666 std::unique_ptr<MotionEntry> nextInjectedEntry =
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004667 std::make_unique<MotionEntry>(motionEvent.getId(), *sampleEventTimes,
4668 resolvedDeviceId, motionEvent.getSource(),
Siarhei Vishniakou6773db62023-04-21 11:30:20 -07004669 displayId, policyFlags,
4670 motionEvent.getAction(),
4671 motionEvent.getActionButton(), flags,
4672 motionEvent.getMetaState(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004673 motionEvent.getButtonState(),
4674 motionEvent.getClassification(),
4675 motionEvent.getEdgeFlags(),
4676 motionEvent.getXPrecision(),
4677 motionEvent.getYPrecision(),
4678 motionEvent.getRawXCursorPosition(),
4679 motionEvent.getRawYCursorPosition(),
4680 motionEvent.getDownTime(),
Siarhei Vishniakou6773db62023-04-21 11:30:20 -07004681 motionEvent.getPointerCount(),
4682 motionEvent.getPointerProperties(),
Prabir Pradhan5beda762021-12-10 09:30:08 +00004683 samplePointerCoords);
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004684 transformMotionEntryForInjectionLocked(*nextInjectedEntry,
4685 motionEvent.getTransform());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004686 injectedEntries.push(std::move(nextInjectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004687 }
4688 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004689 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004690
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004691 default:
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004692 LOG(WARNING) << "Cannot inject " << ftl::enum_string(event->getType()) << " events";
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004693 return InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004694 }
4695
Prabir Pradhan5735a322022-04-11 17:23:34 +00004696 InjectionState* injectionState = new InjectionState(targetUid);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004697 if (syncMode == InputEventInjectionSync::NONE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004698 injectionState->injectionIsAsync = true;
4699 }
4700
4701 injectionState->refCount += 1;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004702 injectedEntries.back()->injectionState = injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004703
4704 bool needWake = false;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004705 while (!injectedEntries.empty()) {
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08004706 if (DEBUG_INJECTION) {
4707 LOG(DEBUG) << "Injecting " << injectedEntries.front()->getDescription();
4708 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004709 needWake |= enqueueInboundEventLocked(std::move(injectedEntries.front()));
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004710 injectedEntries.pop();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004711 }
4712
4713 mLock.unlock();
4714
4715 if (needWake) {
4716 mLooper->wake();
4717 }
4718
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004719 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004720 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004721 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004722
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004723 if (syncMode == InputEventInjectionSync::NONE) {
4724 injectionResult = InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004725 } else {
4726 for (;;) {
4727 injectionResult = injectionState->injectionResult;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004728 if (injectionResult != InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004729 break;
4730 }
4731
4732 nsecs_t remainingTimeout = endTime - now();
4733 if (remainingTimeout <= 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004734 if (DEBUG_INJECTION) {
4735 ALOGD("injectInputEvent - Timed out waiting for injection result "
4736 "to become available.");
4737 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004738 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004739 break;
4740 }
4741
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004742 mInjectionResultAvailable.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004743 }
4744
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004745 if (injectionResult == InputEventInjectionResult::SUCCEEDED &&
4746 syncMode == InputEventInjectionSync::WAIT_FOR_FINISHED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004747 while (injectionState->pendingForegroundDispatches != 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004748 if (DEBUG_INJECTION) {
4749 ALOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
4750 injectionState->pendingForegroundDispatches);
4751 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004752 nsecs_t remainingTimeout = endTime - now();
4753 if (remainingTimeout <= 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004754 if (DEBUG_INJECTION) {
4755 ALOGD("injectInputEvent - Timed out waiting for pending foreground "
4756 "dispatches to finish.");
4757 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004758 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004759 break;
4760 }
4761
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004762 mInjectionSyncFinished.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004763 }
4764 }
4765 }
4766
4767 injectionState->release();
4768 } // release lock
4769
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004770 if (DEBUG_INJECTION) {
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08004771 LOG(DEBUG) << "injectInputEvent - Finished with result "
4772 << ftl::enum_string(injectionResult);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004773 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004774
4775 return injectionResult;
4776}
4777
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004778std::unique_ptr<VerifiedInputEvent> InputDispatcher::verifyInputEvent(const InputEvent& event) {
Gang Wange9087892020-01-07 12:17:14 -05004779 std::array<uint8_t, 32> calculatedHmac;
4780 std::unique_ptr<VerifiedInputEvent> result;
4781 switch (event.getType()) {
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004782 case InputEventType::KEY: {
Gang Wange9087892020-01-07 12:17:14 -05004783 const KeyEvent& keyEvent = static_cast<const KeyEvent&>(event);
4784 VerifiedKeyEvent verifiedKeyEvent = verifiedKeyEventFromKeyEvent(keyEvent);
4785 result = std::make_unique<VerifiedKeyEvent>(verifiedKeyEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004786 calculatedHmac = sign(verifiedKeyEvent);
Gang Wange9087892020-01-07 12:17:14 -05004787 break;
4788 }
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004789 case InputEventType::MOTION: {
Gang Wange9087892020-01-07 12:17:14 -05004790 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(event);
4791 VerifiedMotionEvent verifiedMotionEvent =
4792 verifiedMotionEventFromMotionEvent(motionEvent);
4793 result = std::make_unique<VerifiedMotionEvent>(verifiedMotionEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004794 calculatedHmac = sign(verifiedMotionEvent);
Gang Wange9087892020-01-07 12:17:14 -05004795 break;
4796 }
4797 default: {
4798 ALOGE("Cannot verify events of type %" PRId32, event.getType());
4799 return nullptr;
4800 }
4801 }
4802 if (calculatedHmac == INVALID_HMAC) {
4803 return nullptr;
4804 }
tyiu1573a672023-02-21 22:38:32 +00004805 if (0 != CRYPTO_memcmp(calculatedHmac.data(), event.getHmac().data(), calculatedHmac.size())) {
Gang Wange9087892020-01-07 12:17:14 -05004806 return nullptr;
4807 }
4808 return result;
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004809}
4810
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004811void InputDispatcher::setInjectionResult(EventEntry& entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004812 InputEventInjectionResult injectionResult) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004813 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004814 if (injectionState) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004815 if (DEBUG_INJECTION) {
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08004816 LOG(DEBUG) << "Setting input event injection result to "
4817 << ftl::enum_string(injectionResult);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004818 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004819
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004820 if (injectionState->injectionIsAsync && !(entry.policyFlags & POLICY_FLAG_FILTERED)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004821 // Log the outcome since the injector did not wait for the injection result.
4822 switch (injectionResult) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004823 case InputEventInjectionResult::SUCCEEDED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004824 ALOGV("Asynchronous input event injection succeeded.");
4825 break;
Prabir Pradhan5735a322022-04-11 17:23:34 +00004826 case InputEventInjectionResult::TARGET_MISMATCH:
4827 ALOGV("Asynchronous input event injection target mismatch.");
4828 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004829 case InputEventInjectionResult::FAILED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004830 ALOGW("Asynchronous input event injection failed.");
4831 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004832 case InputEventInjectionResult::TIMED_OUT:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004833 ALOGW("Asynchronous input event injection timed out.");
4834 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004835 case InputEventInjectionResult::PENDING:
4836 ALOGE("Setting result to 'PENDING' for asynchronous injection");
4837 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004838 }
4839 }
4840
4841 injectionState->injectionResult = injectionResult;
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004842 mInjectionResultAvailable.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004843 }
4844}
4845
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004846void InputDispatcher::transformMotionEntryForInjectionLocked(
4847 MotionEntry& entry, const ui::Transform& injectedTransform) const {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004848 // Input injection works in the logical display coordinate space, but the input pipeline works
4849 // display space, so we need to transform the injected events accordingly.
4850 const auto it = mDisplayInfos.find(entry.displayId);
4851 if (it == mDisplayInfos.end()) return;
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004852 const auto& transformToDisplay = it->second.transform.inverse() * injectedTransform;
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004853
Prabir Pradhand9a2ebe2022-07-20 19:25:13 +00004854 if (entry.xCursorPosition != AMOTION_EVENT_INVALID_CURSOR_POSITION &&
4855 entry.yCursorPosition != AMOTION_EVENT_INVALID_CURSOR_POSITION) {
4856 const vec2 cursor =
4857 MotionEvent::calculateTransformedXY(entry.source, transformToDisplay,
4858 {entry.xCursorPosition, entry.yCursorPosition});
4859 entry.xCursorPosition = cursor.x;
4860 entry.yCursorPosition = cursor.y;
4861 }
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004862 for (uint32_t i = 0; i < entry.pointerCount; i++) {
Prabir Pradhan8e6ce222022-02-24 09:08:54 -08004863 entry.pointerCoords[i] =
4864 MotionEvent::calculateTransformedCoords(entry.source, transformToDisplay,
4865 entry.pointerCoords[i]);
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004866 }
4867}
4868
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004869void InputDispatcher::incrementPendingForegroundDispatches(EventEntry& entry) {
4870 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004871 if (injectionState) {
4872 injectionState->pendingForegroundDispatches += 1;
4873 }
4874}
4875
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004876void InputDispatcher::decrementPendingForegroundDispatches(EventEntry& entry) {
4877 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004878 if (injectionState) {
4879 injectionState->pendingForegroundDispatches -= 1;
4880
4881 if (injectionState->pendingForegroundDispatches == 0) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004882 mInjectionSyncFinished.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004883 }
4884 }
4885}
4886
chaviw98318de2021-05-19 16:45:23 -05004887const std::vector<sp<WindowInfoHandle>>& InputDispatcher::getWindowHandlesLocked(
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004888 int32_t displayId) const {
chaviw98318de2021-05-19 16:45:23 -05004889 static const std::vector<sp<WindowInfoHandle>> EMPTY_WINDOW_HANDLES;
Vishnu Nairad321cd2020-08-20 16:40:21 -07004890 auto it = mWindowHandlesByDisplay.find(displayId);
4891 return it != mWindowHandlesByDisplay.end() ? it->second : EMPTY_WINDOW_HANDLES;
Arthur Hungb92218b2018-08-14 12:00:21 +08004892}
4893
chaviw98318de2021-05-19 16:45:23 -05004894sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(
chaviwfbe5d9c2018-12-26 12:23:37 -08004895 const sp<IBinder>& windowHandleToken) const {
arthurhungbe737672020-06-24 12:29:21 +08004896 if (windowHandleToken == nullptr) {
4897 return nullptr;
4898 }
4899
Arthur Hungb92218b2018-08-14 12:00:21 +08004900 for (auto& it : mWindowHandlesByDisplay) {
chaviw98318de2021-05-19 16:45:23 -05004901 const std::vector<sp<WindowInfoHandle>>& windowHandles = it.second;
4902 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
chaviwfbe5d9c2018-12-26 12:23:37 -08004903 if (windowHandle->getToken() == windowHandleToken) {
Arthur Hungb92218b2018-08-14 12:00:21 +08004904 return windowHandle;
4905 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004906 }
4907 }
Yi Kong9b14ac62018-07-17 13:48:38 -07004908 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004909}
4910
chaviw98318de2021-05-19 16:45:23 -05004911sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(const sp<IBinder>& windowHandleToken,
4912 int displayId) const {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004913 if (windowHandleToken == nullptr) {
4914 return nullptr;
4915 }
4916
chaviw98318de2021-05-19 16:45:23 -05004917 for (const sp<WindowInfoHandle>& windowHandle : getWindowHandlesLocked(displayId)) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004918 if (windowHandle->getToken() == windowHandleToken) {
4919 return windowHandle;
4920 }
4921 }
4922 return nullptr;
4923}
4924
chaviw98318de2021-05-19 16:45:23 -05004925sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(
4926 const sp<WindowInfoHandle>& windowHandle) const {
Mady Mellor017bcd12020-06-23 19:12:00 +00004927 for (auto& it : mWindowHandlesByDisplay) {
chaviw98318de2021-05-19 16:45:23 -05004928 const std::vector<sp<WindowInfoHandle>>& windowHandles = it.second;
4929 for (const sp<WindowInfoHandle>& handle : windowHandles) {
arthurhungbe737672020-06-24 12:29:21 +08004930 if (handle->getId() == windowHandle->getId() &&
4931 handle->getToken() == windowHandle->getToken()) {
Mady Mellor017bcd12020-06-23 19:12:00 +00004932 if (windowHandle->getInfo()->displayId != it.first) {
4933 ALOGE("Found window %s in display %" PRId32
4934 ", but it should belong to display %" PRId32,
4935 windowHandle->getName().c_str(), it.first,
4936 windowHandle->getInfo()->displayId);
4937 }
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004938 return handle;
Arthur Hungb92218b2018-08-14 12:00:21 +08004939 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004940 }
4941 }
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004942 return nullptr;
4943}
4944
chaviw98318de2021-05-19 16:45:23 -05004945sp<WindowInfoHandle> InputDispatcher::getFocusedWindowHandleLocked(int displayId) const {
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004946 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(displayId);
4947 return getWindowHandleLocked(focusedToken, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004948}
4949
Prabir Pradhan33e3baa2022-12-06 20:30:22 +00004950ui::Transform InputDispatcher::getTransformLocked(int32_t displayId) const {
4951 auto displayInfoIt = mDisplayInfos.find(displayId);
4952 return displayInfoIt != mDisplayInfos.end() ? displayInfoIt->second.transform
4953 : kIdentityTransform;
4954}
4955
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004956bool InputDispatcher::canWindowReceiveMotionLocked(const sp<WindowInfoHandle>& window,
4957 const MotionEntry& motionEntry) const {
4958 const WindowInfo& info = *window->getInfo();
4959
4960 // Skip spy window targets that are not valid for targeted injection.
4961 if (const auto err = verifyTargetedInjection(window, motionEntry); err) {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004962 return false;
4963 }
4964
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004965 if (info.inputConfig.test(WindowInfo::InputConfig::PAUSE_DISPATCHING)) {
4966 ALOGI("Not sending touch event to %s because it is paused", window->getName().c_str());
4967 return false;
4968 }
4969
4970 if (info.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL)) {
4971 ALOGW("Not sending touch gesture to %s because it has config NO_INPUT_CHANNEL",
4972 window->getName().c_str());
4973 return false;
4974 }
4975
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07004976 std::shared_ptr<Connection> connection = getConnectionLocked(window->getToken());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004977 if (connection == nullptr) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004978 ALOGW("Not sending touch to %s because there's no corresponding connection",
4979 window->getName().c_str());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004980 return false;
4981 }
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004982
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004983 if (!connection->responsive) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004984 ALOGW("Not sending touch to %s because it is not responsive", window->getName().c_str());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004985 return false;
4986 }
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004987
4988 // Drop events that can't be trusted due to occlusion
4989 const auto [x, y] = resolveTouchedPosition(motionEntry);
4990 TouchOcclusionInfo occlusionInfo = computeTouchOcclusionInfoLocked(window, x, y);
4991 if (!isTouchTrustedLocked(occlusionInfo)) {
4992 if (DEBUG_TOUCH_OCCLUSION) {
Prabir Pradhan82e081e2022-12-06 09:50:09 +00004993 ALOGD("Stack of obscuring windows during untrusted touch (%.1f, %.1f):", x, y);
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004994 for (const auto& log : occlusionInfo.debugInfo) {
4995 ALOGD("%s", log.c_str());
4996 }
4997 }
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00004998 ALOGW("Dropping untrusted touch event due to %s/%s", occlusionInfo.obscuringPackage.c_str(),
4999 occlusionInfo.obscuringUid.toString().c_str());
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07005000 return false;
5001 }
5002
5003 // Drop touch events if requested by input feature
5004 if (shouldDropInput(motionEntry, window)) {
5005 return false;
5006 }
5007
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005008 return true;
5009}
5010
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005011std::shared_ptr<InputChannel> InputDispatcher::getInputChannelLocked(
5012 const sp<IBinder>& token) const {
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005013 auto connectionIt = mConnectionsByToken.find(token);
5014 if (connectionIt == mConnectionsByToken.end()) {
Robert Carr5c8a0262018-10-03 16:30:44 -07005015 return nullptr;
5016 }
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005017 return connectionIt->second->inputChannel;
Robert Carr5c8a0262018-10-03 16:30:44 -07005018}
5019
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005020void InputDispatcher::updateWindowHandlesForDisplayLocked(
chaviw98318de2021-05-19 16:45:23 -05005021 const std::vector<sp<WindowInfoHandle>>& windowInfoHandles, int32_t displayId) {
5022 if (windowInfoHandles.empty()) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005023 // Remove all handles on a display if there are no windows left.
5024 mWindowHandlesByDisplay.erase(displayId);
5025 return;
5026 }
5027
5028 // Since we compare the pointer of input window handles across window updates, we need
5029 // to make sure the handle object for the same window stays unchanged across updates.
chaviw98318de2021-05-19 16:45:23 -05005030 const std::vector<sp<WindowInfoHandle>>& oldHandles = getWindowHandlesLocked(displayId);
5031 std::unordered_map<int32_t /*id*/, sp<WindowInfoHandle>> oldHandlesById;
5032 for (const sp<WindowInfoHandle>& handle : oldHandles) {
chaviwaf87b3e2019-10-01 16:59:28 -07005033 oldHandlesById[handle->getId()] = handle;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005034 }
5035
chaviw98318de2021-05-19 16:45:23 -05005036 std::vector<sp<WindowInfoHandle>> newHandles;
5037 for (const sp<WindowInfoHandle>& handle : windowInfoHandles) {
chaviw98318de2021-05-19 16:45:23 -05005038 const WindowInfo* info = handle->getInfo();
Siarhei Vishniakou64452932020-11-06 17:51:32 -06005039 if (getInputChannelLocked(handle->getToken()) == nullptr) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005040 const bool noInputChannel =
Prabir Pradhan51e7db02022-02-07 06:02:57 -08005041 info->inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005042 const bool canReceiveInput =
5043 !info->inputConfig.test(WindowInfo::InputConfig::NOT_TOUCHABLE) ||
5044 !info->inputConfig.test(WindowInfo::InputConfig::NOT_FOCUSABLE);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005045 if (canReceiveInput && !noInputChannel) {
John Recke0710582019-09-26 13:46:12 -07005046 ALOGV("Window handle %s has no registered input channel",
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005047 handle->getName().c_str());
Robert Carr2984b7a2020-04-13 17:06:45 -07005048 continue;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005049 }
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005050 }
5051
5052 if (info->displayId != displayId) {
5053 ALOGE("Window %s updated by wrong display %d, should belong to display %d",
5054 handle->getName().c_str(), displayId, info->displayId);
5055 continue;
5056 }
5057
Robert Carredd13602020-04-13 17:24:34 -07005058 if ((oldHandlesById.find(handle->getId()) != oldHandlesById.end()) &&
5059 (oldHandlesById.at(handle->getId())->getToken() == handle->getToken())) {
chaviw98318de2021-05-19 16:45:23 -05005060 const sp<WindowInfoHandle>& oldHandle = oldHandlesById.at(handle->getId());
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005061 oldHandle->updateFrom(handle);
5062 newHandles.push_back(oldHandle);
5063 } else {
5064 newHandles.push_back(handle);
5065 }
5066 }
5067
5068 // Insert or replace
5069 mWindowHandlesByDisplay[displayId] = newHandles;
5070}
5071
Arthur Hung72d8dc32020-03-28 00:48:39 +00005072void InputDispatcher::setInputWindows(
chaviw98318de2021-05-19 16:45:23 -05005073 const std::unordered_map<int32_t, std::vector<sp<WindowInfoHandle>>>& handlesPerDisplay) {
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005074 // TODO(b/198444055): Remove setInputWindows from InputDispatcher.
Arthur Hung72d8dc32020-03-28 00:48:39 +00005075 { // acquire lock
5076 std::scoped_lock _l(mLock);
Siarhei Vishniakou2508b872020-12-03 16:33:53 -10005077 for (const auto& [displayId, handles] : handlesPerDisplay) {
5078 setInputWindowsLocked(handles, displayId);
Arthur Hung72d8dc32020-03-28 00:48:39 +00005079 }
5080 }
5081 // Wake up poll loop since it may need to make new input dispatching choices.
5082 mLooper->wake();
5083}
5084
Arthur Hungb92218b2018-08-14 12:00:21 +08005085/**
5086 * Called from InputManagerService, update window handle list by displayId that can receive input.
5087 * A window handle contains information about InputChannel, Touch Region, Types, Focused,...
5088 * If set an empty list, remove all handles from the specific display.
5089 * For focused handle, check if need to change and send a cancel event to previous one.
5090 * For removed handle, check if need to send a cancel event if already in touch.
5091 */
Arthur Hung72d8dc32020-03-28 00:48:39 +00005092void InputDispatcher::setInputWindowsLocked(
chaviw98318de2021-05-19 16:45:23 -05005093 const std::vector<sp<WindowInfoHandle>>& windowInfoHandles, int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005094 if (DEBUG_FOCUS) {
5095 std::string windowList;
chaviw98318de2021-05-19 16:45:23 -05005096 for (const sp<WindowInfoHandle>& iwh : windowInfoHandles) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005097 windowList += iwh->getName() + " ";
5098 }
5099 ALOGD("setInputWindows displayId=%" PRId32 " %s", displayId, windowList.c_str());
5100 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005101
Prabir Pradhand65552b2021-10-07 11:23:50 -07005102 // Check preconditions for new input windows
chaviw98318de2021-05-19 16:45:23 -05005103 for (const sp<WindowInfoHandle>& window : windowInfoHandles) {
Prabir Pradhand65552b2021-10-07 11:23:50 -07005104 const WindowInfo& info = *window->getInfo();
5105
5106 // Ensure all tokens are null if the window has feature NO_INPUT_CHANNEL
Prabir Pradhan51e7db02022-02-07 06:02:57 -08005107 const bool noInputWindow = info.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005108 if (noInputWindow && window->getToken() != nullptr) {
5109 ALOGE("%s has feature NO_INPUT_WINDOW, but a non-null token. Clearing",
5110 window->getName().c_str());
5111 window->releaseChannel();
5112 }
Prabir Pradhand65552b2021-10-07 11:23:50 -07005113
Prabir Pradhan5c85e052021-12-22 02:27:12 -08005114 // Ensure all spy windows are trusted overlays
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005115 LOG_ALWAYS_FATAL_IF(info.isSpy() &&
5116 !info.inputConfig.test(
5117 WindowInfo::InputConfig::TRUSTED_OVERLAY),
Prabir Pradhan5c85e052021-12-22 02:27:12 -08005118 "%s has feature SPY, but is not a trusted overlay.",
5119 window->getName().c_str());
5120
Prabir Pradhand65552b2021-10-07 11:23:50 -07005121 // Ensure all stylus interceptors are trusted overlays
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005122 LOG_ALWAYS_FATAL_IF(info.interceptsStylus() &&
5123 !info.inputConfig.test(
5124 WindowInfo::InputConfig::TRUSTED_OVERLAY),
Prabir Pradhand65552b2021-10-07 11:23:50 -07005125 "%s has feature INTERCEPTS_STYLUS, but is not a trusted overlay.",
5126 window->getName().c_str());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005127 }
5128
Arthur Hung72d8dc32020-03-28 00:48:39 +00005129 // Copy old handles for release if they are no longer present.
chaviw98318de2021-05-19 16:45:23 -05005130 const std::vector<sp<WindowInfoHandle>> oldWindowHandles = getWindowHandlesLocked(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005131
Prabir Pradhan93a0f912021-04-21 13:47:42 -07005132 // Save the old windows' orientation by ID before it gets updated.
5133 std::unordered_map<int32_t, uint32_t> oldWindowOrientations;
chaviw98318de2021-05-19 16:45:23 -05005134 for (const sp<WindowInfoHandle>& handle : oldWindowHandles) {
Prabir Pradhan93a0f912021-04-21 13:47:42 -07005135 oldWindowOrientations.emplace(handle->getId(),
5136 handle->getInfo()->transform.getOrientation());
5137 }
5138
chaviw98318de2021-05-19 16:45:23 -05005139 updateWindowHandlesForDisplayLocked(windowInfoHandles, displayId);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005140
chaviw98318de2021-05-19 16:45:23 -05005141 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Arthur Hung72d8dc32020-03-28 00:48:39 +00005142
Vishnu Nairc519ff72021-01-21 08:23:08 -08005143 std::optional<FocusResolver::FocusChanges> changes =
5144 mFocusResolver.setInputWindows(displayId, windowHandles);
5145 if (changes) {
5146 onFocusChangedLocked(*changes);
Arthur Hung72d8dc32020-03-28 00:48:39 +00005147 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005148
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005149 std::unordered_map<int32_t, TouchState>::iterator stateIt =
5150 mTouchStatesByDisplay.find(displayId);
5151 if (stateIt != mTouchStatesByDisplay.end()) {
5152 TouchState& state = stateIt->second;
Arthur Hung72d8dc32020-03-28 00:48:39 +00005153 for (size_t i = 0; i < state.windows.size();) {
5154 TouchedWindow& touchedWindow = state.windows[i];
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07005155 if (getWindowHandleLocked(touchedWindow.windowHandle) == nullptr) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005156 if (DEBUG_FOCUS) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00005157 ALOGD("Touched window was removed: %s in display %" PRId32,
5158 touchedWindow.windowHandle->getName().c_str(), displayId);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005159 }
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005160 std::shared_ptr<InputChannel> touchedInputChannel =
Arthur Hung72d8dc32020-03-28 00:48:39 +00005161 getInputChannelLocked(touchedWindow.windowHandle->getToken());
5162 if (touchedInputChannel != nullptr) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00005163 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
Arthur Hung72d8dc32020-03-28 00:48:39 +00005164 "touched window was removed");
5165 synthesizeCancelationEventsForInputChannelLocked(touchedInputChannel, options);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00005166 // Since we are about to drop the touch, cancel the events for the wallpaper as
5167 // well.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005168 if (touchedWindow.targetFlags.test(InputTarget::Flags::FOREGROUND) &&
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005169 touchedWindow.windowHandle->getInfo()->inputConfig.test(
5170 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER)) {
Siarhei Vishniakouca205502021-07-16 21:31:58 +00005171 sp<WindowInfoHandle> wallpaper = state.getWallpaperWindow();
Arthur Hungc539dbb2022-12-08 07:45:36 +00005172 synthesizeCancelationEventsForWindowLocked(wallpaper, options);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00005173 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005174 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00005175 state.windows.erase(state.windows.begin() + i);
5176 } else {
5177 ++i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005178 }
5179 }
arthurhungb89ccb02020-12-30 16:19:01 +08005180
arthurhung6d4bed92021-03-17 11:59:33 +08005181 // If drag window is gone, it would receive a cancel event and broadcast the DRAG_END. We
arthurhungb89ccb02020-12-30 16:19:01 +08005182 // could just clear the state here.
Arthur Hung3915c1f2022-05-31 07:17:17 +00005183 if (mDragState && mDragState->dragWindow->getInfo()->displayId == displayId &&
arthurhung6d4bed92021-03-17 11:59:33 +08005184 std::find(windowHandles.begin(), windowHandles.end(), mDragState->dragWindow) ==
arthurhungb89ccb02020-12-30 16:19:01 +08005185 windowHandles.end()) {
Arthur Hung3915c1f2022-05-31 07:17:17 +00005186 ALOGI("Drag window went away: %s", mDragState->dragWindow->getName().c_str());
5187 sendDropWindowCommandLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08005188 mDragState.reset();
arthurhungb89ccb02020-12-30 16:19:01 +08005189 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00005190 }
Arthur Hung25e2af12020-03-26 12:58:37 +00005191
Prabir Pradhan8b89c2f2021-07-29 16:30:14 +00005192 // Determine if the orientation of any of the input windows have changed, and cancel all
5193 // pointer events if necessary.
5194 for (const sp<WindowInfoHandle>& oldWindowHandle : oldWindowHandles) {
5195 const sp<WindowInfoHandle> newWindowHandle = getWindowHandleLocked(oldWindowHandle);
5196 if (newWindowHandle != nullptr &&
5197 newWindowHandle->getInfo()->transform.getOrientation() !=
5198 oldWindowOrientations[oldWindowHandle->getId()]) {
5199 std::shared_ptr<InputChannel> inputChannel =
5200 getInputChannelLocked(newWindowHandle->getToken());
5201 if (inputChannel != nullptr) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00005202 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
Prabir Pradhan8b89c2f2021-07-29 16:30:14 +00005203 "touched window's orientation changed");
5204 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
Prabir Pradhan93a0f912021-04-21 13:47:42 -07005205 }
5206 }
5207 }
5208
Arthur Hung72d8dc32020-03-28 00:48:39 +00005209 // Release information for windows that are no longer present.
5210 // This ensures that unused input channels are released promptly.
5211 // Otherwise, they might stick around until the window handle is destroyed
5212 // which might not happen until the next GC.
chaviw98318de2021-05-19 16:45:23 -05005213 for (const sp<WindowInfoHandle>& oldWindowHandle : oldWindowHandles) {
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07005214 if (getWindowHandleLocked(oldWindowHandle) == nullptr) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00005215 if (DEBUG_FOCUS) {
5216 ALOGD("Window went away: %s", oldWindowHandle->getName().c_str());
Arthur Hung25e2af12020-03-26 12:58:37 +00005217 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00005218 oldWindowHandle->releaseChannel();
Arthur Hung25e2af12020-03-26 12:58:37 +00005219 }
chaviw291d88a2019-02-14 10:33:58 -08005220 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005221}
5222
5223void InputDispatcher::setFocusedApplication(
Chris Yea209fde2020-07-22 13:54:51 -07005224 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005225 if (DEBUG_FOCUS) {
5226 ALOGD("setFocusedApplication displayId=%" PRId32 " %s", displayId,
5227 inputApplicationHandle ? inputApplicationHandle->getName().c_str() : "<nullptr>");
5228 }
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05005229 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005230 std::scoped_lock _l(mLock);
Vishnu Nair599f1412021-06-21 10:39:58 -07005231 setFocusedApplicationLocked(displayId, inputApplicationHandle);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005232 } // release lock
5233
5234 // Wake up poll loop since it may need to make new input dispatching choices.
5235 mLooper->wake();
5236}
5237
Vishnu Nair599f1412021-06-21 10:39:58 -07005238void InputDispatcher::setFocusedApplicationLocked(
5239 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
5240 std::shared_ptr<InputApplicationHandle> oldFocusedApplicationHandle =
5241 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
5242
5243 if (sharedPointersEqual(oldFocusedApplicationHandle, inputApplicationHandle)) {
5244 return; // This application is already focused. No need to wake up or change anything.
5245 }
5246
5247 // Set the new application handle.
5248 if (inputApplicationHandle != nullptr) {
5249 mFocusedApplicationHandlesByDisplay[displayId] = inputApplicationHandle;
5250 } else {
5251 mFocusedApplicationHandlesByDisplay.erase(displayId);
5252 }
5253
5254 // No matter what the old focused application was, stop waiting on it because it is
5255 // no longer focused.
5256 resetNoFocusedWindowTimeoutLocked();
5257}
5258
Tiger Huang721e26f2018-07-24 22:26:19 +08005259/**
5260 * Sets the focused display, which is responsible for receiving focus-dispatched input events where
5261 * the display not specified.
5262 *
5263 * We track any unreleased events for each window. If a window loses the ability to receive the
5264 * released event, we will send a cancel event to it. So when the focused display is changed, we
5265 * cancel all the unreleased display-unspecified events for the focused window on the old focused
5266 * display. The display-specified events won't be affected.
5267 */
5268void InputDispatcher::setFocusedDisplay(int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005269 if (DEBUG_FOCUS) {
5270 ALOGD("setFocusedDisplay displayId=%" PRId32, displayId);
5271 }
Tiger Huang721e26f2018-07-24 22:26:19 +08005272 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005273 std::scoped_lock _l(mLock);
Tiger Huang721e26f2018-07-24 22:26:19 +08005274
5275 if (mFocusedDisplayId != displayId) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07005276 sp<IBinder> oldFocusedWindowToken =
Vishnu Nairc519ff72021-01-21 08:23:08 -08005277 mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07005278 if (oldFocusedWindowToken != nullptr) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005279 std::shared_ptr<InputChannel> inputChannel =
Vishnu Nairad321cd2020-08-20 16:40:21 -07005280 getInputChannelLocked(oldFocusedWindowToken);
Tiger Huang721e26f2018-07-24 22:26:19 +08005281 if (inputChannel != nullptr) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005282 CancelationOptions
Michael Wrightfb04fd52022-11-24 22:31:11 +00005283 options(CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005284 "The display which contains this window no longer has focus.");
Michael Wright3dd60e22019-03-27 22:06:44 +00005285 options.displayId = ADISPLAY_ID_NONE;
Tiger Huang721e26f2018-07-24 22:26:19 +08005286 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
5287 }
5288 }
5289 mFocusedDisplayId = displayId;
5290
Chris Ye3c2d6f52020-08-09 10:39:48 -07005291 // Find new focused window and validate
Vishnu Nairc519ff72021-01-21 08:23:08 -08005292 sp<IBinder> newFocusedWindowToken = mFocusResolver.getFocusedWindowToken(displayId);
Prabir Pradhancef936d2021-07-21 16:17:52 +00005293 sendFocusChangedCommandLocked(oldFocusedWindowToken, newFocusedWindowToken);
Robert Carrf759f162018-11-13 12:57:11 -08005294
Vishnu Nairad321cd2020-08-20 16:40:21 -07005295 if (newFocusedWindowToken == nullptr) {
Tiger Huang721e26f2018-07-24 22:26:19 +08005296 ALOGW("Focused display #%" PRId32 " does not have a focused window.", displayId);
Vishnu Nairc519ff72021-01-21 08:23:08 -08005297 if (mFocusResolver.hasFocusedWindowTokens()) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07005298 ALOGE("But another display has a focused window\n%s",
Vishnu Nairc519ff72021-01-21 08:23:08 -08005299 mFocusResolver.dumpFocusedWindows().c_str());
Tiger Huang721e26f2018-07-24 22:26:19 +08005300 }
5301 }
5302 }
Tiger Huang721e26f2018-07-24 22:26:19 +08005303 } // release lock
5304
5305 // Wake up poll loop since it may need to make new input dispatching choices.
5306 mLooper->wake();
5307}
5308
Michael Wrightd02c5b62014-02-10 15:10:22 -08005309void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005310 if (DEBUG_FOCUS) {
5311 ALOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
5312 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005313
5314 bool changed;
5315 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005316 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005317
5318 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
5319 if (mDispatchFrozen && !frozen) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005320 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005321 }
5322
5323 if (mDispatchEnabled && !enabled) {
5324 resetAndDropEverythingLocked("dispatcher is being disabled");
5325 }
5326
5327 mDispatchEnabled = enabled;
5328 mDispatchFrozen = frozen;
5329 changed = true;
5330 } else {
5331 changed = false;
5332 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005333 } // release lock
5334
5335 if (changed) {
5336 // Wake up poll loop since it may need to make new input dispatching choices.
5337 mLooper->wake();
5338 }
5339}
5340
5341void InputDispatcher::setInputFilterEnabled(bool enabled) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005342 if (DEBUG_FOCUS) {
5343 ALOGD("setInputFilterEnabled: enabled=%d", enabled);
5344 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005345
5346 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005347 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005348
5349 if (mInputFilterEnabled == enabled) {
5350 return;
5351 }
5352
5353 mInputFilterEnabled = enabled;
5354 resetAndDropEverythingLocked("input filter is being enabled or disabled");
5355 } // release lock
5356
5357 // Wake up poll loop since there might be work to do to drop everything.
5358 mLooper->wake();
5359}
5360
Prabir Pradhane59c6dc2023-06-13 19:53:03 +00005361bool InputDispatcher::setInTouchMode(bool inTouchMode, gui::Pid pid, gui::Uid uid,
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00005362 bool hasPermission, int32_t displayId) {
Antonio Kantekf16f2832021-09-28 04:39:20 +00005363 bool needWake = false;
5364 {
5365 std::scoped_lock lock(mLock);
Antonio Kantek15beb512022-06-13 22:35:41 +00005366 ALOGD_IF(DEBUG_TOUCH_MODE,
Prabir Pradhane59c6dc2023-06-13 19:53:03 +00005367 "Request to change touch mode to %s (calling pid=%s, uid=%s, "
Antonio Kantek15beb512022-06-13 22:35:41 +00005368 "hasPermission=%s, target displayId=%d, mTouchModePerDisplay[displayId]=%s)",
Prabir Pradhane59c6dc2023-06-13 19:53:03 +00005369 toString(inTouchMode), pid.toString().c_str(), uid.toString().c_str(),
5370 toString(hasPermission), displayId,
Antonio Kantek15beb512022-06-13 22:35:41 +00005371 mTouchModePerDisplay.count(displayId) == 0
5372 ? "not set"
5373 : std::to_string(mTouchModePerDisplay[displayId]).c_str());
5374
Antonio Kantek15beb512022-06-13 22:35:41 +00005375 auto touchModeIt = mTouchModePerDisplay.find(displayId);
5376 if (touchModeIt != mTouchModePerDisplay.end() && touchModeIt->second == inTouchMode) {
Antonio Kantekea47acb2021-12-23 12:41:25 -08005377 return false;
Antonio Kantekf16f2832021-09-28 04:39:20 +00005378 }
Antonio Kantekea47acb2021-12-23 12:41:25 -08005379 if (!hasPermission) {
Antonio Kantek48710e42022-03-24 14:19:30 -07005380 if (!focusedWindowIsOwnedByLocked(pid, uid) &&
5381 !recentWindowsAreOwnedByLocked(pid, uid)) {
Prabir Pradhane59c6dc2023-06-13 19:53:03 +00005382 ALOGD("Touch mode switch rejected, caller (pid=%s, uid=%s) doesn't own the focused "
Antonio Kantek48710e42022-03-24 14:19:30 -07005383 "window nor none of the previously interacted window",
Prabir Pradhane59c6dc2023-06-13 19:53:03 +00005384 pid.toString().c_str(), uid.toString().c_str());
Antonio Kantekea47acb2021-12-23 12:41:25 -08005385 return false;
5386 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00005387 }
Antonio Kantek15beb512022-06-13 22:35:41 +00005388 mTouchModePerDisplay[displayId] = inTouchMode;
5389 auto entry = std::make_unique<TouchModeEntry>(mIdGenerator.nextId(), now(), inTouchMode,
5390 displayId);
Antonio Kantekf16f2832021-09-28 04:39:20 +00005391 needWake = enqueueInboundEventLocked(std::move(entry));
5392 } // release lock
5393
5394 if (needWake) {
5395 mLooper->wake();
5396 }
Antonio Kantekea47acb2021-12-23 12:41:25 -08005397 return true;
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -08005398}
5399
Prabir Pradhane59c6dc2023-06-13 19:53:03 +00005400bool InputDispatcher::focusedWindowIsOwnedByLocked(gui::Pid pid, gui::Uid uid) {
Antonio Kantek48710e42022-03-24 14:19:30 -07005401 const sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
5402 if (focusedToken == nullptr) {
5403 return false;
5404 }
5405 sp<WindowInfoHandle> windowHandle = getWindowHandleLocked(focusedToken);
5406 return isWindowOwnedBy(windowHandle, pid, uid);
5407}
5408
Prabir Pradhane59c6dc2023-06-13 19:53:03 +00005409bool InputDispatcher::recentWindowsAreOwnedByLocked(gui::Pid pid, gui::Uid uid) {
Antonio Kantek48710e42022-03-24 14:19:30 -07005410 return std::find_if(mInteractionConnectionTokens.begin(), mInteractionConnectionTokens.end(),
5411 [&](const sp<IBinder>& connectionToken) REQUIRES(mLock) {
5412 const sp<WindowInfoHandle> windowHandle =
5413 getWindowHandleLocked(connectionToken);
5414 return isWindowOwnedBy(windowHandle, pid, uid);
5415 }) != mInteractionConnectionTokens.end();
5416}
5417
Bernardo Rufinoea97d182020-08-19 14:43:14 +01005418void InputDispatcher::setMaximumObscuringOpacityForTouch(float opacity) {
5419 if (opacity < 0 || opacity > 1) {
5420 LOG_ALWAYS_FATAL("Maximum obscuring opacity for touch should be >= 0 and <= 1");
5421 return;
5422 }
5423
5424 std::scoped_lock lock(mLock);
5425 mMaximumObscuringOpacityForTouch = opacity;
5426}
5427
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005428std::tuple<TouchState*, TouchedWindow*, int32_t /*displayId*/>
5429InputDispatcher::findTouchStateWindowAndDisplayLocked(const sp<IBinder>& token) {
Arthur Hungabbb9d82021-09-01 14:52:30 +00005430 for (auto& [displayId, state] : mTouchStatesByDisplay) {
5431 for (TouchedWindow& w : state.windows) {
5432 if (w.windowHandle->getToken() == token) {
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005433 return std::make_tuple(&state, &w, displayId);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005434 }
5435 }
5436 }
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005437 return std::make_tuple(nullptr, nullptr, ADISPLAY_ID_DEFAULT);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005438}
5439
arthurhungb89ccb02020-12-30 16:19:01 +08005440bool InputDispatcher::transferTouchFocus(const sp<IBinder>& fromToken, const sp<IBinder>& toToken,
5441 bool isDragDrop) {
chaviwfbe5d9c2018-12-26 12:23:37 -08005442 if (fromToken == toToken) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005443 if (DEBUG_FOCUS) {
5444 ALOGD("Trivial transfer to same window.");
5445 }
chaviwfbe5d9c2018-12-26 12:23:37 -08005446 return true;
5447 }
5448
Michael Wrightd02c5b62014-02-10 15:10:22 -08005449 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005450 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005451
Arthur Hungabbb9d82021-09-01 14:52:30 +00005452 // Find the target touch state and touched window by fromToken.
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005453 auto [state, touchedWindow, displayId] = findTouchStateWindowAndDisplayLocked(fromToken);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005454 if (state == nullptr || touchedWindow == nullptr) {
5455 ALOGD("Focus transfer failed because from window is not being touched.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005456 return false;
5457 }
Arthur Hungabbb9d82021-09-01 14:52:30 +00005458
Arthur Hungabbb9d82021-09-01 14:52:30 +00005459 sp<WindowInfoHandle> toWindowHandle = getWindowHandleLocked(toToken, displayId);
5460 if (toWindowHandle == nullptr) {
5461 ALOGW("Cannot transfer focus because to window not found.");
5462 return false;
5463 }
5464
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005465 if (DEBUG_FOCUS) {
5466 ALOGD("transferTouchFocus: fromWindowHandle=%s, toWindowHandle=%s",
Arthur Hungabbb9d82021-09-01 14:52:30 +00005467 touchedWindow->windowHandle->getName().c_str(),
5468 toWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005469 }
5470
Arthur Hungabbb9d82021-09-01 14:52:30 +00005471 // Erase old window.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005472 ftl::Flags<InputTarget::Flags> oldTargetFlags = touchedWindow->targetFlags;
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08005473 std::bitset<MAX_POINTER_ID + 1> pointerIds = touchedWindow->pointerIds;
Arthur Hungc539dbb2022-12-08 07:45:36 +00005474 sp<WindowInfoHandle> fromWindowHandle = touchedWindow->windowHandle;
Arthur Hungabbb9d82021-09-01 14:52:30 +00005475 state->removeWindowByToken(fromToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005476
Arthur Hungabbb9d82021-09-01 14:52:30 +00005477 // Add new window.
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00005478 nsecs_t downTimeInTarget = now();
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005479 ftl::Flags<InputTarget::Flags> newTargetFlags =
5480 oldTargetFlags & (InputTarget::Flags::SPLIT | InputTarget::Flags::DISPATCH_AS_IS);
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00005481 if (canReceiveForegroundTouches(*toWindowHandle->getInfo())) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005482 newTargetFlags |= InputTarget::Flags::FOREGROUND;
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00005483 }
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00005484 state->addOrUpdateWindow(toWindowHandle, newTargetFlags, pointerIds, downTimeInTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005485
Arthur Hungabbb9d82021-09-01 14:52:30 +00005486 // Store the dragging window.
5487 if (isDragDrop) {
Arthur Hungb75c2aa2022-07-15 09:35:36 +00005488 if (pointerIds.count() != 1) {
5489 ALOGW("The drag and drop cannot be started when there is no pointer or more than 1"
5490 " pointer on the window.");
Arthur Hung54745652022-04-20 07:17:41 +00005491 return false;
5492 }
Arthur Hungb75c2aa2022-07-15 09:35:36 +00005493 // Track the pointer id for drag window and generate the drag state.
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08005494 const size_t id = firstMarkedBit(pointerIds);
Arthur Hung54745652022-04-20 07:17:41 +00005495 mDragState = std::make_unique<DragState>(toWindowHandle, id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005496 }
5497
Arthur Hungabbb9d82021-09-01 14:52:30 +00005498 // Synthesize cancel for old window and down for new window.
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07005499 std::shared_ptr<Connection> fromConnection = getConnectionLocked(fromToken);
5500 std::shared_ptr<Connection> toConnection = getConnectionLocked(toToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005501 if (fromConnection != nullptr && toConnection != nullptr) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08005502 fromConnection->inputState.mergePointerStateTo(toConnection->inputState);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005503 CancelationOptions
Michael Wrightfb04fd52022-11-24 22:31:11 +00005504 options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005505 "transferring touch focus from this window to another window");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005506 synthesizeCancelationEventsForConnectionLocked(fromConnection, options);
Arthur Hungc539dbb2022-12-08 07:45:36 +00005507 synthesizePointerDownEventsForConnectionLocked(downTimeInTarget, toConnection,
5508 newTargetFlags);
5509
5510 // Check if the wallpaper window should deliver the corresponding event.
5511 transferWallpaperTouch(oldTargetFlags, newTargetFlags, fromWindowHandle, toWindowHandle,
5512 *state, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005513 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005514 } // release lock
5515
5516 // Wake up poll loop since it may need to make new input dispatching choices.
5517 mLooper->wake();
5518 return true;
5519}
5520
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005521/**
5522 * Get the touched foreground window on the given display.
5523 * Return null if there are no windows touched on that display, or if more than one foreground
5524 * window is being touched.
5525 */
5526sp<WindowInfoHandle> InputDispatcher::findTouchedForegroundWindowLocked(int32_t displayId) const {
5527 auto stateIt = mTouchStatesByDisplay.find(displayId);
5528 if (stateIt == mTouchStatesByDisplay.end()) {
5529 ALOGI("No touch state on display %" PRId32, displayId);
5530 return nullptr;
5531 }
5532
5533 const TouchState& state = stateIt->second;
5534 sp<WindowInfoHandle> touchedForegroundWindow;
5535 // If multiple foreground windows are touched, return nullptr
5536 for (const TouchedWindow& window : state.windows) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005537 if (window.targetFlags.test(InputTarget::Flags::FOREGROUND)) {
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005538 if (touchedForegroundWindow != nullptr) {
5539 ALOGI("Two or more foreground windows: %s and %s",
5540 touchedForegroundWindow->getName().c_str(),
5541 window.windowHandle->getName().c_str());
5542 return nullptr;
5543 }
5544 touchedForegroundWindow = window.windowHandle;
5545 }
5546 }
5547 return touchedForegroundWindow;
5548}
5549
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005550// Binder call
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005551bool InputDispatcher::transferTouch(const sp<IBinder>& destChannelToken, int32_t displayId) {
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005552 sp<IBinder> fromToken;
5553 { // acquire lock
5554 std::scoped_lock _l(mLock);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005555 sp<WindowInfoHandle> toWindowHandle = getWindowHandleLocked(destChannelToken, displayId);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005556 if (toWindowHandle == nullptr) {
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005557 ALOGW("Could not find window associated with token=%p on display %" PRId32,
5558 destChannelToken.get(), displayId);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005559 return false;
5560 }
5561
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005562 sp<WindowInfoHandle> from = findTouchedForegroundWindowLocked(displayId);
5563 if (from == nullptr) {
5564 ALOGE("Could not find a source window in %s for %p", __func__, destChannelToken.get());
5565 return false;
5566 }
5567
5568 fromToken = from->getToken();
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005569 } // release lock
5570
5571 return transferTouchFocus(fromToken, destChannelToken);
5572}
5573
Michael Wrightd02c5b62014-02-10 15:10:22 -08005574void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005575 if (DEBUG_FOCUS) {
5576 ALOGD("Resetting and dropping all events (%s).", reason);
5577 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005578
Michael Wrightfb04fd52022-11-24 22:31:11 +00005579 CancelationOptions options(CancelationOptions::Mode::CANCEL_ALL_EVENTS, reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005580 synthesizeCancelationEventsForAllConnectionsLocked(options);
5581
5582 resetKeyRepeatLocked();
5583 releasePendingEventLocked();
5584 drainInboundQueueLocked();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005585 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005586
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005587 mAnrTracker.clear();
Jeff Brownf086ddb2014-02-11 14:28:48 -08005588 mTouchStatesByDisplay.clear();
Michael Wright78f24442014-08-06 15:55:28 -07005589 mReplacedKeys.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005590}
5591
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005592void InputDispatcher::logDispatchStateLocked() const {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005593 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005594 dumpDispatchStateLocked(dump);
5595
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005596 std::istringstream stream(dump);
5597 std::string line;
5598
5599 while (std::getline(stream, line, '\n')) {
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07005600 ALOGI("%s", line.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005601 }
5602}
5603
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005604std::string InputDispatcher::dumpPointerCaptureStateLocked() const {
Prabir Pradhan99987712020-11-10 18:43:05 -08005605 std::string dump;
5606
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005607 dump += StringPrintf(INDENT "Pointer Capture Requested: %s\n",
5608 toString(mCurrentPointerCaptureRequest.enable));
Prabir Pradhan99987712020-11-10 18:43:05 -08005609
5610 std::string windowName = "None";
5611 if (mWindowTokenWithPointerCapture) {
chaviw98318de2021-05-19 16:45:23 -05005612 const sp<WindowInfoHandle> captureWindowHandle =
Prabir Pradhan99987712020-11-10 18:43:05 -08005613 getWindowHandleLocked(mWindowTokenWithPointerCapture);
5614 windowName = captureWindowHandle ? captureWindowHandle->getName().c_str()
5615 : "token has capture without window";
5616 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005617 dump += StringPrintf(INDENT "Current Window with Pointer Capture: %s\n", windowName.c_str());
Prabir Pradhan99987712020-11-10 18:43:05 -08005618
5619 return dump;
5620}
5621
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005622void InputDispatcher::dumpDispatchStateLocked(std::string& dump) const {
Siarhei Vishniakou043a3ec2019-05-01 11:30:46 -07005623 dump += StringPrintf(INDENT "DispatchEnabled: %s\n", toString(mDispatchEnabled));
5624 dump += StringPrintf(INDENT "DispatchFrozen: %s\n", toString(mDispatchFrozen));
5625 dump += StringPrintf(INDENT "InputFilterEnabled: %s\n", toString(mInputFilterEnabled));
Tiger Huang721e26f2018-07-24 22:26:19 +08005626 dump += StringPrintf(INDENT "FocusedDisplayId: %" PRId32 "\n", mFocusedDisplayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005627
Tiger Huang721e26f2018-07-24 22:26:19 +08005628 if (!mFocusedApplicationHandlesByDisplay.empty()) {
5629 dump += StringPrintf(INDENT "FocusedApplications:\n");
5630 for (auto& it : mFocusedApplicationHandlesByDisplay) {
5631 const int32_t displayId = it.first;
Chris Yea209fde2020-07-22 13:54:51 -07005632 const std::shared_ptr<InputApplicationHandle>& applicationHandle = it.second;
Siarhei Vishniakou70622952020-07-30 11:17:23 -05005633 const std::chrono::duration timeout =
5634 applicationHandle->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005635 dump += StringPrintf(INDENT2 "displayId=%" PRId32
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005636 ", name='%s', dispatchingTimeout=%" PRId64 "ms\n",
Siarhei Vishniakou70622952020-07-30 11:17:23 -05005637 displayId, applicationHandle->getName().c_str(), millis(timeout));
Tiger Huang721e26f2018-07-24 22:26:19 +08005638 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005639 } else {
Tiger Huang721e26f2018-07-24 22:26:19 +08005640 dump += StringPrintf(INDENT "FocusedApplications: <none>\n");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005641 }
Tiger Huang721e26f2018-07-24 22:26:19 +08005642
Vishnu Nairc519ff72021-01-21 08:23:08 -08005643 dump += mFocusResolver.dump();
Prabir Pradhan99987712020-11-10 18:43:05 -08005644 dump += dumpPointerCaptureStateLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005645
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005646 if (!mTouchStatesByDisplay.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005647 dump += StringPrintf(INDENT "TouchStatesByDisplay:\n");
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005648 for (const auto& [displayId, state] : mTouchStatesByDisplay) {
Siarhei Vishniakou6e1e9872022-11-08 17:51:35 -08005649 std::string touchStateDump = addLinePrefix(state.dump(), INDENT2);
5650 dump += INDENT2 + std::to_string(displayId) + " : " + touchStateDump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005651 }
5652 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005653 dump += INDENT "TouchStates: <no displays touched>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005654 }
5655
arthurhung6d4bed92021-03-17 11:59:33 +08005656 if (mDragState) {
5657 dump += StringPrintf(INDENT "DragState:\n");
5658 mDragState->dump(dump, INDENT2);
5659 }
5660
Arthur Hungb92218b2018-08-14 12:00:21 +08005661 if (!mWindowHandlesByDisplay.empty()) {
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005662 for (const auto& [displayId, windowHandles] : mWindowHandlesByDisplay) {
5663 dump += StringPrintf(INDENT "Display: %" PRId32 "\n", displayId);
5664 if (const auto& it = mDisplayInfos.find(displayId); it != mDisplayInfos.end()) {
5665 const auto& displayInfo = it->second;
5666 dump += StringPrintf(INDENT2 "logicalSize=%dx%d\n", displayInfo.logicalWidth,
5667 displayInfo.logicalHeight);
5668 displayInfo.transform.dump(dump, "transform", INDENT4);
5669 } else {
5670 dump += INDENT2 "No DisplayInfo found!\n";
5671 }
5672
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08005673 if (!windowHandles.empty()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08005674 dump += INDENT2 "Windows:\n";
5675 for (size_t i = 0; i < windowHandles.size(); i++) {
chaviw98318de2021-05-19 16:45:23 -05005676 const sp<WindowInfoHandle>& windowHandle = windowHandles[i];
5677 const WindowInfo* windowInfo = windowHandle->getInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005678
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00005679 dump += StringPrintf(INDENT3 "%zu: name='%s', id=%" PRId32 ", displayId=%d, "
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005680 "inputConfig=%s, alpha=%.2f, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005681 "frame=[%d,%d][%d,%d], globalScale=%f, "
Bernardo Rufino49d99e42021-01-18 15:16:59 +00005682 "applicationInfo.name=%s, "
5683 "applicationInfo.token=%s, "
chaviw1ff3d1e2020-07-01 15:53:47 -07005684 "touchableRegion=",
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00005685 i, windowInfo->name.c_str(), windowInfo->id,
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005686 windowInfo->displayId,
5687 windowInfo->inputConfig.string().c_str(),
5688 windowInfo->alpha, windowInfo->frameLeft,
5689 windowInfo->frameTop, windowInfo->frameRight,
5690 windowInfo->frameBottom, windowInfo->globalScaleFactor,
Bernardo Rufino49d99e42021-01-18 15:16:59 +00005691 windowInfo->applicationInfo.name.c_str(),
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07005692 binderToString(windowInfo->applicationInfo.token).c_str());
Bernardo Rufino53fc31e2020-11-03 11:01:07 +00005693 dump += dumpRegion(windowInfo->touchableRegion);
Prabir Pradhane59c6dc2023-06-13 19:53:03 +00005694 dump += StringPrintf(", ownerPid=%s, ownerUid=%s, dispatchingTimeout=%" PRId64
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005695 "ms, hasToken=%s, "
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005696 "touchOcclusionMode=%s\n",
Prabir Pradhane59c6dc2023-06-13 19:53:03 +00005697 windowInfo->ownerPid.toString().c_str(),
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00005698 windowInfo->ownerUid.toString().c_str(),
Bernardo Rufinoc2f1fad2020-11-04 17:30:57 +00005699 millis(windowInfo->dispatchingTimeout),
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07005700 binderToString(windowInfo->token).c_str(),
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005701 toString(windowInfo->touchOcclusionMode).c_str());
chaviw85b44202020-07-24 11:46:21 -07005702 windowInfo->transform.dump(dump, "transform", INDENT4);
Arthur Hungb92218b2018-08-14 12:00:21 +08005703 }
5704 } else {
5705 dump += INDENT2 "Windows: <none>\n";
5706 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005707 }
5708 } else {
Arthur Hungb92218b2018-08-14 12:00:21 +08005709 dump += INDENT "Displays: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005710 }
5711
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005712 if (!mGlobalMonitorsByDisplay.empty()) {
5713 for (const auto& [displayId, monitors] : mGlobalMonitorsByDisplay) {
5714 dump += StringPrintf(INDENT "Global monitors on display %d:\n", displayId);
Michael Wright3dd60e22019-03-27 22:06:44 +00005715 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005716 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005717 } else {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005718 dump += INDENT "Global Monitors: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005719 }
5720
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005721 const nsecs_t currentTime = now();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005722
5723 // Dump recently dispatched or dropped events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005724 if (!mRecentQueue.empty()) {
5725 dump += StringPrintf(INDENT "RecentQueue: length=%zu\n", mRecentQueue.size());
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005726 for (const std::shared_ptr<EventEntry>& entry : mRecentQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005727 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005728 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005729 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005730 }
5731 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005732 dump += INDENT "RecentQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005733 }
5734
5735 // Dump event currently being dispatched.
5736 if (mPendingEvent) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005737 dump += INDENT "PendingEvent:\n";
5738 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005739 dump += mPendingEvent->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005740 dump += StringPrintf(", age=%" PRId64 "ms\n",
5741 ns2ms(currentTime - mPendingEvent->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005742 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005743 dump += INDENT "PendingEvent: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005744 }
5745
5746 // Dump inbound events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005747 if (!mInboundQueue.empty()) {
5748 dump += StringPrintf(INDENT "InboundQueue: length=%zu\n", mInboundQueue.size());
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005749 for (const std::shared_ptr<EventEntry>& entry : mInboundQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005750 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005751 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005752 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005753 }
5754 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005755 dump += INDENT "InboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005756 }
5757
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005758 if (!mReplacedKeys.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005759 dump += INDENT "ReplacedKeys:\n";
Michael Wright3cec4462022-11-24 22:05:46 +00005760 for (const auto& [replacement, newKeyCode] : mReplacedKeys) {
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005761 dump += StringPrintf(INDENT2 "originalKeyCode=%d, deviceId=%d -> newKeyCode=%d\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005762 replacement.keyCode, replacement.deviceId, newKeyCode);
Michael Wright78f24442014-08-06 15:55:28 -07005763 }
5764 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005765 dump += INDENT "ReplacedKeys: <empty>\n";
Michael Wright78f24442014-08-06 15:55:28 -07005766 }
5767
Prabir Pradhancef936d2021-07-21 16:17:52 +00005768 if (!mCommandQueue.empty()) {
5769 dump += StringPrintf(INDENT "CommandQueue: size=%zu\n", mCommandQueue.size());
5770 } else {
5771 dump += INDENT "CommandQueue: <empty>\n";
5772 }
5773
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005774 if (!mConnectionsByToken.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005775 dump += INDENT "Connections:\n";
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005776 for (const auto& [token, connection] : mConnectionsByToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005777 dump += StringPrintf(INDENT2 "%i: channelName='%s', windowName='%s', "
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005778 "status=%s, monitor=%s, responsive=%s\n",
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005779 connection->inputChannel->getFd().get(),
5780 connection->getInputChannelName().c_str(),
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08005781 connection->getWindowName().c_str(),
5782 ftl::enum_string(connection->status).c_str(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005783 toString(connection->monitor), toString(connection->responsive));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005784
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005785 if (!connection->outboundQueue.empty()) {
5786 dump += StringPrintf(INDENT3 "OutboundQueue: length=%zu\n",
5787 connection->outboundQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005788 dump += dumpQueue(connection->outboundQueue, currentTime);
5789
Michael Wrightd02c5b62014-02-10 15:10:22 -08005790 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005791 dump += INDENT3 "OutboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005792 }
5793
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005794 if (!connection->waitQueue.empty()) {
5795 dump += StringPrintf(INDENT3 "WaitQueue: length=%zu\n",
5796 connection->waitQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005797 dump += dumpQueue(connection->waitQueue, currentTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005798 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005799 dump += INDENT3 "WaitQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005800 }
5801 }
5802 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005803 dump += INDENT "Connections: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005804 }
5805
5806 if (isAppSwitchPendingLocked()) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005807 dump += StringPrintf(INDENT "AppSwitch: pending, due in %" PRId64 "ms\n",
5808 ns2ms(mAppSwitchDueTime - now()));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005809 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005810 dump += INDENT "AppSwitch: not pending\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005811 }
5812
Antonio Kantek15beb512022-06-13 22:35:41 +00005813 if (!mTouchModePerDisplay.empty()) {
5814 dump += INDENT "TouchModePerDisplay:\n";
5815 for (const auto& [displayId, touchMode] : mTouchModePerDisplay) {
5816 dump += StringPrintf(INDENT2 "Display: %" PRId32 " TouchMode: %s\n", displayId,
5817 std::to_string(touchMode).c_str());
5818 }
5819 } else {
5820 dump += INDENT "TouchModePerDisplay: <none>\n";
5821 }
5822
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005823 dump += INDENT "Configuration:\n";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005824 dump += StringPrintf(INDENT2 "KeyRepeatDelay: %" PRId64 "ms\n", ns2ms(mConfig.keyRepeatDelay));
5825 dump += StringPrintf(INDENT2 "KeyRepeatTimeout: %" PRId64 "ms\n",
5826 ns2ms(mConfig.keyRepeatTimeout));
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00005827 dump += mLatencyTracker.dump(INDENT2);
Siarhei Vishniakoua04181f2021-03-26 05:56:49 +00005828 dump += mLatencyAggregator.dump(INDENT2);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005829}
5830
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005831void InputDispatcher::dumpMonitors(std::string& dump, const std::vector<Monitor>& monitors) const {
Michael Wright3dd60e22019-03-27 22:06:44 +00005832 const size_t numMonitors = monitors.size();
5833 for (size_t i = 0; i < numMonitors; i++) {
5834 const Monitor& monitor = monitors[i];
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005835 const std::shared_ptr<InputChannel>& channel = monitor.inputChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005836 dump += StringPrintf(INDENT2 "%zu: '%s', ", i, channel->getName().c_str());
5837 dump += "\n";
5838 }
5839}
5840
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005841class LooperEventCallback : public LooperCallback {
5842public:
5843 LooperEventCallback(std::function<int(int events)> callback) : mCallback(callback) {}
5844 int handleEvent(int /*fd*/, int events, void* /*data*/) override { return mCallback(events); }
5845
5846private:
5847 std::function<int(int events)> mCallback;
5848};
5849
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005850Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputChannel(const std::string& name) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00005851 if (DEBUG_CHANNEL_CREATION) {
5852 ALOGD("channel '%s' ~ createInputChannel", name.c_str());
5853 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005854
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005855 std::unique_ptr<InputChannel> serverChannel;
Garfield Tan15601662020-09-22 15:32:38 -07005856 std::unique_ptr<InputChannel> clientChannel;
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005857 status_t result = InputChannel::openInputChannelPair(name, serverChannel, clientChannel);
Garfield Tan15601662020-09-22 15:32:38 -07005858
5859 if (result) {
5860 return base::Error(result) << "Failed to open input channel pair with name " << name;
5861 }
5862
Michael Wrightd02c5b62014-02-10 15:10:22 -08005863 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005864 std::scoped_lock _l(mLock);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005865 const sp<IBinder>& token = serverChannel->getConnectionToken();
Garfield Tan15601662020-09-22 15:32:38 -07005866 int fd = serverChannel->getFd();
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07005867 std::shared_ptr<Connection> connection =
5868 std::make_shared<Connection>(std::move(serverChannel), /*monitor=*/false,
5869 mIdGenerator);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005870
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005871 if (mConnectionsByToken.find(token) != mConnectionsByToken.end()) {
5872 ALOGE("Created a new connection, but the token %p is already known", token.get());
5873 }
5874 mConnectionsByToken.emplace(token, connection);
5875
5876 std::function<int(int events)> callback = std::bind(&InputDispatcher::handleReceiveCallback,
5877 this, std::placeholders::_1, token);
5878
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005879 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, sp<LooperEventCallback>::make(callback),
5880 nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005881 } // release lock
5882
5883 // Wake the looper because some connections have changed.
5884 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07005885 return clientChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005886}
5887
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005888Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputMonitor(int32_t displayId,
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005889 const std::string& name,
Prabir Pradhane59c6dc2023-06-13 19:53:03 +00005890 gui::Pid pid) {
Garfield Tan15601662020-09-22 15:32:38 -07005891 std::shared_ptr<InputChannel> serverChannel;
5892 std::unique_ptr<InputChannel> clientChannel;
5893 status_t result = openInputChannelPair(name, serverChannel, clientChannel);
5894 if (result) {
5895 return base::Error(result) << "Failed to open input channel pair with name " << name;
5896 }
5897
Michael Wright3dd60e22019-03-27 22:06:44 +00005898 { // acquire lock
5899 std::scoped_lock _l(mLock);
5900
5901 if (displayId < 0) {
Garfield Tan15601662020-09-22 15:32:38 -07005902 return base::Error(BAD_VALUE) << "Attempted to create input monitor with name " << name
5903 << " without a specified display.";
Michael Wright3dd60e22019-03-27 22:06:44 +00005904 }
5905
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07005906 std::shared_ptr<Connection> connection =
5907 std::make_shared<Connection>(serverChannel, /*monitor=*/true, mIdGenerator);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005908 const sp<IBinder>& token = serverChannel->getConnectionToken();
Garfield Tan15601662020-09-22 15:32:38 -07005909 const int fd = serverChannel->getFd();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005910
5911 if (mConnectionsByToken.find(token) != mConnectionsByToken.end()) {
5912 ALOGE("Created a new connection, but the token %p is already known", token.get());
5913 }
5914 mConnectionsByToken.emplace(token, connection);
5915 std::function<int(int events)> callback = std::bind(&InputDispatcher::handleReceiveCallback,
5916 this, std::placeholders::_1, token);
Michael Wright3dd60e22019-03-27 22:06:44 +00005917
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005918 mGlobalMonitorsByDisplay[displayId].emplace_back(serverChannel, pid);
Michael Wright3dd60e22019-03-27 22:06:44 +00005919
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005920 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, sp<LooperEventCallback>::make(callback),
5921 nullptr);
Michael Wright3dd60e22019-03-27 22:06:44 +00005922 }
Garfield Tan15601662020-09-22 15:32:38 -07005923
Michael Wright3dd60e22019-03-27 22:06:44 +00005924 // Wake the looper because some connections have changed.
5925 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07005926 return clientChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005927}
5928
Garfield Tan15601662020-09-22 15:32:38 -07005929status_t InputDispatcher::removeInputChannel(const sp<IBinder>& connectionToken) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005930 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005931 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005932
Harry Cutts33476232023-01-30 19:57:29 +00005933 status_t status = removeInputChannelLocked(connectionToken, /*notify=*/false);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005934 if (status) {
5935 return status;
5936 }
5937 } // release lock
5938
5939 // Wake the poll loop because removing the connection may have changed the current
5940 // synchronization state.
5941 mLooper->wake();
5942 return OK;
5943}
5944
Garfield Tan15601662020-09-22 15:32:38 -07005945status_t InputDispatcher::removeInputChannelLocked(const sp<IBinder>& connectionToken,
5946 bool notify) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07005947 std::shared_ptr<Connection> connection = getConnectionLocked(connectionToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005948 if (connection == nullptr) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005949 // Connection can be removed via socket hang up or an explicit call to 'removeInputChannel'
Michael Wrightd02c5b62014-02-10 15:10:22 -08005950 return BAD_VALUE;
5951 }
5952
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005953 removeConnectionLocked(connection);
Robert Carr5c8a0262018-10-03 16:30:44 -07005954
Michael Wrightd02c5b62014-02-10 15:10:22 -08005955 if (connection->monitor) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005956 removeMonitorChannelLocked(connectionToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005957 }
5958
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005959 mLooper->removeFd(connection->inputChannel->getFd());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005960
5961 nsecs_t currentTime = now();
5962 abortBrokenDispatchCycleLocked(currentTime, connection, notify);
5963
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08005964 connection->status = Connection::Status::ZOMBIE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005965 return OK;
5966}
5967
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005968void InputDispatcher::removeMonitorChannelLocked(const sp<IBinder>& connectionToken) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005969 for (auto it = mGlobalMonitorsByDisplay.begin(); it != mGlobalMonitorsByDisplay.end();) {
5970 auto& [displayId, monitors] = *it;
5971 std::erase_if(monitors, [connectionToken](const Monitor& monitor) {
5972 return monitor.inputChannel->getConnectionToken() == connectionToken;
5973 });
Michael Wright3dd60e22019-03-27 22:06:44 +00005974
Michael Wright3dd60e22019-03-27 22:06:44 +00005975 if (monitors.empty()) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005976 it = mGlobalMonitorsByDisplay.erase(it);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005977 } else {
5978 ++it;
5979 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005980 }
5981}
5982
Michael Wright3dd60e22019-03-27 22:06:44 +00005983status_t InputDispatcher::pilferPointers(const sp<IBinder>& token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005984 std::scoped_lock _l(mLock);
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00005985 return pilferPointersLocked(token);
5986}
Michael Wright3dd60e22019-03-27 22:06:44 +00005987
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00005988status_t InputDispatcher::pilferPointersLocked(const sp<IBinder>& token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005989 const std::shared_ptr<InputChannel> requestingChannel = getInputChannelLocked(token);
5990 if (!requestingChannel) {
5991 ALOGW("Attempted to pilfer pointers from an un-registered channel or invalid token");
5992 return BAD_VALUE;
Michael Wright3dd60e22019-03-27 22:06:44 +00005993 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005994
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005995 auto [statePtr, windowPtr, displayId] = findTouchStateWindowAndDisplayLocked(token);
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08005996 if (statePtr == nullptr || windowPtr == nullptr || windowPtr->pointerIds.none()) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005997 ALOGW("Attempted to pilfer points from a channel without any on-going pointer streams."
5998 " Ignoring.");
5999 return BAD_VALUE;
6000 }
6001
6002 TouchState& state = *statePtr;
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00006003 TouchedWindow& window = *windowPtr;
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006004 // Send cancel events to all the input channels we're stealing from.
Michael Wrightfb04fd52022-11-24 22:31:11 +00006005 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006006 "input channel stole pointer stream");
6007 options.deviceId = state.deviceId;
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07006008 options.displayId = displayId;
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07006009 options.pointerIds = window.pointerIds;
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006010 std::string canceledWindows;
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00006011 for (const TouchedWindow& w : state.windows) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006012 const std::shared_ptr<InputChannel> channel =
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00006013 getInputChannelLocked(w.windowHandle->getToken());
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006014 if (channel != nullptr && channel->getConnectionToken() != token) {
6015 synthesizeCancelationEventsForInputChannelLocked(channel, options);
6016 canceledWindows += canceledWindows.empty() ? "[" : ", ";
6017 canceledWindows += channel->getName();
6018 }
6019 }
6020 canceledWindows += canceledWindows.empty() ? "[]" : "]";
6021 ALOGI("Channel %s is stealing touch from %s", requestingChannel->getName().c_str(),
6022 canceledWindows.c_str());
6023
Prabir Pradhane680f9b2022-02-04 04:24:00 -08006024 // Prevent the gesture from being sent to any other windows.
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00006025 // This only blocks relevant pointers to be sent to other windows
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08006026 window.pilferedPointerIds |= window.pointerIds;
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00006027
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07006028 state.cancelPointersForWindowsExcept(window.pointerIds, token);
Michael Wright3dd60e22019-03-27 22:06:44 +00006029 return OK;
6030}
6031
Prabir Pradhan99987712020-11-10 18:43:05 -08006032void InputDispatcher::requestPointerCapture(const sp<IBinder>& windowToken, bool enabled) {
6033 { // acquire lock
6034 std::scoped_lock _l(mLock);
6035 if (DEBUG_FOCUS) {
chaviw98318de2021-05-19 16:45:23 -05006036 const sp<WindowInfoHandle> windowHandle = getWindowHandleLocked(windowToken);
Prabir Pradhan99987712020-11-10 18:43:05 -08006037 ALOGI("Request to %s Pointer Capture from: %s.", enabled ? "enable" : "disable",
6038 windowHandle != nullptr ? windowHandle->getName().c_str()
6039 : "token without window");
6040 }
6041
Vishnu Nairc519ff72021-01-21 08:23:08 -08006042 const sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Prabir Pradhan99987712020-11-10 18:43:05 -08006043 if (focusedToken != windowToken) {
6044 ALOGW("Ignoring request to %s Pointer Capture: window does not have focus.",
6045 enabled ? "enable" : "disable");
6046 return;
6047 }
6048
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006049 if (enabled == mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006050 ALOGW("Ignoring request to %s Pointer Capture: "
6051 "window has %s requested pointer capture.",
6052 enabled ? "enable" : "disable", enabled ? "already" : "not");
6053 return;
6054 }
6055
Christine Franksb768bb42021-11-29 12:11:31 -08006056 if (enabled) {
6057 if (std::find(mIneligibleDisplaysForPointerCapture.begin(),
6058 mIneligibleDisplaysForPointerCapture.end(),
6059 mFocusedDisplayId) != mIneligibleDisplaysForPointerCapture.end()) {
6060 ALOGW("Ignoring request to enable Pointer Capture: display is not eligible");
6061 return;
6062 }
6063 }
6064
Prabir Pradhan99987712020-11-10 18:43:05 -08006065 setPointerCaptureLocked(enabled);
6066 } // release lock
6067
6068 // Wake the thread to process command entries.
6069 mLooper->wake();
6070}
6071
Christine Franksb768bb42021-11-29 12:11:31 -08006072void InputDispatcher::setDisplayEligibilityForPointerCapture(int32_t displayId, bool isEligible) {
6073 { // acquire lock
6074 std::scoped_lock _l(mLock);
6075 std::erase(mIneligibleDisplaysForPointerCapture, displayId);
6076 if (!isEligible) {
6077 mIneligibleDisplaysForPointerCapture.push_back(displayId);
6078 }
6079 } // release lock
6080}
6081
Prabir Pradhane59c6dc2023-06-13 19:53:03 +00006082std::optional<gui::Pid> InputDispatcher::findMonitorPidByTokenLocked(const sp<IBinder>& token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006083 for (const auto& [_, monitors] : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00006084 for (const Monitor& monitor : monitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07006085 if (monitor.inputChannel->getConnectionToken() == token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006086 return monitor.pid;
Michael Wright3dd60e22019-03-27 22:06:44 +00006087 }
6088 }
6089 }
6090 return std::nullopt;
6091}
6092
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006093std::shared_ptr<Connection> InputDispatcher::getConnectionLocked(
6094 const sp<IBinder>& inputConnectionToken) const {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07006095 if (inputConnectionToken == nullptr) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07006096 return nullptr;
Arthur Hung3b413f22018-10-26 18:05:34 +08006097 }
6098
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00006099 for (const auto& [token, connection] : mConnectionsByToken) {
6100 if (token == inputConnectionToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07006101 return connection;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006102 }
6103 }
Robert Carr4e670e52018-08-15 13:26:12 -07006104
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07006105 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006106}
6107
Siarhei Vishniakouad991402020-10-28 11:40:09 -05006108std::string InputDispatcher::getConnectionNameLocked(const sp<IBinder>& connectionToken) const {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006109 std::shared_ptr<Connection> connection = getConnectionLocked(connectionToken);
Siarhei Vishniakouad991402020-10-28 11:40:09 -05006110 if (connection == nullptr) {
6111 return "<nullptr>";
6112 }
6113 return connection->getInputChannelName();
6114}
6115
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006116void InputDispatcher::removeConnectionLocked(const std::shared_ptr<Connection>& connection) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006117 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00006118 mConnectionsByToken.erase(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07006119}
6120
Prabir Pradhancef936d2021-07-21 16:17:52 +00006121void InputDispatcher::doDispatchCycleFinishedCommand(nsecs_t finishTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006122 const std::shared_ptr<Connection>& connection,
6123 uint32_t seq, bool handled,
6124 nsecs_t consumeTime) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006125 // Handle post-event policy actions.
6126 std::deque<DispatchEntry*>::iterator dispatchEntryIt = connection->findWaitQueueEntry(seq);
6127 if (dispatchEntryIt == connection->waitQueue.end()) {
6128 return;
6129 }
6130 DispatchEntry* dispatchEntry = *dispatchEntryIt;
6131 const nsecs_t eventDuration = finishTime - dispatchEntry->deliveryTime;
6132 if (eventDuration > SLOW_EVENT_PROCESSING_WARNING_TIMEOUT) {
6133 ALOGI("%s spent %" PRId64 "ms processing %s", connection->getWindowName().c_str(),
6134 ns2ms(eventDuration), dispatchEntry->eventEntry->getDescription().c_str());
6135 }
6136 if (shouldReportFinishedEvent(*dispatchEntry, *connection)) {
6137 mLatencyTracker.trackFinishedEvent(dispatchEntry->eventEntry->id,
6138 connection->inputChannel->getConnectionToken(),
6139 dispatchEntry->deliveryTime, consumeTime, finishTime);
6140 }
6141
6142 bool restartEvent;
6143 if (dispatchEntry->eventEntry->type == EventEntry::Type::KEY) {
6144 KeyEntry& keyEntry = static_cast<KeyEntry&>(*(dispatchEntry->eventEntry));
6145 restartEvent =
6146 afterKeyEventLockedInterruptable(connection, dispatchEntry, keyEntry, handled);
6147 } else if (dispatchEntry->eventEntry->type == EventEntry::Type::MOTION) {
6148 MotionEntry& motionEntry = static_cast<MotionEntry&>(*(dispatchEntry->eventEntry));
6149 restartEvent = afterMotionEventLockedInterruptable(connection, dispatchEntry, motionEntry,
6150 handled);
6151 } else {
6152 restartEvent = false;
6153 }
6154
6155 // Dequeue the event and start the next cycle.
6156 // Because the lock might have been released, it is possible that the
6157 // contents of the wait queue to have been drained, so we need to double-check
6158 // a few things.
6159 dispatchEntryIt = connection->findWaitQueueEntry(seq);
6160 if (dispatchEntryIt != connection->waitQueue.end()) {
6161 dispatchEntry = *dispatchEntryIt;
6162 connection->waitQueue.erase(dispatchEntryIt);
6163 const sp<IBinder>& connectionToken = connection->inputChannel->getConnectionToken();
6164 mAnrTracker.erase(dispatchEntry->timeoutTime, connectionToken);
6165 if (!connection->responsive) {
6166 connection->responsive = isConnectionResponsive(*connection);
6167 if (connection->responsive) {
6168 // The connection was unresponsive, and now it's responsive.
6169 processConnectionResponsiveLocked(*connection);
6170 }
6171 }
6172 traceWaitQueueLength(*connection);
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08006173 if (restartEvent && connection->status == Connection::Status::NORMAL) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006174 connection->outboundQueue.push_front(dispatchEntry);
6175 traceOutboundQueueLength(*connection);
6176 } else {
6177 releaseDispatchEntry(dispatchEntry);
6178 }
6179 }
6180
6181 // Start the next dispatch cycle for this connection.
6182 startDispatchCycleLocked(now(), connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006183}
6184
Prabir Pradhancef936d2021-07-21 16:17:52 +00006185void InputDispatcher::sendFocusChangedCommandLocked(const sp<IBinder>& oldToken,
6186 const sp<IBinder>& newToken) {
6187 auto command = [this, oldToken, newToken]() REQUIRES(mLock) {
6188 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00006189 mPolicy.notifyFocusChanged(oldToken, newToken);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006190 };
6191 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08006192}
6193
Prabir Pradhancef936d2021-07-21 16:17:52 +00006194void InputDispatcher::sendDropWindowCommandLocked(const sp<IBinder>& token, float x, float y) {
6195 auto command = [this, token, x, y]() REQUIRES(mLock) {
6196 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00006197 mPolicy.notifyDropWindow(token, x, y);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006198 };
6199 postCommandLocked(std::move(command));
Robert Carrf759f162018-11-13 12:57:11 -08006200}
6201
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006202void InputDispatcher::onAnrLocked(const std::shared_ptr<Connection>& connection) {
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006203 if (connection == nullptr) {
6204 LOG_ALWAYS_FATAL("Caller must check for nullness");
6205 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006206 // Since we are allowing the policy to extend the timeout, maybe the waitQueue
6207 // is already healthy again. Don't raise ANR in this situation
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006208 if (connection->waitQueue.empty()) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006209 ALOGI("Not raising ANR because the connection %s has recovered",
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006210 connection->inputChannel->getName().c_str());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006211 return;
6212 }
6213 /**
6214 * The "oldestEntry" is the entry that was first sent to the application. That entry, however,
6215 * may not be the one that caused the timeout to occur. One possibility is that window timeout
6216 * has changed. This could cause newer entries to time out before the already dispatched
6217 * entries. In that situation, the newest entries caused ANR. But in all likelihood, the app
6218 * processes the events linearly. So providing information about the oldest entry seems to be
6219 * most useful.
6220 */
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006221 DispatchEntry* oldestEntry = *connection->waitQueue.begin();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006222 const nsecs_t currentWait = now() - oldestEntry->deliveryTime;
6223 std::string reason =
6224 android::base::StringPrintf("%s is not responding. Waited %" PRId64 "ms for %s",
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006225 connection->inputChannel->getName().c_str(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006226 ns2ms(currentWait),
6227 oldestEntry->eventEntry->getDescription().c_str());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006228 sp<IBinder> connectionToken = connection->inputChannel->getConnectionToken();
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -06006229 updateLastAnrStateLocked(getWindowHandleLocked(connectionToken), reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006230
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006231 processConnectionUnresponsiveLocked(*connection, std::move(reason));
6232
6233 // Stop waking up for events on this connection, it is already unresponsive
6234 cancelEventsForAnrLocked(connection);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006235}
6236
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05006237void InputDispatcher::onAnrLocked(std::shared_ptr<InputApplicationHandle> application) {
6238 std::string reason =
6239 StringPrintf("%s does not have a focused window", application->getName().c_str());
6240 updateLastAnrStateLocked(*application, reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006241
Prabir Pradhancef936d2021-07-21 16:17:52 +00006242 auto command = [this, application = std::move(application)]() REQUIRES(mLock) {
6243 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00006244 mPolicy.notifyNoFocusedWindowAnr(application);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006245 };
6246 postCommandLocked(std::move(command));
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00006247}
6248
chaviw98318de2021-05-19 16:45:23 -05006249void InputDispatcher::updateLastAnrStateLocked(const sp<WindowInfoHandle>& window,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006250 const std::string& reason) {
6251 const std::string windowLabel = getApplicationWindowLabel(nullptr, window);
6252 updateLastAnrStateLocked(windowLabel, reason);
6253}
6254
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05006255void InputDispatcher::updateLastAnrStateLocked(const InputApplicationHandle& application,
6256 const std::string& reason) {
6257 const std::string windowLabel = getApplicationWindowLabel(&application, nullptr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006258 updateLastAnrStateLocked(windowLabel, reason);
6259}
6260
6261void InputDispatcher::updateLastAnrStateLocked(const std::string& windowLabel,
6262 const std::string& reason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006263 // Capture a record of the InputDispatcher state at the time of the ANR.
Yi Kong9b14ac62018-07-17 13:48:38 -07006264 time_t t = time(nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006265 struct tm tm;
6266 localtime_r(&t, &tm);
6267 char timestr[64];
6268 strftime(timestr, sizeof(timestr), "%F %T", &tm);
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006269 mLastAnrState.clear();
6270 mLastAnrState += INDENT "ANR:\n";
6271 mLastAnrState += StringPrintf(INDENT2 "Time: %s\n", timestr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006272 mLastAnrState += StringPrintf(INDENT2 "Reason: %s\n", reason.c_str());
6273 mLastAnrState += StringPrintf(INDENT2 "Window: %s\n", windowLabel.c_str());
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006274 dumpDispatchStateLocked(mLastAnrState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006275}
6276
Prabir Pradhancef936d2021-07-21 16:17:52 +00006277void InputDispatcher::doInterceptKeyBeforeDispatchingCommand(const sp<IBinder>& focusedWindowToken,
6278 KeyEntry& entry) {
6279 const KeyEvent event = createKeyEvent(entry);
6280 nsecs_t delay = 0;
6281 { // release lock
6282 scoped_unlock unlock(mLock);
6283 android::base::Timer t;
Prabir Pradhana41d2442023-04-20 21:30:40 +00006284 delay = mPolicy.interceptKeyBeforeDispatching(focusedWindowToken, event, entry.policyFlags);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006285 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
6286 ALOGW("Excessive delay in interceptKeyBeforeDispatching; took %s ms",
6287 std::to_string(t.duration().count()).c_str());
6288 }
6289 } // acquire lock
Michael Wrightd02c5b62014-02-10 15:10:22 -08006290
6291 if (delay < 0) {
Michael Wright5caf55a2022-11-24 22:31:42 +00006292 entry.interceptKeyResult = KeyEntry::InterceptKeyResult::SKIP;
Prabir Pradhancef936d2021-07-21 16:17:52 +00006293 } else if (delay == 0) {
Michael Wright5caf55a2022-11-24 22:31:42 +00006294 entry.interceptKeyResult = KeyEntry::InterceptKeyResult::CONTINUE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006295 } else {
Michael Wright5caf55a2022-11-24 22:31:42 +00006296 entry.interceptKeyResult = KeyEntry::InterceptKeyResult::TRY_AGAIN_LATER;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006297 entry.interceptKeyWakeupTime = now() + delay;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006298 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006299}
6300
Prabir Pradhancef936d2021-07-21 16:17:52 +00006301void InputDispatcher::sendWindowUnresponsiveCommandLocked(const sp<IBinder>& token,
Prabir Pradhane59c6dc2023-06-13 19:53:03 +00006302 std::optional<gui::Pid> pid,
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006303 std::string reason) {
Prabir Pradhanedd96402022-02-15 01:46:16 -08006304 auto command = [this, token, pid, reason = std::move(reason)]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006305 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00006306 mPolicy.notifyWindowUnresponsive(token, pid, reason);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006307 };
6308 postCommandLocked(std::move(command));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006309}
6310
Prabir Pradhanedd96402022-02-15 01:46:16 -08006311void InputDispatcher::sendWindowResponsiveCommandLocked(const sp<IBinder>& token,
Prabir Pradhane59c6dc2023-06-13 19:53:03 +00006312 std::optional<gui::Pid> pid) {
Prabir Pradhanedd96402022-02-15 01:46:16 -08006313 auto command = [this, token, pid]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006314 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00006315 mPolicy.notifyWindowResponsive(token, pid);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006316 };
6317 postCommandLocked(std::move(command));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006318}
6319
6320/**
6321 * Tell the policy that a connection has become unresponsive so that it can start ANR.
6322 * Check whether the connection of interest is a monitor or a window, and add the corresponding
6323 * command entry to the command queue.
6324 */
6325void InputDispatcher::processConnectionUnresponsiveLocked(const Connection& connection,
6326 std::string reason) {
6327 const sp<IBinder>& connectionToken = connection.inputChannel->getConnectionToken();
Prabir Pradhane59c6dc2023-06-13 19:53:03 +00006328 std::optional<gui::Pid> pid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006329 if (connection.monitor) {
6330 ALOGW("Monitor %s is unresponsive: %s", connection.inputChannel->getName().c_str(),
6331 reason.c_str());
Prabir Pradhanedd96402022-02-15 01:46:16 -08006332 pid = findMonitorPidByTokenLocked(connectionToken);
6333 } else {
6334 // The connection is a window
6335 ALOGW("Window %s is unresponsive: %s", connection.inputChannel->getName().c_str(),
6336 reason.c_str());
6337 const sp<WindowInfoHandle> handle = getWindowHandleLocked(connectionToken);
6338 if (handle != nullptr) {
6339 pid = handle->getInfo()->ownerPid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006340 }
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006341 }
Prabir Pradhanedd96402022-02-15 01:46:16 -08006342 sendWindowUnresponsiveCommandLocked(connectionToken, pid, std::move(reason));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006343}
6344
6345/**
6346 * Tell the policy that a connection has become responsive so that it can stop ANR.
6347 */
6348void InputDispatcher::processConnectionResponsiveLocked(const Connection& connection) {
6349 const sp<IBinder>& connectionToken = connection.inputChannel->getConnectionToken();
Prabir Pradhane59c6dc2023-06-13 19:53:03 +00006350 std::optional<gui::Pid> pid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006351 if (connection.monitor) {
Prabir Pradhanedd96402022-02-15 01:46:16 -08006352 pid = findMonitorPidByTokenLocked(connectionToken);
6353 } else {
6354 // The connection is a window
6355 const sp<WindowInfoHandle> handle = getWindowHandleLocked(connectionToken);
6356 if (handle != nullptr) {
6357 pid = handle->getInfo()->ownerPid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006358 }
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006359 }
Prabir Pradhanedd96402022-02-15 01:46:16 -08006360 sendWindowResponsiveCommandLocked(connectionToken, pid);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006361}
6362
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006363bool InputDispatcher::afterKeyEventLockedInterruptable(
6364 const std::shared_ptr<Connection>& connection, DispatchEntry* dispatchEntry,
6365 KeyEntry& keyEntry, bool handled) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006366 if (keyEntry.flags & AKEY_EVENT_FLAG_FALLBACK) {
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006367 if (!handled) {
6368 // Report the key as unhandled, since the fallback was not handled.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006369 mReporter->reportUnhandledKey(keyEntry.id);
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006370 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006371 return false;
6372 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006373
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006374 // Get the fallback key state.
6375 // Clear it out after dispatching the UP.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006376 int32_t originalKeyCode = keyEntry.keyCode;
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006377 std::optional<int32_t> fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006378 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006379 connection->inputState.removeFallbackKey(originalKeyCode);
6380 }
6381
6382 if (handled || !dispatchEntry->hasForegroundTarget()) {
6383 // If the application handles the original key for which we previously
6384 // generated a fallback or if the window is not a foreground window,
6385 // then cancel the associated fallback key, if any.
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006386 if (fallbackKeyCode) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006387 // Dispatch the unhandled key to the policy with the cancel flag.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006388 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6389 ALOGD("Unhandled key event: Asking policy to cancel fallback action. "
6390 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6391 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount,
6392 keyEntry.policyFlags);
6393 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006394 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006395 event.setFlags(event.getFlags() | AKEY_EVENT_FLAG_CANCELED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006396
6397 mLock.unlock();
6398
Prabir Pradhana41d2442023-04-20 21:30:40 +00006399 if (const auto unhandledKeyFallback =
6400 mPolicy.dispatchUnhandledKey(connection->inputChannel->getConnectionToken(),
6401 event, keyEntry.policyFlags);
6402 unhandledKeyFallback) {
6403 event = *unhandledKeyFallback;
6404 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006405
6406 mLock.lock();
6407
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006408 // Cancel the fallback key.
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006409 if (*fallbackKeyCode != AKEYCODE_UNKNOWN) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00006410 CancelationOptions options(CancelationOptions::Mode::CANCEL_FALLBACK_EVENTS,
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006411 "application handled the original non-fallback key "
6412 "or is no longer a foreground target, "
6413 "canceling previously dispatched fallback key");
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006414 options.keyCode = *fallbackKeyCode;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006415 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006416 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006417 connection->inputState.removeFallbackKey(originalKeyCode);
6418 }
6419 } else {
6420 // If the application did not handle a non-fallback key, first check
6421 // that we are in a good state to perform unhandled key event processing
6422 // Then ask the policy what to do with it.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006423 bool initialDown = keyEntry.action == AKEY_EVENT_ACTION_DOWN && keyEntry.repeatCount == 0;
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006424 if (!fallbackKeyCode && !initialDown) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006425 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6426 ALOGD("Unhandled key event: Skipping unhandled key event processing "
6427 "since this is not an initial down. "
6428 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6429 originalKeyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
6430 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006431 return false;
6432 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006433
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006434 // Dispatch the unhandled key to the policy.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006435 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6436 ALOGD("Unhandled key event: Asking policy to perform fallback action. "
6437 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6438 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
6439 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006440 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006441
6442 mLock.unlock();
6443
Prabir Pradhana41d2442023-04-20 21:30:40 +00006444 bool fallback = false;
6445 if (auto fb = mPolicy.dispatchUnhandledKey(connection->inputChannel->getConnectionToken(),
6446 event, keyEntry.policyFlags);
6447 fb) {
6448 fallback = true;
6449 event = *fb;
6450 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006451
6452 mLock.lock();
6453
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08006454 if (connection->status != Connection::Status::NORMAL) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006455 connection->inputState.removeFallbackKey(originalKeyCode);
6456 return false;
6457 }
6458
6459 // Latch the fallback keycode for this key on an initial down.
6460 // The fallback keycode cannot change at any other point in the lifecycle.
6461 if (initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006462 if (fallback) {
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006463 *fallbackKeyCode = event.getKeyCode();
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006464 } else {
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006465 *fallbackKeyCode = AKEYCODE_UNKNOWN;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006466 }
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006467 connection->inputState.setFallbackKey(originalKeyCode, *fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006468 }
6469
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006470 ALOG_ASSERT(fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006471
6472 // Cancel the fallback key if the policy decides not to send it anymore.
6473 // We will continue to dispatch the key to the policy but we will no
6474 // longer dispatch a fallback key to the application.
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006475 if (*fallbackKeyCode != AKEYCODE_UNKNOWN &&
6476 (!fallback || *fallbackKeyCode != event.getKeyCode())) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006477 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6478 if (fallback) {
6479 ALOGD("Unhandled key event: Policy requested to send key %d"
6480 "as a fallback for %d, but on the DOWN it had requested "
6481 "to send %d instead. Fallback canceled.",
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006482 event.getKeyCode(), originalKeyCode, *fallbackKeyCode);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006483 } else {
6484 ALOGD("Unhandled key event: Policy did not request fallback for %d, "
6485 "but on the DOWN it had requested to send %d. "
6486 "Fallback canceled.",
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006487 originalKeyCode, *fallbackKeyCode);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006488 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006489 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006490
Michael Wrightfb04fd52022-11-24 22:31:11 +00006491 CancelationOptions options(CancelationOptions::Mode::CANCEL_FALLBACK_EVENTS,
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006492 "canceling fallback, policy no longer desires it");
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006493 options.keyCode = *fallbackKeyCode;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006494 synthesizeCancelationEventsForConnectionLocked(connection, options);
6495
6496 fallback = false;
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006497 *fallbackKeyCode = AKEYCODE_UNKNOWN;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006498 if (keyEntry.action != AKEY_EVENT_ACTION_UP) {
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006499 connection->inputState.setFallbackKey(originalKeyCode, *fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006500 }
6501 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006502
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006503 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6504 {
6505 std::string msg;
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006506 const std::map<int32_t, int32_t>& fallbackKeys =
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006507 connection->inputState.getFallbackKeys();
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006508 for (const auto& [key, value] : fallbackKeys) {
6509 msg += StringPrintf(", %d->%d", key, value);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006510 }
6511 ALOGD("Unhandled key event: %zu currently tracked fallback keys%s.",
6512 fallbackKeys.size(), msg.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006513 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006514 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006515
6516 if (fallback) {
6517 // Restart the dispatch cycle using the fallback key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006518 keyEntry.eventTime = event.getEventTime();
6519 keyEntry.deviceId = event.getDeviceId();
6520 keyEntry.source = event.getSource();
6521 keyEntry.displayId = event.getDisplayId();
6522 keyEntry.flags = event.getFlags() | AKEY_EVENT_FLAG_FALLBACK;
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006523 keyEntry.keyCode = *fallbackKeyCode;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006524 keyEntry.scanCode = event.getScanCode();
6525 keyEntry.metaState = event.getMetaState();
6526 keyEntry.repeatCount = event.getRepeatCount();
6527 keyEntry.downTime = event.getDownTime();
6528 keyEntry.syntheticRepeat = false;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006529
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006530 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6531 ALOGD("Unhandled key event: Dispatching fallback key. "
6532 "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006533 originalKeyCode, *fallbackKeyCode, keyEntry.metaState);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006534 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006535 return true; // restart the event
6536 } else {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006537 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6538 ALOGD("Unhandled key event: No fallback key.");
6539 }
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006540
6541 // Report the key as unhandled, since there is no fallback key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006542 mReporter->reportUnhandledKey(keyEntry.id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006543 }
6544 }
6545 return false;
6546}
6547
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006548bool InputDispatcher::afterMotionEventLockedInterruptable(
6549 const std::shared_ptr<Connection>& connection, DispatchEntry* dispatchEntry,
6550 MotionEntry& motionEntry, bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006551 return false;
6552}
6553
Michael Wrightd02c5b62014-02-10 15:10:22 -08006554void InputDispatcher::traceInboundQueueLengthLocked() {
6555 if (ATRACE_ENABLED()) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07006556 ATRACE_INT("iq", mInboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006557 }
6558}
6559
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006560void InputDispatcher::traceOutboundQueueLength(const Connection& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006561 if (ATRACE_ENABLED()) {
6562 char counterName[40];
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006563 snprintf(counterName, sizeof(counterName), "oq:%s", connection.getWindowName().c_str());
6564 ATRACE_INT(counterName, connection.outboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006565 }
6566}
6567
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006568void InputDispatcher::traceWaitQueueLength(const Connection& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006569 if (ATRACE_ENABLED()) {
6570 char counterName[40];
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006571 snprintf(counterName, sizeof(counterName), "wq:%s", connection.getWindowName().c_str());
6572 ATRACE_INT(counterName, connection.waitQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006573 }
6574}
6575
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006576void InputDispatcher::dump(std::string& dump) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006577 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006578
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006579 dump += "Input Dispatcher State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08006580 dumpDispatchStateLocked(dump);
6581
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006582 if (!mLastAnrState.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006583 dump += "\nInput Dispatcher State at time of last ANR:\n";
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006584 dump += mLastAnrState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006585 }
6586}
6587
6588void InputDispatcher::monitor() {
6589 // Acquire and release the lock to ensure that the dispatcher has not deadlocked.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006590 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006591 mLooper->wake();
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006592 mDispatcherIsAlive.wait(_l);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006593}
6594
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08006595/**
6596 * Wake up the dispatcher and wait until it processes all events and commands.
6597 * The notification of mDispatcherEnteredIdle is guaranteed to happen after wake(), so
6598 * this method can be safely called from any thread, as long as you've ensured that
6599 * the work you are interested in completing has already been queued.
6600 */
6601bool InputDispatcher::waitForIdle() {
6602 /**
6603 * Timeout should represent the longest possible time that a device might spend processing
6604 * events and commands.
6605 */
6606 constexpr std::chrono::duration TIMEOUT = 100ms;
6607 std::unique_lock lock(mLock);
6608 mLooper->wake();
6609 std::cv_status result = mDispatcherEnteredIdle.wait_for(lock, TIMEOUT);
6610 return result == std::cv_status::no_timeout;
6611}
6612
Vishnu Naire798b472020-07-23 13:52:21 -07006613/**
6614 * Sets focus to the window identified by the token. This must be called
6615 * after updating any input window handles.
6616 *
6617 * Params:
6618 * request.token - input channel token used to identify the window that should gain focus.
6619 * request.focusedToken - the token that the caller expects currently to be focused. If the
6620 * specified token does not match the currently focused window, this request will be dropped.
6621 * If the specified focused token matches the currently focused window, the call will succeed.
6622 * Set this to "null" if this call should succeed no matter what the currently focused token is.
6623 * request.timestamp - SYSTEM_TIME_MONOTONIC timestamp in nanos set by the client (wm)
6624 * when requesting the focus change. This determines which request gets
6625 * precedence if there is a focus change request from another source such as pointer down.
6626 */
Vishnu Nair958da932020-08-21 17:12:37 -07006627void InputDispatcher::setFocusedWindow(const FocusRequest& request) {
6628 { // acquire lock
6629 std::scoped_lock _l(mLock);
Vishnu Nairc519ff72021-01-21 08:23:08 -08006630 std::optional<FocusResolver::FocusChanges> changes =
6631 mFocusResolver.setFocusedWindow(request, getWindowHandlesLocked(request.displayId));
6632 if (changes) {
6633 onFocusChangedLocked(*changes);
Vishnu Nair958da932020-08-21 17:12:37 -07006634 }
6635 } // release lock
6636 // Wake up poll loop since it may need to make new input dispatching choices.
6637 mLooper->wake();
6638}
6639
Vishnu Nairc519ff72021-01-21 08:23:08 -08006640void InputDispatcher::onFocusChangedLocked(const FocusResolver::FocusChanges& changes) {
6641 if (changes.oldFocus) {
6642 std::shared_ptr<InputChannel> focusedInputChannel = getInputChannelLocked(changes.oldFocus);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006643 if (focusedInputChannel) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00006644 CancelationOptions options(CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS,
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006645 "focus left window");
6646 synthesizeCancelationEventsForInputChannelLocked(focusedInputChannel, options);
Harry Cutts33476232023-01-30 19:57:29 +00006647 enqueueFocusEventLocked(changes.oldFocus, /*hasFocus=*/false, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006648 }
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006649 }
Vishnu Nairc519ff72021-01-21 08:23:08 -08006650 if (changes.newFocus) {
Harry Cutts33476232023-01-30 19:57:29 +00006651 enqueueFocusEventLocked(changes.newFocus, /*hasFocus=*/true, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006652 }
6653
Prabir Pradhan99987712020-11-10 18:43:05 -08006654 // If a window has pointer capture, then it must have focus. We need to ensure that this
6655 // contract is upheld when pointer capture is being disabled due to a loss of window focus.
6656 // If the window loses focus before it loses pointer capture, then the window can be in a state
6657 // where it has pointer capture but not focus, violating the contract. Therefore we must
6658 // dispatch the pointer capture event before the focus event. Since focus events are added to
6659 // the front of the queue (above), we add the pointer capture event to the front of the queue
6660 // after the focus events are added. This ensures the pointer capture event ends up at the
6661 // front.
6662 disablePointerCaptureForcedLocked();
6663
Vishnu Nairc519ff72021-01-21 08:23:08 -08006664 if (mFocusedDisplayId == changes.displayId) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006665 sendFocusChangedCommandLocked(changes.oldFocus, changes.newFocus);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006666 }
6667}
Vishnu Nair958da932020-08-21 17:12:37 -07006668
Prabir Pradhan99987712020-11-10 18:43:05 -08006669void InputDispatcher::disablePointerCaptureForcedLocked() {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006670 if (!mCurrentPointerCaptureRequest.enable && !mWindowTokenWithPointerCapture) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006671 return;
6672 }
6673
6674 ALOGD_IF(DEBUG_FOCUS, "Disabling Pointer Capture because the window lost focus.");
6675
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006676 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006677 setPointerCaptureLocked(false);
6678 }
6679
6680 if (!mWindowTokenWithPointerCapture) {
6681 // No need to send capture changes because no window has capture.
6682 return;
6683 }
6684
6685 if (mPendingEvent != nullptr) {
6686 // Move the pending event to the front of the queue. This will give the chance
6687 // for the pending event to be dropped if it is a captured event.
6688 mInboundQueue.push_front(mPendingEvent);
6689 mPendingEvent = nullptr;
6690 }
6691
6692 auto entry = std::make_unique<PointerCaptureChangedEntry>(mIdGenerator.nextId(), now(),
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006693 mCurrentPointerCaptureRequest);
Prabir Pradhan99987712020-11-10 18:43:05 -08006694 mInboundQueue.push_front(std::move(entry));
6695}
6696
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006697void InputDispatcher::setPointerCaptureLocked(bool enable) {
6698 mCurrentPointerCaptureRequest.enable = enable;
6699 mCurrentPointerCaptureRequest.seq++;
6700 auto command = [this, request = mCurrentPointerCaptureRequest]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006701 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00006702 mPolicy.setPointerCapture(request);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006703 };
6704 postCommandLocked(std::move(command));
Prabir Pradhan99987712020-11-10 18:43:05 -08006705}
6706
Vishnu Nair599f1412021-06-21 10:39:58 -07006707void InputDispatcher::displayRemoved(int32_t displayId) {
6708 { // acquire lock
6709 std::scoped_lock _l(mLock);
6710 // Set an empty list to remove all handles from the specific display.
6711 setInputWindowsLocked(/* window handles */ {}, displayId);
6712 setFocusedApplicationLocked(displayId, nullptr);
6713 // Call focus resolver to clean up stale requests. This must be called after input windows
6714 // have been removed for the removed display.
6715 mFocusResolver.displayRemoved(displayId);
Christine Franksb768bb42021-11-29 12:11:31 -08006716 // Reset pointer capture eligibility, regardless of previous state.
6717 std::erase(mIneligibleDisplaysForPointerCapture, displayId);
Antonio Kantek15beb512022-06-13 22:35:41 +00006718 // Remove the associated touch mode state.
6719 mTouchModePerDisplay.erase(displayId);
Siarhei Vishniakou5c02a712023-05-15 15:45:02 -07006720 mVerifiersByDisplay.erase(displayId);
Vishnu Nair599f1412021-06-21 10:39:58 -07006721 } // release lock
6722
6723 // Wake up poll loop since it may need to make new input dispatching choices.
6724 mLooper->wake();
6725}
6726
Patrick Williamsd828f302023-04-28 17:52:08 -05006727void InputDispatcher::onWindowInfosChanged(const gui::WindowInfosUpdate& update) {
chaviw15fab6f2021-06-07 14:15:52 -05006728 // The listener sends the windows as a flattened array. Separate the windows by display for
6729 // more convenient parsing.
6730 std::unordered_map<int32_t, std::vector<sp<WindowInfoHandle>>> handlesPerDisplay;
Patrick Williamsd828f302023-04-28 17:52:08 -05006731 for (const auto& info : update.windowInfos) {
chaviw15fab6f2021-06-07 14:15:52 -05006732 handlesPerDisplay.emplace(info.displayId, std::vector<sp<WindowInfoHandle>>());
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07006733 handlesPerDisplay[info.displayId].push_back(sp<WindowInfoHandle>::make(info));
chaviw15fab6f2021-06-07 14:15:52 -05006734 }
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006735
6736 { // acquire lock
6737 std::scoped_lock _l(mLock);
Prabir Pradhan814fe082022-07-22 20:22:18 +00006738
6739 // Ensure that we have an entry created for all existing displays so that if a displayId has
6740 // no windows, we can tell that the windows were removed from the display.
6741 for (const auto& [displayId, _] : mWindowHandlesByDisplay) {
6742 handlesPerDisplay[displayId];
6743 }
6744
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006745 mDisplayInfos.clear();
Patrick Williamsd828f302023-04-28 17:52:08 -05006746 for (const auto& displayInfo : update.displayInfos) {
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006747 mDisplayInfos.emplace(displayInfo.displayId, displayInfo);
6748 }
6749
6750 for (const auto& [displayId, handles] : handlesPerDisplay) {
6751 setInputWindowsLocked(handles, displayId);
6752 }
Patrick Williams9464b2c2023-05-23 11:22:04 -05006753
6754 if (update.vsyncId < mWindowInfosVsyncId) {
6755 ALOGE("Received out of order window infos update. Last update vsync id: %" PRId64
6756 ", current update vsync id: %" PRId64,
6757 mWindowInfosVsyncId, update.vsyncId);
6758 }
6759 mWindowInfosVsyncId = update.vsyncId;
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006760 }
6761 // Wake up poll loop since it may need to make new input dispatching choices.
6762 mLooper->wake();
chaviw15fab6f2021-06-07 14:15:52 -05006763}
6764
Vishnu Nair062a8672021-09-03 16:07:44 -07006765bool InputDispatcher::shouldDropInput(
6766 const EventEntry& entry, const sp<android::gui::WindowInfoHandle>& windowHandle) const {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006767 if (windowHandle->getInfo()->inputConfig.test(WindowInfo::InputConfig::DROP_INPUT) ||
6768 (windowHandle->getInfo()->inputConfig.test(
6769 WindowInfo::InputConfig::DROP_INPUT_IF_OBSCURED) &&
Vishnu Nair062a8672021-09-03 16:07:44 -07006770 isWindowObscuredLocked(windowHandle))) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006771 ALOGW("Dropping %s event targeting %s as requested by the input configuration {%s} on "
6772 "display %" PRId32 ".",
Vishnu Nair062a8672021-09-03 16:07:44 -07006773 ftl::enum_string(entry.type).c_str(), windowHandle->getName().c_str(),
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006774 windowHandle->getInfo()->inputConfig.string().c_str(),
Vishnu Nair062a8672021-09-03 16:07:44 -07006775 windowHandle->getInfo()->displayId);
6776 return true;
6777 }
6778 return false;
6779}
6780
Siarhei Vishniakou18050092021-09-01 13:32:49 -07006781void InputDispatcher::DispatcherWindowListener::onWindowInfosChanged(
Patrick Williamsd828f302023-04-28 17:52:08 -05006782 const gui::WindowInfosUpdate& update) {
6783 mDispatcher.onWindowInfosChanged(update);
Siarhei Vishniakou18050092021-09-01 13:32:49 -07006784}
6785
Arthur Hungdfd528e2021-12-08 13:23:04 +00006786void InputDispatcher::cancelCurrentTouch() {
6787 {
6788 std::scoped_lock _l(mLock);
6789 ALOGD("Canceling all ongoing pointer gestures on all displays.");
Michael Wrightfb04fd52022-11-24 22:31:11 +00006790 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
Arthur Hungdfd528e2021-12-08 13:23:04 +00006791 "cancel current touch");
6792 synthesizeCancelationEventsForAllConnectionsLocked(options);
6793
6794 mTouchStatesByDisplay.clear();
Arthur Hungdfd528e2021-12-08 13:23:04 +00006795 }
6796 // Wake up poll loop since there might be work to do.
6797 mLooper->wake();
6798}
6799
Prabir Pradhan87112a72023-04-20 19:13:39 +00006800void InputDispatcher::requestRefreshConfiguration() {
Prabir Pradhana41d2442023-04-20 21:30:40 +00006801 InputDispatcherConfiguration config = mPolicy.getDispatcherConfiguration();
Prabir Pradhan87112a72023-04-20 19:13:39 +00006802
6803 std::scoped_lock _l(mLock);
6804 mConfig = config;
6805}
6806
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006807void InputDispatcher::setMonitorDispatchingTimeoutForTest(std::chrono::nanoseconds timeout) {
6808 std::scoped_lock _l(mLock);
6809 mMonitorDispatchingTimeout = timeout;
6810}
6811
Arthur Hungc539dbb2022-12-08 07:45:36 +00006812void InputDispatcher::slipWallpaperTouch(ftl::Flags<InputTarget::Flags> targetFlags,
6813 const sp<WindowInfoHandle>& oldWindowHandle,
6814 const sp<WindowInfoHandle>& newWindowHandle,
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08006815 TouchState& state, int32_t pointerId,
Siarhei Vishniakoubf880522023-05-01 11:03:22 -07006816 std::vector<InputTarget>& targets) const {
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08006817 std::bitset<MAX_POINTER_ID + 1> pointerIds;
6818 pointerIds.set(pointerId);
Arthur Hungc539dbb2022-12-08 07:45:36 +00006819 const bool oldHasWallpaper = oldWindowHandle->getInfo()->inputConfig.test(
6820 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
6821 const bool newHasWallpaper = targetFlags.test(InputTarget::Flags::FOREGROUND) &&
6822 newWindowHandle->getInfo()->inputConfig.test(
6823 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
6824 const sp<WindowInfoHandle> oldWallpaper =
6825 oldHasWallpaper ? state.getWallpaperWindow() : nullptr;
6826 const sp<WindowInfoHandle> newWallpaper =
6827 newHasWallpaper ? findWallpaperWindowBelow(newWindowHandle) : nullptr;
6828 if (oldWallpaper == newWallpaper) {
6829 return;
6830 }
6831
6832 if (oldWallpaper != nullptr) {
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08006833 const TouchedWindow& oldTouchedWindow = state.getTouchedWindow(oldWallpaper);
6834 addWindowTargetLocked(oldWallpaper,
6835 oldTouchedWindow.targetFlags |
6836 InputTarget::Flags::DISPATCH_AS_SLIPPERY_EXIT,
6837 pointerIds, oldTouchedWindow.firstDownTimeInTarget, targets);
6838 state.removeTouchedPointerFromWindow(pointerId, oldWallpaper);
Arthur Hungc539dbb2022-12-08 07:45:36 +00006839 }
6840
6841 if (newWallpaper != nullptr) {
6842 state.addOrUpdateWindow(newWallpaper,
6843 InputTarget::Flags::DISPATCH_AS_SLIPPERY_ENTER |
6844 InputTarget::Flags::WINDOW_IS_OBSCURED |
6845 InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED,
6846 pointerIds);
6847 }
6848}
6849
6850void InputDispatcher::transferWallpaperTouch(ftl::Flags<InputTarget::Flags> oldTargetFlags,
6851 ftl::Flags<InputTarget::Flags> newTargetFlags,
6852 const sp<WindowInfoHandle> fromWindowHandle,
6853 const sp<WindowInfoHandle> toWindowHandle,
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08006854 TouchState& state,
6855 std::bitset<MAX_POINTER_ID + 1> pointerIds) {
Arthur Hungc539dbb2022-12-08 07:45:36 +00006856 const bool oldHasWallpaper = oldTargetFlags.test(InputTarget::Flags::FOREGROUND) &&
6857 fromWindowHandle->getInfo()->inputConfig.test(
6858 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
6859 const bool newHasWallpaper = newTargetFlags.test(InputTarget::Flags::FOREGROUND) &&
6860 toWindowHandle->getInfo()->inputConfig.test(
6861 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
6862
6863 const sp<WindowInfoHandle> oldWallpaper =
6864 oldHasWallpaper ? state.getWallpaperWindow() : nullptr;
6865 const sp<WindowInfoHandle> newWallpaper =
6866 newHasWallpaper ? findWallpaperWindowBelow(toWindowHandle) : nullptr;
6867 if (oldWallpaper == newWallpaper) {
6868 return;
6869 }
6870
6871 if (oldWallpaper != nullptr) {
6872 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
6873 "transferring touch focus to another window");
6874 state.removeWindowByToken(oldWallpaper->getToken());
6875 synthesizeCancelationEventsForWindowLocked(oldWallpaper, options);
6876 }
6877
6878 if (newWallpaper != nullptr) {
6879 nsecs_t downTimeInTarget = now();
6880 ftl::Flags<InputTarget::Flags> wallpaperFlags =
6881 oldTargetFlags & (InputTarget::Flags::SPLIT | InputTarget::Flags::DISPATCH_AS_IS);
6882 wallpaperFlags |= InputTarget::Flags::WINDOW_IS_OBSCURED |
6883 InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED;
6884 state.addOrUpdateWindow(newWallpaper, wallpaperFlags, pointerIds, downTimeInTarget);
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006885 std::shared_ptr<Connection> wallpaperConnection =
6886 getConnectionLocked(newWallpaper->getToken());
Arthur Hungc539dbb2022-12-08 07:45:36 +00006887 if (wallpaperConnection != nullptr) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006888 std::shared_ptr<Connection> toConnection =
6889 getConnectionLocked(toWindowHandle->getToken());
Arthur Hungc539dbb2022-12-08 07:45:36 +00006890 toConnection->inputState.mergePointerStateTo(wallpaperConnection->inputState);
6891 synthesizePointerDownEventsForConnectionLocked(downTimeInTarget, wallpaperConnection,
6892 wallpaperFlags);
6893 }
6894 }
6895}
6896
6897sp<WindowInfoHandle> InputDispatcher::findWallpaperWindowBelow(
6898 const sp<WindowInfoHandle>& windowHandle) const {
6899 const std::vector<sp<WindowInfoHandle>>& windowHandles =
6900 getWindowHandlesLocked(windowHandle->getInfo()->displayId);
6901 bool foundWindow = false;
6902 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
6903 if (!foundWindow && otherHandle != windowHandle) {
6904 continue;
6905 }
6906 if (windowHandle == otherHandle) {
6907 foundWindow = true;
6908 continue;
6909 }
6910
6911 if (otherHandle->getInfo()->inputConfig.test(WindowInfo::InputConfig::IS_WALLPAPER)) {
6912 return otherHandle;
6913 }
6914 }
6915 return nullptr;
6916}
6917
Garfield Tane84e6f92019-08-29 17:28:41 -07006918} // namespace android::inputdispatcher