blob: d98641ec1d22c7c509be77f3b68e3cbdc6d31995 [file] [log] [blame]
Michael Wrightd02c5b62014-02-10 15:10:22 -08001/*
2 * Copyright (C) 2010 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#define LOG_TAG "InputDispatcher"
18#define ATRACE_TAG ATRACE_TAG_INPUT
19
John Recke0710582019-09-26 13:46:12 -070020#define LOG_NDEBUG 1
Michael Wrightd02c5b62014-02-10 15:10:22 -080021
Michael Wright2b3c3302018-03-02 17:19:13 +000022#include <android-base/chrono_utils.h>
Siarhei Vishniakoud010b012023-01-18 15:00:53 -080023#include <android-base/logging.h>
Peter Collingbourneb04b9b82021-02-08 12:09:47 -080024#include <android-base/properties.h>
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080025#include <android-base/stringprintf.h>
Siarhei Vishniakou70622952020-07-30 11:17:23 -050026#include <android/os/IInputConstants.h>
Robert Carr4e670e52018-08-15 13:26:12 -070027#include <binder/Binder.h>
Dominik Laskowski75788452021-02-09 18:51:25 -080028#include <ftl/enum.h>
Siarhei Vishniakou5c02a712023-05-15 15:45:02 -070029#include <log/log_event_list.h>
Siarhei Vishniakou31977182022-09-30 08:51:23 -070030#if defined(__ANDROID__)
chaviw15fab6f2021-06-07 14:15:52 -050031#include <gui/SurfaceComposerClient.h>
Siarhei Vishniakou31977182022-09-30 08:51:23 -070032#endif
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -080033#include <input/InputDevice.h>
Siarhei Vishniakou6e1e9872022-11-08 17:51:35 -080034#include <input/PrintTools.h>
Prabir Pradhana37bad12023-08-18 15:55:32 +000035#include <input/TraceTools.h>
tyiu1573a672023-02-21 22:38:32 +000036#include <openssl/mem.h>
Garfield Tan0fc2fa72019-08-29 17:22:15 -070037#include <powermanager/PowerManager.h>
Michael Wright44753b12020-07-08 13:48:11 +010038#include <unistd.h>
Garfield Tan0fc2fa72019-08-29 17:22:15 -070039#include <utils/Trace.h>
Michael Wrightd02c5b62014-02-10 15:10:22 -080040
Michael Wright44753b12020-07-08 13:48:11 +010041#include <cerrno>
42#include <cinttypes>
43#include <climits>
44#include <cstddef>
45#include <ctime>
46#include <queue>
47#include <sstream>
48
49#include "Connection.h"
Arthur Hung1a1007b2022-05-11 07:15:01 +000050#include "DebugConfig.h"
Chris Yef59a2f42020-10-16 12:55:26 -070051#include "InputDispatcher.h"
Michael Wright44753b12020-07-08 13:48:11 +010052
Michael Wrightd02c5b62014-02-10 15:10:22 -080053#define INDENT " "
54#define INDENT2 " "
55#define INDENT3 " "
56#define INDENT4 " "
57
Siarhei Vishniakou253f4642022-11-09 13:42:06 -080058using namespace android::ftl::flag_operators;
Siarhei Vishniakou23740b92023-04-21 11:30:20 -070059using android::base::Error;
Peter Collingbourneb04b9b82021-02-08 12:09:47 -080060using android::base::HwTimeoutMultiplier;
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +000061using android::base::Result;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080062using android::base::StringPrintf;
Prabir Pradhan48f8cb92021-08-26 14:05:36 -070063using android::gui::DisplayInfo;
chaviw98318de2021-05-19 16:45:23 -050064using android::gui::FocusRequest;
65using android::gui::TouchOcclusionMode;
66using android::gui::WindowInfo;
67using android::gui::WindowInfoHandle;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -080068using android::os::InputEventInjectionResult;
69using android::os::InputEventInjectionSync;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080070
Garfield Tane84e6f92019-08-29 17:28:41 -070071namespace android::inputdispatcher {
Michael Wrightd02c5b62014-02-10 15:10:22 -080072
Prabir Pradhancef936d2021-07-21 16:17:52 +000073namespace {
Prabir Pradhancef936d2021-07-21 16:17:52 +000074// Temporarily releases a held mutex for the lifetime of the instance.
75// Named to match std::scoped_lock
76class scoped_unlock {
77public:
78 explicit scoped_unlock(std::mutex& mutex) : mMutex(mutex) { mMutex.unlock(); }
79 ~scoped_unlock() { mMutex.lock(); }
80
81private:
82 std::mutex& mMutex;
83};
84
Michael Wrightd02c5b62014-02-10 15:10:22 -080085// Default input dispatching timeout if there is no focused application or paused window
86// from which to determine an appropriate dispatching timeout.
Peter Collingbourneb04b9b82021-02-08 12:09:47 -080087const std::chrono::duration DEFAULT_INPUT_DISPATCHING_TIMEOUT = std::chrono::milliseconds(
88 android::os::IInputConstants::UNMULTIPLIED_DEFAULT_DISPATCHING_TIMEOUT_MILLIS *
89 HwTimeoutMultiplier());
Michael Wrightd02c5b62014-02-10 15:10:22 -080090
91// Amount of time to allow for all pending events to be processed when an app switch
92// key is on the way. This is used to preempt input dispatch and drop input events
93// when an application takes too long to respond and the user has pressed an app switch key.
Michael Wright2b3c3302018-03-02 17:19:13 +000094constexpr nsecs_t APP_SWITCH_TIMEOUT = 500 * 1000000LL; // 0.5sec
Michael Wrightd02c5b62014-02-10 15:10:22 -080095
Siarhei Vishniakou289e9242022-02-15 14:50:16 -080096const std::chrono::duration STALE_EVENT_TIMEOUT = std::chrono::seconds(10) * HwTimeoutMultiplier();
Michael Wrightd02c5b62014-02-10 15:10:22 -080097
Michael Wrightd02c5b62014-02-10 15:10:22 -080098// Log a warning when an event takes longer than this to process, even if an ANR does not occur.
Michael Wright2b3c3302018-03-02 17:19:13 +000099constexpr nsecs_t SLOW_EVENT_PROCESSING_WARNING_TIMEOUT = 2000 * 1000000LL; // 2sec
100
101// Log a warning when an interception call takes longer than this to process.
102constexpr std::chrono::milliseconds SLOW_INTERCEPTION_THRESHOLD = 50ms;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800103
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700104// Additional key latency in case a connection is still processing some motion events.
105// This will help with the case when a user touched a button that opens a new window,
106// and gives us the chance to dispatch the key to this new window.
107constexpr std::chrono::nanoseconds KEY_WAITING_FOR_EVENTS_TIMEOUT = 500ms;
108
Michael Wrightd02c5b62014-02-10 15:10:22 -0800109// Number of recent events to keep for debugging purposes.
Michael Wright2b3c3302018-03-02 17:19:13 +0000110constexpr size_t RECENT_QUEUE_MAX_SIZE = 10;
111
Antonio Kantekea47acb2021-12-23 12:41:25 -0800112// Event log tags. See EventLogTags.logtags for reference.
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +0000113constexpr int LOGTAG_INPUT_INTERACTION = 62000;
114constexpr int LOGTAG_INPUT_FOCUS = 62001;
Arthur Hungb3307ee2021-10-14 10:57:37 +0000115constexpr int LOGTAG_INPUT_CANCEL = 62003;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +0000116
Prabir Pradhan33e3baa2022-12-06 20:30:22 +0000117const ui::Transform kIdentityTransform;
118
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000119inline nsecs_t now() {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800120 return systemTime(SYSTEM_TIME_MONOTONIC);
121}
122
Siarhei Vishniakoud38a1e02023-07-18 11:55:17 -0700123bool isEmpty(const std::stringstream& ss) {
124 return ss.rdbuf()->in_avail() == 0;
125}
126
Siarhei Vishniakou63b63612023-04-12 11:00:23 -0700127inline const std::string binderToString(const sp<IBinder>& binder) {
Bernardo Rufino49d99e42021-01-18 15:16:59 +0000128 if (binder == nullptr) {
129 return "<null>";
130 }
131 return StringPrintf("%p", binder.get());
132}
133
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +0000134static std::string uidString(const gui::Uid& uid) {
135 return uid.toString();
136}
137
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700138Result<void> checkKeyAction(int32_t action) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800139 switch (action) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700140 case AKEY_EVENT_ACTION_DOWN:
141 case AKEY_EVENT_ACTION_UP:
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700142 return {};
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700143 default:
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700144 return Error() << "Key event has invalid action code " << action;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800145 }
146}
147
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700148Result<void> validateKeyEvent(int32_t action) {
149 return checkKeyAction(action);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800150}
151
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700152Result<void> checkMotionAction(int32_t action, int32_t actionButton, int32_t pointerCount) {
Siarhei Vishniakou2f61bdc2022-12-02 08:55:51 -0800153 switch (MotionEvent::getActionMasked(action)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700154 case AMOTION_EVENT_ACTION_DOWN:
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700155 case AMOTION_EVENT_ACTION_UP: {
156 if (pointerCount != 1) {
157 return Error() << "invalid pointer count " << pointerCount;
158 }
159 return {};
160 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700161 case AMOTION_EVENT_ACTION_MOVE:
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700162 case AMOTION_EVENT_ACTION_HOVER_ENTER:
163 case AMOTION_EVENT_ACTION_HOVER_MOVE:
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700164 case AMOTION_EVENT_ACTION_HOVER_EXIT: {
165 if (pointerCount < 1) {
166 return Error() << "invalid pointer count " << pointerCount;
167 }
168 return {};
169 }
Siarhei Vishniakou2f61bdc2022-12-02 08:55:51 -0800170 case AMOTION_EVENT_ACTION_CANCEL:
171 case AMOTION_EVENT_ACTION_OUTSIDE:
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700172 case AMOTION_EVENT_ACTION_SCROLL:
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700173 return {};
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700174 case AMOTION_EVENT_ACTION_POINTER_DOWN:
175 case AMOTION_EVENT_ACTION_POINTER_UP: {
Siarhei Vishniakou2f61bdc2022-12-02 08:55:51 -0800176 const int32_t index = MotionEvent::getActionIndex(action);
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700177 if (index < 0) {
178 return Error() << "invalid index " << index << " for "
179 << MotionEvent::actionToString(action);
180 }
181 if (index >= pointerCount) {
182 return Error() << "invalid index " << index << " for pointerCount " << pointerCount;
183 }
184 if (pointerCount <= 1) {
185 return Error() << "invalid pointer count " << pointerCount << " for "
186 << MotionEvent::actionToString(action);
187 }
188 return {};
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700189 }
190 case AMOTION_EVENT_ACTION_BUTTON_PRESS:
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700191 case AMOTION_EVENT_ACTION_BUTTON_RELEASE: {
192 if (actionButton == 0) {
193 return Error() << "action button should be nonzero for "
194 << MotionEvent::actionToString(action);
195 }
196 return {};
197 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700198 default:
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700199 return Error() << "invalid action " << action;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800200 }
201}
202
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000203int64_t millis(std::chrono::nanoseconds t) {
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -0500204 return std::chrono::duration_cast<std::chrono::milliseconds>(t).count();
205}
206
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700207Result<void> validateMotionEvent(int32_t action, int32_t actionButton, size_t pointerCount,
208 const PointerProperties* pointerProperties) {
209 Result<void> actionCheck = checkMotionAction(action, actionButton, pointerCount);
210 if (!actionCheck.ok()) {
211 return actionCheck;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800212 }
213 if (pointerCount < 1 || pointerCount > MAX_POINTERS) {
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700214 return Error() << "Motion event has invalid pointer count " << pointerCount
215 << "; value must be between 1 and " << MAX_POINTERS << ".";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800216 }
Siarhei Vishniakou8a878352023-01-30 14:05:01 -0800217 std::bitset<MAX_POINTER_ID + 1> pointerIdBits;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800218 for (size_t i = 0; i < pointerCount; i++) {
219 int32_t id = pointerProperties[i].id;
220 if (id < 0 || id > MAX_POINTER_ID) {
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700221 return Error() << "Motion event has invalid pointer id " << id
222 << "; value must be between 0 and " << MAX_POINTER_ID;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800223 }
Siarhei Vishniakou8a878352023-01-30 14:05:01 -0800224 if (pointerIdBits.test(id)) {
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700225 return Error() << "Motion event has duplicate pointer id " << id;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800226 }
Siarhei Vishniakou8a878352023-01-30 14:05:01 -0800227 pointerIdBits.set(id);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800228 }
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700229 return {};
230}
231
232Result<void> validateInputEvent(const InputEvent& event) {
233 switch (event.getType()) {
234 case InputEventType::KEY: {
235 const KeyEvent& key = static_cast<const KeyEvent&>(event);
236 const int32_t action = key.getAction();
237 return validateKeyEvent(action);
238 }
239 case InputEventType::MOTION: {
240 const MotionEvent& motion = static_cast<const MotionEvent&>(event);
241 const int32_t action = motion.getAction();
242 const size_t pointerCount = motion.getPointerCount();
243 const PointerProperties* pointerProperties = motion.getPointerProperties();
244 const int32_t actionButton = motion.getActionButton();
245 return validateMotionEvent(action, actionButton, pointerCount, pointerProperties);
246 }
247 default: {
248 return {};
249 }
250 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800251}
252
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000253std::string dumpRegion(const Region& region) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800254 if (region.isEmpty()) {
Bernardo Rufino53fc31e2020-11-03 11:01:07 +0000255 return "<empty>";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800256 }
257
Bernardo Rufino53fc31e2020-11-03 11:01:07 +0000258 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800259 bool first = true;
260 Region::const_iterator cur = region.begin();
261 Region::const_iterator const tail = region.end();
262 while (cur != tail) {
263 if (first) {
264 first = false;
265 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800266 dump += "|";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800267 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800268 dump += StringPrintf("[%d,%d][%d,%d]", cur->left, cur->top, cur->right, cur->bottom);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800269 cur++;
270 }
Bernardo Rufino53fc31e2020-11-03 11:01:07 +0000271 return dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800272}
273
Prabir 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 Pradhanaeebeb42023-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
Siarhei Vishniakou5b9766d2023-07-18 14:06:29 -0700605 const int32_t pointerIndex = MotionEvent::getActionIndex(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 Vishniakoub581f7f2022-12-07 20:23:06 +0000657 out.push_back(touchedWindow);
658 }
659 }
660
661 for (const sp<WindowInfoHandle>& newWindow : newWindows) {
662 TouchedWindow touchedWindow;
663 touchedWindow.windowHandle = newWindow;
664 if (oldWindows.find(newWindow) == oldWindows.end()) {
665 // Any windows that have this pointer now, and didn't have it before, should get
666 // HOVER_ENTER
667 touchedWindow.targetFlags = InputTarget::Flags::DISPATCH_AS_HOVER_ENTER;
668 } else {
669 // This pointer was already sent to the window. Use ACTION_HOVER_MOVE.
Siarhei Vishniakouc2eb8502023-04-11 18:33:36 -0700670 if (CC_UNLIKELY(maskedAction != AMOTION_EVENT_ACTION_HOVER_MOVE)) {
671 LOG(FATAL) << "Expected ACTION_HOVER_MOVE instead of " << entry.getDescription();
672 }
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000673 touchedWindow.targetFlags = InputTarget::Flags::DISPATCH_AS_IS;
674 }
Siarhei Vishniakou0836a302023-05-03 13:54:30 -0700675 touchedWindow.addHoveringPointer(entry.deviceId, pointerId);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000676 if (canReceiveForegroundTouches(*newWindow->getInfo())) {
677 touchedWindow.targetFlags |= InputTarget::Flags::FOREGROUND;
678 }
679 out.push_back(touchedWindow);
680 }
681 return out;
682}
683
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -0800684template <typename T>
685std::vector<T>& operator+=(std::vector<T>& left, const std::vector<T>& right) {
686 left.insert(left.end(), right.begin(), right.end());
687 return left;
688}
689
Harry Cuttsb166c002023-05-09 13:06:05 +0000690// Filter windows in a TouchState and targets in a vector to remove untrusted windows/targets from
691// both.
692void filterUntrustedTargets(TouchState& touchState, std::vector<InputTarget>& targets) {
693 std::erase_if(touchState.windows, [&](const TouchedWindow& window) {
694 if (!window.windowHandle->getInfo()->inputConfig.test(
695 WindowInfo::InputConfig::TRUSTED_OVERLAY)) {
696 // In addition to TouchState, erase this window from the input targets! We don't have a
697 // good way to do this today except by adding a nested loop.
698 // TODO(b/282025641): simplify this code once InputTargets are being identified
699 // separately from TouchedWindows.
700 std::erase_if(targets, [&](const InputTarget& target) {
701 return target.inputChannel->getConnectionToken() == window.windowHandle->getToken();
702 });
703 return true;
704 }
705 return false;
706 });
707}
708
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000709} // namespace
710
Michael Wrightd02c5b62014-02-10 15:10:22 -0800711// --- InputDispatcher ---
712
Prabir Pradhana41d2442023-04-20 21:30:40 +0000713InputDispatcher::InputDispatcher(InputDispatcherPolicyInterface& policy)
Siarhei Vishniakou289e9242022-02-15 14:50:16 -0800714 : InputDispatcher(policy, STALE_EVENT_TIMEOUT) {}
715
Prabir Pradhana41d2442023-04-20 21:30:40 +0000716InputDispatcher::InputDispatcher(InputDispatcherPolicyInterface& policy,
Siarhei Vishniakou289e9242022-02-15 14:50:16 -0800717 std::chrono::nanoseconds staleEventTimeout)
Garfield Tan00f511d2019-06-12 16:55:40 -0700718 : mPolicy(policy),
719 mPendingEvent(nullptr),
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700720 mLastDropReason(DropReason::NOT_DROPPED),
Garfield Tanff1f1bb2020-01-28 13:24:04 -0800721 mIdGenerator(IdGenerator::Source::INPUT_DISPATCHER),
Garfield Tan00f511d2019-06-12 16:55:40 -0700722 mAppSwitchSawKeyDown(false),
Colin Cross5b799302022-10-18 21:52:41 -0700723 mAppSwitchDueTime(LLONG_MAX),
Garfield Tan00f511d2019-06-12 16:55:40 -0700724 mNextUnblockedEvent(nullptr),
Prabir Pradhan1376fcd2022-01-21 09:56:35 -0800725 mMonitorDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT),
Garfield Tan00f511d2019-06-12 16:55:40 -0700726 mDispatchEnabled(false),
727 mDispatchFrozen(false),
728 mInputFilterEnabled(false),
Bernardo Rufinoea97d182020-08-19 14:43:14 +0100729 mMaximumObscuringOpacityForTouch(1.0f),
Siarhei Vishniakou2508b872020-12-03 16:33:53 -1000730 mFocusedDisplayId(ADISPLAY_ID_DEFAULT),
Prabir Pradhan99987712020-11-10 18:43:05 -0800731 mWindowTokenWithPointerCapture(nullptr),
Siarhei Vishniakou289e9242022-02-15 14:50:16 -0800732 mStaleEventTimeout(staleEventTimeout),
Siarhei Vishniakoua04181f2021-03-26 05:56:49 +0000733 mLatencyAggregator(),
Antonio Kantek15beb512022-06-13 22:35:41 +0000734 mLatencyTracker(&mLatencyAggregator) {
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -0700735 mLooper = sp<Looper>::make(false);
Prabir Pradhanf93562f2018-11-29 12:13:37 -0800736 mReporter = createInputReporter();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800737
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -0700738 mWindowInfoListener = sp<DispatcherWindowListener>::make(*this);
Siarhei Vishniakou31977182022-09-30 08:51:23 -0700739#if defined(__ANDROID__)
Siarhei Vishniakou18050092021-09-01 13:32:49 -0700740 SurfaceComposerClient::getDefault()->addWindowInfosListener(mWindowInfoListener);
Siarhei Vishniakou31977182022-09-30 08:51:23 -0700741#endif
Yi Kong9b14ac62018-07-17 13:48:38 -0700742 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800743}
744
745InputDispatcher::~InputDispatcher() {
Prabir Pradhancef936d2021-07-21 16:17:52 +0000746 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800747
Prabir Pradhancef936d2021-07-21 16:17:52 +0000748 resetKeyRepeatLocked();
749 releasePendingEventLocked();
750 drainInboundQueueLocked();
751 mCommandQueue.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800752
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +0000753 while (!mConnectionsByToken.empty()) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -0700754 std::shared_ptr<Connection> connection = mConnectionsByToken.begin()->second;
Harry Cutts33476232023-01-30 19:57:29 +0000755 removeInputChannelLocked(connection->inputChannel->getConnectionToken(), /*notify=*/false);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800756 }
757}
758
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700759status_t InputDispatcher::start() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700760 if (mThread) {
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700761 return ALREADY_EXISTS;
762 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700763 mThread = std::make_unique<InputThread>(
764 "InputDispatcher", [this]() { dispatchOnce(); }, [this]() { mLooper->wake(); });
765 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700766}
767
768status_t InputDispatcher::stop() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700769 if (mThread && mThread->isCallingThread()) {
770 ALOGE("InputDispatcher cannot be stopped from its own thread!");
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700771 return INVALID_OPERATION;
772 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700773 mThread.reset();
774 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700775}
776
Michael Wrightd02c5b62014-02-10 15:10:22 -0800777void InputDispatcher::dispatchOnce() {
Colin Cross5b799302022-10-18 21:52:41 -0700778 nsecs_t nextWakeupTime = LLONG_MAX;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800779 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -0800780 std::scoped_lock _l(mLock);
781 mDispatcherIsAlive.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800782
783 // Run a dispatch loop if there are no pending commands.
784 // The dispatch loop might enqueue commands to run afterwards.
785 if (!haveCommandsLocked()) {
786 dispatchOnceInnerLocked(&nextWakeupTime);
787 }
788
789 // Run all pending commands if there are any.
790 // If any commands were run then force the next poll to wake up immediately.
Prabir Pradhancef936d2021-07-21 16:17:52 +0000791 if (runCommandsLockedInterruptable()) {
Colin Cross5b799302022-10-18 21:52:41 -0700792 nextWakeupTime = LLONG_MIN;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800793 }
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800794
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700795 // If we are still waiting for ack on some events,
796 // we might have to wake up earlier to check if an app is anr'ing.
797 const nsecs_t nextAnrCheck = processAnrsLocked();
798 nextWakeupTime = std::min(nextWakeupTime, nextAnrCheck);
799
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800800 // We are about to enter an infinitely long sleep, because we have no commands or
801 // pending or queued events
Colin Cross5b799302022-10-18 21:52:41 -0700802 if (nextWakeupTime == LLONG_MAX) {
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800803 mDispatcherEnteredIdle.notify_all();
804 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800805 } // release lock
806
807 // Wait for callback or timeout or wake. (make sure we round up, not down)
808 nsecs_t currentTime = now();
809 int timeoutMillis = toMillisecondTimeoutDelay(currentTime, nextWakeupTime);
810 mLooper->pollOnce(timeoutMillis);
811}
812
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700813/**
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500814 * Raise ANR if there is no focused window.
815 * Before the ANR is raised, do a final state check:
816 * 1. The currently focused application must be the same one we are waiting for.
817 * 2. Ensure we still don't have a focused window.
818 */
819void InputDispatcher::processNoFocusedWindowAnrLocked() {
820 // Check if the application that we are waiting for is still focused.
821 std::shared_ptr<InputApplicationHandle> focusedApplication =
822 getValueByKey(mFocusedApplicationHandlesByDisplay, mAwaitedApplicationDisplayId);
823 if (focusedApplication == nullptr ||
824 focusedApplication->getApplicationToken() !=
825 mAwaitedFocusedApplication->getApplicationToken()) {
826 // Unexpected because we should have reset the ANR timer when focused application changed
827 ALOGE("Waited for a focused window, but focused application has already changed to %s",
828 focusedApplication->getName().c_str());
829 return; // The focused application has changed.
830 }
831
chaviw98318de2021-05-19 16:45:23 -0500832 const sp<WindowInfoHandle>& focusedWindowHandle =
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500833 getFocusedWindowHandleLocked(mAwaitedApplicationDisplayId);
834 if (focusedWindowHandle != nullptr) {
835 return; // We now have a focused window. No need for ANR.
836 }
837 onAnrLocked(mAwaitedFocusedApplication);
838}
839
840/**
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700841 * Check if any of the connections' wait queues have events that are too old.
842 * If we waited for events to be ack'ed for more than the window timeout, raise an ANR.
843 * Return the time at which we should wake up next.
844 */
845nsecs_t InputDispatcher::processAnrsLocked() {
846 const nsecs_t currentTime = now();
Colin Cross5b799302022-10-18 21:52:41 -0700847 nsecs_t nextAnrCheck = LLONG_MAX;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700848 // Check if we are waiting for a focused window to appear. Raise ANR if waited too long
849 if (mNoFocusedWindowTimeoutTime.has_value() && mAwaitedFocusedApplication != nullptr) {
850 if (currentTime >= *mNoFocusedWindowTimeoutTime) {
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500851 processNoFocusedWindowAnrLocked();
Chris Yea209fde2020-07-22 13:54:51 -0700852 mAwaitedFocusedApplication.reset();
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500853 mNoFocusedWindowTimeoutTime = std::nullopt;
Colin Cross5b799302022-10-18 21:52:41 -0700854 return LLONG_MIN;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700855 } else {
Siarhei Vishniakou38a6d272020-10-20 20:29:33 -0500856 // Keep waiting. We will drop the event when mNoFocusedWindowTimeoutTime comes.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700857 nextAnrCheck = *mNoFocusedWindowTimeoutTime;
858 }
859 }
860
861 // Check if any connection ANRs are due
862 nextAnrCheck = std::min(nextAnrCheck, mAnrTracker.firstTimeout());
863 if (currentTime < nextAnrCheck) { // most likely scenario
864 return nextAnrCheck; // everything is normal. Let's check again at nextAnrCheck
865 }
866
867 // If we reached here, we have an unresponsive connection.
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -0700868 std::shared_ptr<Connection> connection = getConnectionLocked(mAnrTracker.firstToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700869 if (connection == nullptr) {
870 ALOGE("Could not find connection for entry %" PRId64, mAnrTracker.firstTimeout());
871 return nextAnrCheck;
872 }
873 connection->responsive = false;
874 // Stop waking up for this unresponsive connection
875 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000876 onAnrLocked(connection);
Colin Cross5b799302022-10-18 21:52:41 -0700877 return LLONG_MIN;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700878}
879
Prabir Pradhan1376fcd2022-01-21 09:56:35 -0800880std::chrono::nanoseconds InputDispatcher::getDispatchingTimeoutLocked(
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -0700881 const std::shared_ptr<Connection>& connection) {
Prabir Pradhan1376fcd2022-01-21 09:56:35 -0800882 if (connection->monitor) {
883 return mMonitorDispatchingTimeout;
884 }
885 const sp<WindowInfoHandle> window =
886 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700887 if (window != nullptr) {
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500888 return window->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700889 }
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500890 return DEFAULT_INPUT_DISPATCHING_TIMEOUT;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700891}
892
Michael Wrightd02c5b62014-02-10 15:10:22 -0800893void InputDispatcher::dispatchOnceInnerLocked(nsecs_t* nextWakeupTime) {
894 nsecs_t currentTime = now();
895
Jeff Browndc5992e2014-04-11 01:27:26 -0700896 // Reset the key repeat timer whenever normal dispatch is suspended while the
897 // device is in a non-interactive state. This is to ensure that we abort a key
898 // repeat if the device is just coming out of sleep.
899 if (!mDispatchEnabled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800900 resetKeyRepeatLocked();
901 }
902
903 // If dispatching is frozen, do not process timeouts or try to deliver any new events.
904 if (mDispatchFrozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +0100905 if (DEBUG_FOCUS) {
906 ALOGD("Dispatch frozen. Waiting some more.");
907 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800908 return;
909 }
910
911 // Optimize latency of app switches.
912 // Essentially we start a short timeout when an app switch key (HOME / ENDCALL) has
913 // been pressed. When it expires, we preempt dispatch and drop all other pending events.
914 bool isAppSwitchDue = mAppSwitchDueTime <= currentTime;
915 if (mAppSwitchDueTime < *nextWakeupTime) {
916 *nextWakeupTime = mAppSwitchDueTime;
917 }
918
919 // Ready to start a new event.
920 // If we don't already have a pending event, go grab one.
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700921 if (!mPendingEvent) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700922 if (mInboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800923 if (isAppSwitchDue) {
924 // The inbound queue is empty so the app switch key we were waiting
925 // for will never arrive. Stop waiting for it.
926 resetPendingAppSwitchLocked(false);
927 isAppSwitchDue = false;
928 }
929
930 // Synthesize a key repeat if appropriate.
931 if (mKeyRepeatState.lastKeyEntry) {
932 if (currentTime >= mKeyRepeatState.nextRepeatTime) {
933 mPendingEvent = synthesizeKeyRepeatLocked(currentTime);
934 } else {
935 if (mKeyRepeatState.nextRepeatTime < *nextWakeupTime) {
936 *nextWakeupTime = mKeyRepeatState.nextRepeatTime;
937 }
938 }
939 }
940
941 // Nothing to do if there is no pending event.
942 if (!mPendingEvent) {
943 return;
944 }
945 } else {
946 // Inbound queue has at least one entry.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700947 mPendingEvent = mInboundQueue.front();
948 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800949 traceInboundQueueLengthLocked();
950 }
951
952 // Poke user activity for this event.
953 if (mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700954 pokeUserActivityLocked(*mPendingEvent);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800955 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800956 }
957
958 // Now we have an event to dispatch.
959 // All events are eventually dequeued and processed this way, even if we intend to drop them.
Yi Kong9b14ac62018-07-17 13:48:38 -0700960 ALOG_ASSERT(mPendingEvent != nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800961 bool done = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700962 DropReason dropReason = DropReason::NOT_DROPPED;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800963 if (!(mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700964 dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800965 } else if (!mDispatchEnabled) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700966 dropReason = DropReason::DISABLED;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800967 }
968
969 if (mNextUnblockedEvent == mPendingEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -0700970 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800971 }
972
973 switch (mPendingEvent->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700974 case EventEntry::Type::CONFIGURATION_CHANGED: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700975 const ConfigurationChangedEntry& typedEntry =
976 static_cast<const ConfigurationChangedEntry&>(*mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700977 done = dispatchConfigurationChangedLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700978 dropReason = DropReason::NOT_DROPPED; // configuration changes are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700979 break;
980 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800981
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700982 case EventEntry::Type::DEVICE_RESET: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700983 const DeviceResetEntry& typedEntry =
984 static_cast<const DeviceResetEntry&>(*mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700985 done = dispatchDeviceResetLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700986 dropReason = DropReason::NOT_DROPPED; // device resets are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700987 break;
988 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800989
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100990 case EventEntry::Type::FOCUS: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700991 std::shared_ptr<FocusEntry> typedEntry =
992 std::static_pointer_cast<FocusEntry>(mPendingEvent);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100993 dispatchFocusLocked(currentTime, typedEntry);
994 done = true;
995 dropReason = DropReason::NOT_DROPPED; // focus events are never dropped
996 break;
997 }
998
Antonio Kantek7242d8b2021-08-05 16:07:20 -0700999 case EventEntry::Type::TOUCH_MODE_CHANGED: {
1000 const auto typedEntry = std::static_pointer_cast<TouchModeEntry>(mPendingEvent);
1001 dispatchTouchModeChangeLocked(currentTime, typedEntry);
1002 done = true;
1003 dropReason = DropReason::NOT_DROPPED; // touch mode events are never dropped
1004 break;
1005 }
1006
Prabir Pradhan99987712020-11-10 18:43:05 -08001007 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
1008 const auto typedEntry =
1009 std::static_pointer_cast<PointerCaptureChangedEntry>(mPendingEvent);
1010 dispatchPointerCaptureChangedLocked(currentTime, typedEntry, dropReason);
1011 done = true;
1012 break;
1013 }
1014
arthurhungb89ccb02020-12-30 16:19:01 +08001015 case EventEntry::Type::DRAG: {
1016 std::shared_ptr<DragEntry> typedEntry =
1017 std::static_pointer_cast<DragEntry>(mPendingEvent);
1018 dispatchDragLocked(currentTime, typedEntry);
1019 done = true;
1020 break;
1021 }
1022
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001023 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001024 std::shared_ptr<KeyEntry> keyEntry = std::static_pointer_cast<KeyEntry>(mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001025 if (isAppSwitchDue) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001026 if (isAppSwitchKeyEvent(*keyEntry)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001027 resetPendingAppSwitchLocked(true);
1028 isAppSwitchDue = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001029 } else if (dropReason == DropReason::NOT_DROPPED) {
1030 dropReason = DropReason::APP_SWITCH;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001031 }
1032 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001033 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *keyEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001034 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001035 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001036 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
1037 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001038 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001039 done = dispatchKeyLocked(currentTime, keyEntry, &dropReason, nextWakeupTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001040 break;
1041 }
1042
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001043 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001044 std::shared_ptr<MotionEntry> motionEntry =
1045 std::static_pointer_cast<MotionEntry>(mPendingEvent);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001046 if (dropReason == DropReason::NOT_DROPPED && isAppSwitchDue) {
1047 dropReason = DropReason::APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001048 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001049 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *motionEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001050 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001051 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001052 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
1053 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001054 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001055 done = dispatchMotionLocked(currentTime, motionEntry, &dropReason, nextWakeupTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001056 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001057 }
Chris Yef59a2f42020-10-16 12:55:26 -07001058
1059 case EventEntry::Type::SENSOR: {
1060 std::shared_ptr<SensorEntry> sensorEntry =
1061 std::static_pointer_cast<SensorEntry>(mPendingEvent);
1062 if (dropReason == DropReason::NOT_DROPPED && isAppSwitchDue) {
1063 dropReason = DropReason::APP_SWITCH;
1064 }
1065 // Sensor timestamps use SYSTEM_TIME_BOOTTIME time base, so we can't use
1066 // 'currentTime' here, get SYSTEM_TIME_BOOTTIME instead.
1067 nsecs_t bootTime = systemTime(SYSTEM_TIME_BOOTTIME);
1068 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(bootTime, *sensorEntry)) {
1069 dropReason = DropReason::STALE;
1070 }
1071 dispatchSensorLocked(currentTime, sensorEntry, &dropReason, nextWakeupTime);
1072 done = true;
1073 break;
1074 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001075 }
1076
1077 if (done) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001078 if (dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001079 dropInboundEventLocked(*mPendingEvent, dropReason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001080 }
Michael Wright3a981722015-06-10 15:26:13 +01001081 mLastDropReason = dropReason;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001082
1083 releasePendingEventLocked();
Colin Cross5b799302022-10-18 21:52:41 -07001084 *nextWakeupTime = LLONG_MIN; // force next poll to wake up immediately
Michael Wrightd02c5b62014-02-10 15:10:22 -08001085 }
1086}
1087
Siarhei Vishniakou289e9242022-02-15 14:50:16 -08001088bool InputDispatcher::isStaleEvent(nsecs_t currentTime, const EventEntry& entry) {
1089 return std::chrono::nanoseconds(currentTime - entry.eventTime) >= mStaleEventTimeout;
1090}
1091
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001092/**
1093 * Return true if the events preceding this incoming motion event should be dropped
1094 * Return false otherwise (the default behaviour)
1095 */
1096bool InputDispatcher::shouldPruneInboundQueueLocked(const MotionEntry& motionEntry) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001097 const bool isPointerDownEvent = motionEntry.action == AMOTION_EVENT_ACTION_DOWN &&
Prabir Pradhanaa561d12021-09-24 06:57:33 -07001098 isFromSource(motionEntry.source, AINPUT_SOURCE_CLASS_POINTER);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001099
1100 // Optimize case where the current application is unresponsive and the user
1101 // decides to touch a window in a different application.
1102 // If the application takes too long to catch up then we drop all events preceding
1103 // the touch into the other window.
1104 if (isPointerDownEvent && mAwaitedFocusedApplication != nullptr) {
Siarhei Vishniakou9306c382022-09-30 15:30:31 -07001105 const int32_t displayId = motionEntry.displayId;
1106 const auto [x, y] = resolveTouchedPosition(motionEntry);
Harry Cutts33476232023-01-30 19:57:29 +00001107 const bool isStylus = isPointerFromStylus(motionEntry, /*pointerIndex=*/0);
Siarhei Vishniakou9306c382022-09-30 15:30:31 -07001108
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07001109 sp<WindowInfoHandle> touchedWindowHandle =
1110 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 Vishniakoue1ada272022-11-03 10:47:08 -07001234sp<WindowInfoHandle> InputDispatcher::findTouchedWindowAtLocked(int32_t displayId, float x, float y,
1235 bool isStylus,
1236 bool ignoreDragWindow) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001237 // Traverse windows from front to back to find touched window.
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001238 const auto& windowHandles = getWindowHandlesLocked(displayId);
chaviw98318de2021-05-19 16:45:23 -05001239 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
arthurhung6d4bed92021-03-17 11:59:33 +08001240 if (ignoreDragWindow && haveSameToken(windowHandle, mDragState->dragWindow)) {
arthurhungb89ccb02020-12-30 16:19:01 +08001241 continue;
1242 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001243
Prabir Pradhan3f90d312021-11-19 03:57:24 -08001244 const WindowInfo& info = *windowHandle->getInfo();
Prabir Pradhan33e3baa2022-12-06 20:30:22 +00001245 if (!info.isSpy() &&
1246 windowAcceptsTouchAt(info, displayId, x, y, isStylus, getTransformLocked(displayId))) {
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07001247 return windowHandle;
1248 }
1249 }
1250 return nullptr;
1251}
1252
1253std::vector<InputTarget> InputDispatcher::findOutsideTargetsLocked(
1254 int32_t displayId, const sp<WindowInfoHandle>& touchedWindow) const {
1255 if (touchedWindow == nullptr) {
1256 return {};
1257 }
1258 // Traverse windows from front to back until we encounter the touched window.
1259 std::vector<InputTarget> outsideTargets;
1260 const auto& windowHandles = getWindowHandlesLocked(displayId);
1261 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
1262 if (windowHandle == touchedWindow) {
1263 // Stop iterating once we found a touched window. Any WATCH_OUTSIDE_TOUCH window
1264 // below the touched window will not get ACTION_OUTSIDE event.
1265 return outsideTargets;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08001266 }
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001267
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07001268 const WindowInfo& info = *windowHandle->getInfo();
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08001269 if (info.inputConfig.test(WindowInfo::InputConfig::WATCH_OUTSIDE_TOUCH)) {
1270 addWindowTargetLocked(windowHandle, InputTarget::Flags::DISPATCH_AS_OUTSIDE,
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08001271 /*pointerIds=*/{}, /*firstDownTimeInTarget=*/std::nullopt,
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08001272 outsideTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001273 }
1274 }
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07001275 return outsideTargets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001276}
1277
Prabir Pradhand65552b2021-10-07 11:23:50 -07001278std::vector<sp<WindowInfoHandle>> InputDispatcher::findTouchedSpyWindowsAtLocked(
Prabir Pradhan82e081e2022-12-06 09:50:09 +00001279 int32_t displayId, float x, float y, bool isStylus) const {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001280 // Traverse windows from front to back and gather the touched spy windows.
1281 std::vector<sp<WindowInfoHandle>> spyWindows;
1282 const auto& windowHandles = getWindowHandlesLocked(displayId);
1283 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
1284 const WindowInfo& info = *windowHandle->getInfo();
1285
Prabir Pradhan33e3baa2022-12-06 20:30:22 +00001286 if (!windowAcceptsTouchAt(info, displayId, x, y, isStylus, getTransformLocked(displayId))) {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001287 continue;
1288 }
1289 if (!info.isSpy()) {
1290 // The first touched non-spy window was found, so return the spy windows touched so far.
1291 return spyWindows;
1292 }
1293 spyWindows.push_back(windowHandle);
1294 }
1295 return spyWindows;
1296}
1297
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001298void InputDispatcher::dropInboundEventLocked(const EventEntry& entry, DropReason dropReason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001299 const char* reason;
1300 switch (dropReason) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001301 case DropReason::POLICY:
Prabir Pradhan65613802023-02-22 23:36:58 +00001302 if (debugInboundEventDetails()) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001303 ALOGD("Dropped event because policy consumed it.");
1304 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001305 reason = "inbound event was dropped because the policy consumed it";
1306 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001307 case DropReason::DISABLED:
1308 if (mLastDropReason != DropReason::DISABLED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001309 ALOGI("Dropped event because input dispatch is disabled.");
1310 }
1311 reason = "inbound event was dropped because input dispatch is disabled";
1312 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001313 case DropReason::APP_SWITCH:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001314 ALOGI("Dropped event because of pending overdue app switch.");
1315 reason = "inbound event was dropped because of pending overdue app switch";
1316 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001317 case DropReason::BLOCKED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001318 ALOGI("Dropped event because the current application is not responding and the user "
1319 "has started interacting with a different application.");
1320 reason = "inbound event was dropped because the current application is not responding "
1321 "and the user has started interacting with a different application";
1322 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001323 case DropReason::STALE:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001324 ALOGI("Dropped event because it is stale.");
1325 reason = "inbound event was dropped because it is stale";
1326 break;
Prabir Pradhan99987712020-11-10 18:43:05 -08001327 case DropReason::NO_POINTER_CAPTURE:
1328 ALOGI("Dropped event because there is no window with Pointer Capture.");
1329 reason = "inbound event was dropped because there is no window with Pointer Capture";
1330 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001331 case DropReason::NOT_DROPPED: {
1332 LOG_ALWAYS_FATAL("Should not be dropping a NOT_DROPPED event");
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001333 return;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001334 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001335 }
1336
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001337 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001338 case EventEntry::Type::KEY: {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001339 CancelationOptions options(CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS, reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001340 synthesizeCancelationEventsForAllConnectionsLocked(options);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001341 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001342 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001343 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001344 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
1345 if (motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001346 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS, reason);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001347 synthesizeCancelationEventsForAllConnectionsLocked(options);
1348 } else {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001349 CancelationOptions options(CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS,
1350 reason);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001351 synthesizeCancelationEventsForAllConnectionsLocked(options);
1352 }
1353 break;
1354 }
Chris Yef59a2f42020-10-16 12:55:26 -07001355 case EventEntry::Type::SENSOR: {
1356 break;
1357 }
arthurhungb89ccb02020-12-30 16:19:01 +08001358 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
1359 case EventEntry::Type::DRAG: {
Prabir Pradhan99987712020-11-10 18:43:05 -08001360 break;
1361 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001362 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001363 case EventEntry::Type::TOUCH_MODE_CHANGED:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001364 case EventEntry::Type::CONFIGURATION_CHANGED:
1365 case EventEntry::Type::DEVICE_RESET: {
Dominik Laskowski75788452021-02-09 18:51:25 -08001366 LOG_ALWAYS_FATAL("Should not drop %s events", ftl::enum_string(entry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001367 break;
1368 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001369 }
1370}
1371
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08001372static bool isAppSwitchKeyCode(int32_t keyCode) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001373 return keyCode == AKEYCODE_HOME || keyCode == AKEYCODE_ENDCALL ||
1374 keyCode == AKEYCODE_APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001375}
1376
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001377bool InputDispatcher::isAppSwitchKeyEvent(const KeyEntry& keyEntry) {
1378 return !(keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) && isAppSwitchKeyCode(keyEntry.keyCode) &&
1379 (keyEntry.policyFlags & POLICY_FLAG_TRUSTED) &&
1380 (keyEntry.policyFlags & POLICY_FLAG_PASS_TO_USER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001381}
1382
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07001383bool InputDispatcher::isAppSwitchPendingLocked() const {
Colin Cross5b799302022-10-18 21:52:41 -07001384 return mAppSwitchDueTime != LLONG_MAX;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001385}
1386
1387void InputDispatcher::resetPendingAppSwitchLocked(bool handled) {
Colin Cross5b799302022-10-18 21:52:41 -07001388 mAppSwitchDueTime = LLONG_MAX;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001389
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001390 if (DEBUG_APP_SWITCH) {
1391 if (handled) {
1392 ALOGD("App switch has arrived.");
1393 } else {
1394 ALOGD("App switch was abandoned.");
1395 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001396 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001397}
1398
Michael Wrightd02c5b62014-02-10 15:10:22 -08001399bool InputDispatcher::haveCommandsLocked() const {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001400 return !mCommandQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001401}
1402
Prabir Pradhancef936d2021-07-21 16:17:52 +00001403bool InputDispatcher::runCommandsLockedInterruptable() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001404 if (mCommandQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001405 return false;
1406 }
1407
1408 do {
Prabir Pradhancef936d2021-07-21 16:17:52 +00001409 auto command = std::move(mCommandQueue.front());
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001410 mCommandQueue.pop_front();
Prabir Pradhancef936d2021-07-21 16:17:52 +00001411 // Commands are run with the lock held, but may release and re-acquire the lock from within.
1412 command();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001413 } while (!mCommandQueue.empty());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001414 return true;
1415}
1416
Prabir Pradhancef936d2021-07-21 16:17:52 +00001417void InputDispatcher::postCommandLocked(Command&& command) {
1418 mCommandQueue.push_back(command);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001419}
1420
1421void InputDispatcher::drainInboundQueueLocked() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001422 while (!mInboundQueue.empty()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001423 std::shared_ptr<EventEntry> entry = mInboundQueue.front();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001424 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001425 releaseInboundEventLocked(entry);
1426 }
1427 traceInboundQueueLengthLocked();
1428}
1429
1430void InputDispatcher::releasePendingEventLocked() {
1431 if (mPendingEvent) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001432 releaseInboundEventLocked(mPendingEvent);
Yi Kong9b14ac62018-07-17 13:48:38 -07001433 mPendingEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001434 }
1435}
1436
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001437void InputDispatcher::releaseInboundEventLocked(std::shared_ptr<EventEntry> entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001438 InjectionState* injectionState = entry->injectionState;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001439 if (injectionState && injectionState->injectionResult == InputEventInjectionResult::PENDING) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001440 if (DEBUG_DISPATCH_CYCLE) {
1441 ALOGD("Injected inbound event was dropped.");
1442 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001443 setInjectionResult(*entry, InputEventInjectionResult::FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001444 }
1445 if (entry == mNextUnblockedEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001446 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001447 }
1448 addRecentEventLocked(entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001449}
1450
1451void InputDispatcher::resetKeyRepeatLocked() {
1452 if (mKeyRepeatState.lastKeyEntry) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001453 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001454 }
1455}
1456
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001457std::shared_ptr<KeyEntry> InputDispatcher::synthesizeKeyRepeatLocked(nsecs_t currentTime) {
1458 std::shared_ptr<KeyEntry> entry = mKeyRepeatState.lastKeyEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001459
Michael Wright2e732952014-09-24 13:26:59 -07001460 uint32_t policyFlags = entry->policyFlags &
1461 (POLICY_FLAG_RAW_MASK | POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_TRUSTED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001462
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001463 std::shared_ptr<KeyEntry> newEntry =
1464 std::make_unique<KeyEntry>(mIdGenerator.nextId(), currentTime, entry->deviceId,
1465 entry->source, entry->displayId, policyFlags, entry->action,
1466 entry->flags, entry->keyCode, entry->scanCode,
1467 entry->metaState, entry->repeatCount + 1, entry->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001468
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001469 newEntry->syntheticRepeat = true;
1470 mKeyRepeatState.lastKeyEntry = newEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001471 mKeyRepeatState.nextRepeatTime = currentTime + mConfig.keyRepeatDelay;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001472 return newEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001473}
1474
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001475bool InputDispatcher::dispatchConfigurationChangedLocked(nsecs_t currentTime,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001476 const ConfigurationChangedEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001477 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1478 ALOGD("dispatchConfigurationChanged - eventTime=%" PRId64, entry.eventTime);
1479 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001480
1481 // Reset key repeating in case a keyboard device was added or removed or something.
1482 resetKeyRepeatLocked();
1483
1484 // Enqueue a command to run outside the lock to tell the policy that the configuration changed.
Prabir Pradhancef936d2021-07-21 16:17:52 +00001485 auto command = [this, eventTime = entry.eventTime]() REQUIRES(mLock) {
1486 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00001487 mPolicy.notifyConfigurationChanged(eventTime);
Prabir Pradhancef936d2021-07-21 16:17:52 +00001488 };
1489 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001490 return true;
1491}
1492
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001493bool InputDispatcher::dispatchDeviceResetLocked(nsecs_t currentTime,
1494 const DeviceResetEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001495 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1496 ALOGD("dispatchDeviceReset - eventTime=%" PRId64 ", deviceId=%d", entry.eventTime,
1497 entry.deviceId);
1498 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001499
liushenxiang42232912021-05-21 20:24:09 +08001500 // Reset key repeating in case a keyboard device was disabled or enabled.
1501 if (mKeyRepeatState.lastKeyEntry && mKeyRepeatState.lastKeyEntry->deviceId == entry.deviceId) {
1502 resetKeyRepeatLocked();
1503 }
1504
Michael Wrightfb04fd52022-11-24 22:31:11 +00001505 CancelationOptions options(CancelationOptions::Mode::CANCEL_ALL_EVENTS, "device was reset");
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001506 options.deviceId = entry.deviceId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001507 synthesizeCancelationEventsForAllConnectionsLocked(options);
Siarhei Vishniakou0686f0c2023-05-02 11:56:15 -07001508
1509 // Remove all active pointers from this device
1510 for (auto& [_, touchState] : mTouchStatesByDisplay) {
1511 touchState.removeAllPointersForDevice(entry.deviceId);
1512 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001513 return true;
1514}
1515
Vishnu Nairad321cd2020-08-20 16:40:21 -07001516void InputDispatcher::enqueueFocusEventLocked(const sp<IBinder>& windowToken, bool hasFocus,
Vishnu Nairc519ff72021-01-21 08:23:08 -08001517 const std::string& reason) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001518 if (mPendingEvent != nullptr) {
1519 // Move the pending event to the front of the queue. This will give the chance
1520 // for the pending event to get dispatched to the newly focused window
1521 mInboundQueue.push_front(mPendingEvent);
1522 mPendingEvent = nullptr;
1523 }
1524
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001525 std::unique_ptr<FocusEntry> focusEntry =
1526 std::make_unique<FocusEntry>(mIdGenerator.nextId(), now(), windowToken, hasFocus,
1527 reason);
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001528
1529 // This event should go to the front of the queue, but behind all other focus events
1530 // Find the last focus event, and insert right after it
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001531 std::deque<std::shared_ptr<EventEntry>>::reverse_iterator it =
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001532 std::find_if(mInboundQueue.rbegin(), mInboundQueue.rend(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001533 [](const std::shared_ptr<EventEntry>& event) {
1534 return event->type == EventEntry::Type::FOCUS;
1535 });
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001536
1537 // Maintain the order of focus events. Insert the entry after all other focus events.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001538 mInboundQueue.insert(it.base(), std::move(focusEntry));
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001539}
1540
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001541void InputDispatcher::dispatchFocusLocked(nsecs_t currentTime, std::shared_ptr<FocusEntry> entry) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05001542 std::shared_ptr<InputChannel> channel = getInputChannelLocked(entry->connectionToken);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001543 if (channel == nullptr) {
1544 return; // Window has gone away
1545 }
1546 InputTarget target;
1547 target.inputChannel = channel;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08001548 target.flags = InputTarget::Flags::DISPATCH_AS_IS;
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001549 entry->dispatchInProgress = true;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00001550 std::string message = std::string("Focus ") + (entry->hasFocus ? "entering " : "leaving ") +
1551 channel->getName();
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07001552 std::string reason = std::string("reason=").append(entry->reason);
1553 android_log_event_list(LOGTAG_INPUT_FOCUS) << message << reason << LOG_ID_EVENTS;
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001554 dispatchEventLocked(currentTime, entry, {target});
1555}
1556
Prabir Pradhan99987712020-11-10 18:43:05 -08001557void InputDispatcher::dispatchPointerCaptureChangedLocked(
1558 nsecs_t currentTime, const std::shared_ptr<PointerCaptureChangedEntry>& entry,
1559 DropReason& dropReason) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001560 dropReason = DropReason::NOT_DROPPED;
1561
Prabir Pradhan99987712020-11-10 18:43:05 -08001562 const bool haveWindowWithPointerCapture = mWindowTokenWithPointerCapture != nullptr;
Prabir Pradhan99987712020-11-10 18:43:05 -08001563 sp<IBinder> token;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001564
1565 if (entry->pointerCaptureRequest.enable) {
1566 // Enable Pointer Capture.
1567 if (haveWindowWithPointerCapture &&
1568 (entry->pointerCaptureRequest == mCurrentPointerCaptureRequest)) {
Prabir Pradhan7092e262022-05-03 16:51:09 +00001569 // This can happen if pointer capture is disabled and re-enabled before we notify the
1570 // app of the state change, so there is no need to notify the app.
1571 ALOGI("Skipping dispatch of Pointer Capture being enabled: no state change.");
1572 return;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001573 }
1574 if (!mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08001575 // This can happen if a window requests capture and immediately releases capture.
1576 ALOGW("No window requested Pointer Capture.");
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001577 dropReason = DropReason::NO_POINTER_CAPTURE;
Prabir Pradhan99987712020-11-10 18:43:05 -08001578 return;
1579 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001580 if (entry->pointerCaptureRequest.seq != mCurrentPointerCaptureRequest.seq) {
1581 ALOGI("Skipping dispatch of Pointer Capture being enabled: sequence number mismatch.");
1582 return;
1583 }
1584
Vishnu Nairc519ff72021-01-21 08:23:08 -08001585 token = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Prabir Pradhan99987712020-11-10 18:43:05 -08001586 LOG_ALWAYS_FATAL_IF(!token, "Cannot find focused window for Pointer Capture.");
1587 mWindowTokenWithPointerCapture = token;
1588 } else {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001589 // Disable Pointer Capture.
1590 // We do not check if the sequence number matches for requests to disable Pointer Capture
1591 // for two reasons:
1592 // 1. Pointer Capture can be disabled by a focus change, which means we can get two entries
1593 // to disable capture with the same sequence number: one generated by
1594 // disablePointerCaptureForcedLocked() and another as an acknowledgement of Pointer
1595 // Capture being disabled in InputReader.
1596 // 2. We respect any request to disable Pointer Capture generated by InputReader, since the
1597 // actual Pointer Capture state that affects events being generated by input devices is
1598 // in InputReader.
1599 if (!haveWindowWithPointerCapture) {
1600 // Pointer capture was already forcefully disabled because of focus change.
1601 dropReason = DropReason::NOT_DROPPED;
1602 return;
1603 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001604 token = mWindowTokenWithPointerCapture;
1605 mWindowTokenWithPointerCapture = nullptr;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001606 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan7d030382020-12-21 07:58:35 -08001607 setPointerCaptureLocked(false);
1608 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001609 }
1610
1611 auto channel = getInputChannelLocked(token);
1612 if (channel == nullptr) {
1613 // Window has gone away, clean up Pointer Capture state.
1614 mWindowTokenWithPointerCapture = nullptr;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001615 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan7d030382020-12-21 07:58:35 -08001616 setPointerCaptureLocked(false);
1617 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001618 return;
1619 }
1620 InputTarget target;
1621 target.inputChannel = channel;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08001622 target.flags = InputTarget::Flags::DISPATCH_AS_IS;
Prabir Pradhan99987712020-11-10 18:43:05 -08001623 entry->dispatchInProgress = true;
1624 dispatchEventLocked(currentTime, entry, {target});
1625
1626 dropReason = DropReason::NOT_DROPPED;
1627}
1628
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001629void InputDispatcher::dispatchTouchModeChangeLocked(nsecs_t currentTime,
1630 const std::shared_ptr<TouchModeEntry>& entry) {
1631 const std::vector<sp<WindowInfoHandle>>& windowHandles =
Antonio Kantek15beb512022-06-13 22:35:41 +00001632 getWindowHandlesLocked(entry->displayId);
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001633 if (windowHandles.empty()) {
1634 return;
1635 }
1636 const std::vector<InputTarget> inputTargets =
1637 getInputTargetsFromWindowHandlesLocked(windowHandles);
1638 if (inputTargets.empty()) {
1639 return;
1640 }
1641 entry->dispatchInProgress = true;
1642 dispatchEventLocked(currentTime, entry, inputTargets);
1643}
1644
1645std::vector<InputTarget> InputDispatcher::getInputTargetsFromWindowHandlesLocked(
1646 const std::vector<sp<WindowInfoHandle>>& windowHandles) const {
1647 std::vector<InputTarget> inputTargets;
1648 for (const sp<WindowInfoHandle>& handle : windowHandles) {
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001649 const sp<IBinder>& token = handle->getToken();
1650 if (token == nullptr) {
1651 continue;
1652 }
1653 std::shared_ptr<InputChannel> channel = getInputChannelLocked(token);
1654 if (channel == nullptr) {
1655 continue; // Window has gone away
1656 }
1657 InputTarget target;
1658 target.inputChannel = channel;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08001659 target.flags = InputTarget::Flags::DISPATCH_AS_IS;
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001660 inputTargets.push_back(target);
1661 }
1662 return inputTargets;
1663}
1664
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001665bool InputDispatcher::dispatchKeyLocked(nsecs_t currentTime, std::shared_ptr<KeyEntry> entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001666 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001667 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001668 if (!entry->dispatchInProgress) {
1669 if (entry->repeatCount == 0 && entry->action == AKEY_EVENT_ACTION_DOWN &&
1670 (entry->policyFlags & POLICY_FLAG_TRUSTED) &&
1671 (!(entry->policyFlags & POLICY_FLAG_DISABLE_KEY_REPEAT))) {
1672 if (mKeyRepeatState.lastKeyEntry &&
Chris Ye2ad95392020-09-01 13:44:44 -07001673 mKeyRepeatState.lastKeyEntry->keyCode == entry->keyCode &&
Michael Wrightd02c5b62014-02-10 15:10:22 -08001674 // We have seen two identical key downs in a row which indicates that the device
1675 // driver is automatically generating key repeats itself. We take note of the
1676 // repeat here, but we disable our own next key repeat timer since it is clear that
1677 // we will not need to synthesize key repeats ourselves.
Chris Ye2ad95392020-09-01 13:44:44 -07001678 mKeyRepeatState.lastKeyEntry->deviceId == entry->deviceId) {
1679 // Make sure we don't get key down from a different device. If a different
1680 // device Id has same key pressed down, the new device Id will replace the
1681 // current one to hold the key repeat with repeat count reset.
1682 // In the future when got a KEY_UP on the device id, drop it and do not
1683 // stop the key repeat on current device.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001684 entry->repeatCount = mKeyRepeatState.lastKeyEntry->repeatCount + 1;
1685 resetKeyRepeatLocked();
Colin Cross5b799302022-10-18 21:52:41 -07001686 mKeyRepeatState.nextRepeatTime = LLONG_MAX; // don't generate repeats ourselves
Michael Wrightd02c5b62014-02-10 15:10:22 -08001687 } else {
1688 // Not a repeat. Save key down state in case we do see a repeat later.
1689 resetKeyRepeatLocked();
1690 mKeyRepeatState.nextRepeatTime = entry->eventTime + mConfig.keyRepeatTimeout;
1691 }
1692 mKeyRepeatState.lastKeyEntry = entry;
Chris Ye2ad95392020-09-01 13:44:44 -07001693 } else if (entry->action == AKEY_EVENT_ACTION_UP && mKeyRepeatState.lastKeyEntry &&
1694 mKeyRepeatState.lastKeyEntry->deviceId != entry->deviceId) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001695 // The key on device 'deviceId' is still down, do not stop key repeat
Prabir Pradhan65613802023-02-22 23:36:58 +00001696 if (debugInboundEventDetails()) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001697 ALOGD("deviceId=%d got KEY_UP as stale", entry->deviceId);
1698 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001699 } else if (!entry->syntheticRepeat) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001700 resetKeyRepeatLocked();
1701 }
1702
1703 if (entry->repeatCount == 1) {
1704 entry->flags |= AKEY_EVENT_FLAG_LONG_PRESS;
1705 } else {
1706 entry->flags &= ~AKEY_EVENT_FLAG_LONG_PRESS;
1707 }
1708
1709 entry->dispatchInProgress = true;
1710
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001711 logOutboundKeyDetails("dispatchKey - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001712 }
1713
1714 // Handle case where the policy asked us to try again later last time.
Michael Wright5caf55a2022-11-24 22:31:42 +00001715 if (entry->interceptKeyResult == KeyEntry::InterceptKeyResult::TRY_AGAIN_LATER) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001716 if (currentTime < entry->interceptKeyWakeupTime) {
1717 if (entry->interceptKeyWakeupTime < *nextWakeupTime) {
1718 *nextWakeupTime = entry->interceptKeyWakeupTime;
1719 }
1720 return false; // wait until next wakeup
1721 }
Michael Wright5caf55a2022-11-24 22:31:42 +00001722 entry->interceptKeyResult = KeyEntry::InterceptKeyResult::UNKNOWN;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001723 entry->interceptKeyWakeupTime = 0;
1724 }
1725
1726 // Give the policy a chance to intercept the key.
Michael Wright5caf55a2022-11-24 22:31:42 +00001727 if (entry->interceptKeyResult == KeyEntry::InterceptKeyResult::UNKNOWN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001728 if (entry->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07001729 sp<IBinder> focusedWindowToken =
Vishnu Nairc519ff72021-01-21 08:23:08 -08001730 mFocusResolver.getFocusedWindowToken(getTargetDisplayId(*entry));
Prabir Pradhancef936d2021-07-21 16:17:52 +00001731
1732 auto command = [this, focusedWindowToken, entry]() REQUIRES(mLock) {
1733 doInterceptKeyBeforeDispatchingCommand(focusedWindowToken, *entry);
1734 };
1735 postCommandLocked(std::move(command));
Josep del Riob3981622023-04-18 15:49:45 +00001736 // Poke user activity for keys not passed to user
1737 pokeUserActivityLocked(*entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001738 return false; // wait for the command to run
1739 } else {
Michael Wright5caf55a2022-11-24 22:31:42 +00001740 entry->interceptKeyResult = KeyEntry::InterceptKeyResult::CONTINUE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001741 }
Michael Wright5caf55a2022-11-24 22:31:42 +00001742 } else if (entry->interceptKeyResult == KeyEntry::InterceptKeyResult::SKIP) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001743 if (*dropReason == DropReason::NOT_DROPPED) {
1744 *dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001745 }
1746 }
1747
1748 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001749 if (*dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001750 setInjectionResult(*entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001751 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
1752 : InputEventInjectionResult::FAILED);
Garfield Tan6a5a14e2020-01-28 13:24:04 -08001753 mReporter->reportDroppedKey(entry->id);
Josep del Riob3981622023-04-18 15:49:45 +00001754 // Poke user activity for undispatched keys
1755 pokeUserActivityLocked(*entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001756 return true;
1757 }
1758
1759 // Identify targets.
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001760 InputEventInjectionResult injectionResult;
1761 sp<WindowInfoHandle> focusedWindow =
1762 findFocusedWindowTargetLocked(currentTime, *entry, nextWakeupTime,
1763 /*byref*/ injectionResult);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001764 if (injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001765 return false;
1766 }
1767
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001768 setInjectionResult(*entry, injectionResult);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001769 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001770 return true;
1771 }
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001772 LOG_ALWAYS_FATAL_IF(focusedWindow == nullptr);
1773
1774 std::vector<InputTarget> inputTargets;
1775 addWindowTargetLocked(focusedWindow,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08001776 InputTarget::Flags::FOREGROUND | InputTarget::Flags::DISPATCH_AS_IS,
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08001777 /*pointerIds=*/{}, getDownTime(*entry), inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001778
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001779 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001780 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001781
1782 // Dispatch the key.
1783 dispatchEventLocked(currentTime, entry, inputTargets);
1784 return true;
1785}
1786
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001787void InputDispatcher::logOutboundKeyDetails(const char* prefix, const KeyEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001788 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1789 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32 ", "
1790 "policyFlags=0x%x, action=0x%x, flags=0x%x, keyCode=0x%x, scanCode=0x%x, "
1791 "metaState=0x%x, repeatCount=%d, downTime=%" PRId64,
1792 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId,
1793 entry.policyFlags, entry.action, entry.flags, entry.keyCode, entry.scanCode,
1794 entry.metaState, entry.repeatCount, entry.downTime);
1795 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001796}
1797
Prabir Pradhancef936d2021-07-21 16:17:52 +00001798void InputDispatcher::dispatchSensorLocked(nsecs_t currentTime,
1799 const std::shared_ptr<SensorEntry>& entry,
Chris Yef59a2f42020-10-16 12:55:26 -07001800 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001801 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1802 ALOGD("notifySensorEvent eventTime=%" PRId64 ", hwTimestamp=%" PRId64 ", deviceId=%d, "
1803 "source=0x%x, sensorType=%s",
1804 entry->eventTime, entry->hwTimestamp, entry->deviceId, entry->source,
Dominik Laskowski75788452021-02-09 18:51:25 -08001805 ftl::enum_string(entry->sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001806 }
Prabir Pradhancef936d2021-07-21 16:17:52 +00001807 auto command = [this, entry]() REQUIRES(mLock) {
1808 scoped_unlock unlock(mLock);
1809
1810 if (entry->accuracyChanged) {
Prabir Pradhana41d2442023-04-20 21:30:40 +00001811 mPolicy.notifySensorAccuracy(entry->deviceId, entry->sensorType, entry->accuracy);
Prabir Pradhancef936d2021-07-21 16:17:52 +00001812 }
Prabir Pradhana41d2442023-04-20 21:30:40 +00001813 mPolicy.notifySensorEvent(entry->deviceId, entry->sensorType, entry->accuracy,
1814 entry->hwTimestamp, entry->values);
Prabir Pradhancef936d2021-07-21 16:17:52 +00001815 };
1816 postCommandLocked(std::move(command));
Chris Yef59a2f42020-10-16 12:55:26 -07001817}
1818
1819bool InputDispatcher::flushSensor(int deviceId, InputDeviceSensorType sensorType) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001820 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1821 ALOGD("flushSensor deviceId=%d, sensorType=%s", deviceId,
Dominik Laskowski75788452021-02-09 18:51:25 -08001822 ftl::enum_string(sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001823 }
Chris Yef59a2f42020-10-16 12:55:26 -07001824 { // acquire lock
1825 std::scoped_lock _l(mLock);
1826
1827 for (auto it = mInboundQueue.begin(); it != mInboundQueue.end(); it++) {
1828 std::shared_ptr<EventEntry> entry = *it;
1829 if (entry->type == EventEntry::Type::SENSOR) {
1830 it = mInboundQueue.erase(it);
1831 releaseInboundEventLocked(entry);
1832 }
1833 }
1834 }
1835 return true;
1836}
1837
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001838bool InputDispatcher::dispatchMotionLocked(nsecs_t currentTime, std::shared_ptr<MotionEntry> entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001839 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001840 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001841 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001842 if (!entry->dispatchInProgress) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001843 entry->dispatchInProgress = true;
1844
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001845 logOutboundMotionDetails("dispatchMotion - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001846 }
1847
1848 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001849 if (*dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001850 setInjectionResult(*entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001851 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
1852 : InputEventInjectionResult::FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001853 return true;
1854 }
1855
Prabir Pradhanaa561d12021-09-24 06:57:33 -07001856 const bool isPointerEvent = isFromSource(entry->source, AINPUT_SOURCE_CLASS_POINTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001857
1858 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001859 std::vector<InputTarget> inputTargets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001860
1861 bool conflictingPointerActions = false;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001862 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001863 if (isPointerEvent) {
1864 // Pointer event. (eg. touchscreen)
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00001865
1866 if (mDragState &&
1867 (entry->action & AMOTION_EVENT_ACTION_MASK) == AMOTION_EVENT_ACTION_POINTER_DOWN) {
1868 // If drag and drop ongoing and pointer down occur: pilfer drag window pointers
1869 pilferPointersLocked(mDragState->dragWindow->getToken());
1870 }
1871
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08001872 inputTargets =
Siarhei Vishniakou4fe57392022-10-25 13:44:30 -07001873 findTouchedWindowTargetsLocked(currentTime, *entry, &conflictingPointerActions,
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001874 /*byref*/ injectionResult);
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08001875 LOG_ALWAYS_FATAL_IF(injectionResult != InputEventInjectionResult::SUCCEEDED &&
1876 !inputTargets.empty());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001877 } else {
1878 // Non touch event. (eg. trackball)
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001879 sp<WindowInfoHandle> focusedWindow =
1880 findFocusedWindowTargetLocked(currentTime, *entry, nextWakeupTime, injectionResult);
1881 if (injectionResult == InputEventInjectionResult::SUCCEEDED) {
1882 LOG_ALWAYS_FATAL_IF(focusedWindow == nullptr);
1883 addWindowTargetLocked(focusedWindow,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08001884 InputTarget::Flags::FOREGROUND |
1885 InputTarget::Flags::DISPATCH_AS_IS,
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08001886 /*pointerIds=*/{}, getDownTime(*entry), inputTargets);
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001887 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001888 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001889 if (injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001890 return false;
1891 }
1892
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001893 setInjectionResult(*entry, injectionResult);
Prabir Pradhan5735a322022-04-11 17:23:34 +00001894 if (injectionResult == InputEventInjectionResult::TARGET_MISMATCH) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001895 return true;
1896 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001897 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001898 CancelationOptions::Mode mode(
1899 isPointerEvent ? CancelationOptions::Mode::CANCEL_POINTER_EVENTS
1900 : CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS);
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001901 CancelationOptions options(mode, "input event injection failed");
1902 synthesizeCancelationEventsForMonitorsLocked(options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001903 return true;
1904 }
1905
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001906 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001907 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001908
1909 // Dispatch the motion.
1910 if (conflictingPointerActions) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001911 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001912 "conflicting pointer actions");
Michael Wrightd02c5b62014-02-10 15:10:22 -08001913 synthesizeCancelationEventsForAllConnectionsLocked(options);
1914 }
1915 dispatchEventLocked(currentTime, entry, inputTargets);
1916 return true;
1917}
1918
chaviw98318de2021-05-19 16:45:23 -05001919void InputDispatcher::enqueueDragEventLocked(const sp<WindowInfoHandle>& windowHandle,
Arthur Hung54745652022-04-20 07:17:41 +00001920 bool isExiting, const int32_t rawX,
1921 const int32_t rawY) {
1922 const vec2 xy = windowHandle->getInfo()->transform.transform(vec2(rawX, rawY));
arthurhungb89ccb02020-12-30 16:19:01 +08001923 std::unique_ptr<DragEntry> dragEntry =
Arthur Hung54745652022-04-20 07:17:41 +00001924 std::make_unique<DragEntry>(mIdGenerator.nextId(), now(), windowHandle->getToken(),
1925 isExiting, xy.x, xy.y);
arthurhungb89ccb02020-12-30 16:19:01 +08001926
1927 enqueueInboundEventLocked(std::move(dragEntry));
1928}
1929
1930void InputDispatcher::dispatchDragLocked(nsecs_t currentTime, std::shared_ptr<DragEntry> entry) {
1931 std::shared_ptr<InputChannel> channel = getInputChannelLocked(entry->connectionToken);
1932 if (channel == nullptr) {
1933 return; // Window has gone away
1934 }
1935 InputTarget target;
1936 target.inputChannel = channel;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08001937 target.flags = InputTarget::Flags::DISPATCH_AS_IS;
arthurhungb89ccb02020-12-30 16:19:01 +08001938 entry->dispatchInProgress = true;
1939 dispatchEventLocked(currentTime, entry, {target});
1940}
1941
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001942void InputDispatcher::logOutboundMotionDetails(const char* prefix, const MotionEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001943 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -08001944 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=%s, displayId=%" PRId32
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001945 ", policyFlags=0x%x, "
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001946 "action=%s, actionButton=0x%x, flags=0x%x, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001947 "metaState=0x%x, buttonState=0x%x,"
1948 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%" PRId64,
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -08001949 prefix, entry.eventTime, entry.deviceId,
1950 inputEventSourceToString(entry.source).c_str(), entry.displayId, entry.policyFlags,
1951 MotionEvent::actionToString(entry.action).c_str(), entry.actionButton, entry.flags,
1952 entry.metaState, entry.buttonState, entry.edgeFlags, entry.xPrecision,
1953 entry.yPrecision, entry.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001954
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001955 for (uint32_t i = 0; i < entry.pointerCount; i++) {
Siarhei Vishniakou09a8fe42022-07-21 17:27:03 -07001956 ALOGD(" Pointer %d: id=%d, toolType=%s, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001957 "x=%f, y=%f, pressure=%f, size=%f, "
1958 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
1959 "orientation=%f",
Siarhei Vishniakou09a8fe42022-07-21 17:27:03 -07001960 i, entry.pointerProperties[i].id,
1961 ftl::enum_string(entry.pointerProperties[i].toolType).c_str(),
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001962 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
1963 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
1964 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
1965 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
1966 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
1967 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
1968 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
1969 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
1970 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
1971 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001972 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001973}
1974
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001975void InputDispatcher::dispatchEventLocked(nsecs_t currentTime,
1976 std::shared_ptr<EventEntry> eventEntry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001977 const std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001978 ATRACE_CALL();
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001979 if (DEBUG_DISPATCH_CYCLE) {
1980 ALOGD("dispatchEventToCurrentInputTargets");
1981 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001982
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00001983 processInteractionsLocked(*eventEntry, inputTargets);
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00001984
Michael Wrightd02c5b62014-02-10 15:10:22 -08001985 ALOG_ASSERT(eventEntry->dispatchInProgress); // should already have been set to true
1986
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001987 pokeUserActivityLocked(*eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001988
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001989 for (const InputTarget& inputTarget : inputTargets) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07001990 std::shared_ptr<Connection> connection =
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07001991 getConnectionLocked(inputTarget.inputChannel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07001992 if (connection != nullptr) {
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08001993 prepareDispatchCycleLocked(currentTime, connection, eventEntry, inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001994 } else {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001995 if (DEBUG_FOCUS) {
1996 ALOGD("Dropping event delivery to target with channel '%s' because it "
1997 "is no longer registered with the input dispatcher.",
1998 inputTarget.inputChannel->getName().c_str());
1999 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002000 }
2001 }
2002}
2003
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07002004void InputDispatcher::cancelEventsForAnrLocked(const std::shared_ptr<Connection>& connection) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002005 // We will not be breaking any connections here, even if the policy wants us to abort dispatch.
2006 // If the policy decides to close the app, we will get a channel removal event via
2007 // unregisterInputChannel, and will clean up the connection that way. We are already not
2008 // sending new pointers to the connection when it blocked, but focused events will continue to
2009 // pile up.
2010 ALOGW("Canceling events for %s because it is unresponsive",
2011 connection->inputChannel->getName().c_str());
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08002012 if (connection->status == Connection::Status::NORMAL) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00002013 CancelationOptions options(CancelationOptions::Mode::CANCEL_ALL_EVENTS,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002014 "application not responding");
2015 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002016 }
2017}
2018
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002019void InputDispatcher::resetNoFocusedWindowTimeoutLocked() {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002020 if (DEBUG_FOCUS) {
2021 ALOGD("Resetting ANR timeouts.");
2022 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002023
2024 // Reset input target wait timeout.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002025 mNoFocusedWindowTimeoutTime = std::nullopt;
Chris Yea209fde2020-07-22 13:54:51 -07002026 mAwaitedFocusedApplication.reset();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002027}
2028
Tiger Huang721e26f2018-07-24 22:26:19 +08002029/**
2030 * Get the display id that the given event should go to. If this event specifies a valid display id,
2031 * then it should be dispatched to that display. Otherwise, the event goes to the focused display.
2032 * Focused display is the display that the user most recently interacted with.
2033 */
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002034int32_t InputDispatcher::getTargetDisplayId(const EventEntry& entry) {
Tiger Huang721e26f2018-07-24 22:26:19 +08002035 int32_t displayId;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002036 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002037 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002038 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
2039 displayId = keyEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002040 break;
2041 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002042 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002043 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
2044 displayId = motionEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002045 break;
2046 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00002047 case EventEntry::Type::TOUCH_MODE_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08002048 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002049 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002050 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07002051 case EventEntry::Type::DEVICE_RESET:
arthurhungb89ccb02020-12-30 16:19:01 +08002052 case EventEntry::Type::SENSOR:
2053 case EventEntry::Type::DRAG: {
Dominik Laskowski75788452021-02-09 18:51:25 -08002054 ALOGE("%s events do not have a target display", ftl::enum_string(entry.type).c_str());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002055 return ADISPLAY_ID_NONE;
2056 }
Tiger Huang721e26f2018-07-24 22:26:19 +08002057 }
2058 return displayId == ADISPLAY_ID_NONE ? mFocusedDisplayId : displayId;
2059}
2060
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002061bool InputDispatcher::shouldWaitToSendKeyLocked(nsecs_t currentTime,
2062 const char* focusedWindowName) {
2063 if (mAnrTracker.empty()) {
2064 // already processed all events that we waited for
2065 mKeyIsWaitingForEventsTimeout = std::nullopt;
2066 return false;
2067 }
2068
2069 if (!mKeyIsWaitingForEventsTimeout.has_value()) {
2070 // Start the timer
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00002071 // Wait to send key because there are unprocessed events that may cause focus to change
Siarhei Vishniakou70622952020-07-30 11:17:23 -05002072 mKeyIsWaitingForEventsTimeout = currentTime +
2073 std::chrono::duration_cast<std::chrono::nanoseconds>(KEY_WAITING_FOR_EVENTS_TIMEOUT)
2074 .count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002075 return true;
2076 }
2077
2078 // We still have pending events, and already started the timer
2079 if (currentTime < *mKeyIsWaitingForEventsTimeout) {
2080 return true; // Still waiting
2081 }
2082
2083 // Waited too long, and some connection still hasn't processed all motions
2084 // Just send the key to the focused window
2085 ALOGW("Dispatching key to %s even though there are other unprocessed events",
2086 focusedWindowName);
2087 mKeyIsWaitingForEventsTimeout = std::nullopt;
2088 return false;
2089}
2090
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002091sp<WindowInfoHandle> InputDispatcher::findFocusedWindowTargetLocked(
2092 nsecs_t currentTime, const EventEntry& entry, nsecs_t* nextWakeupTime,
2093 InputEventInjectionResult& outInjectionResult) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002094 std::string reason;
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002095 outInjectionResult = InputEventInjectionResult::FAILED; // Default result
Michael Wrightd02c5b62014-02-10 15:10:22 -08002096
Tiger Huang721e26f2018-07-24 22:26:19 +08002097 int32_t displayId = getTargetDisplayId(entry);
chaviw98318de2021-05-19 16:45:23 -05002098 sp<WindowInfoHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Chris Yea209fde2020-07-22 13:54:51 -07002099 std::shared_ptr<InputApplicationHandle> focusedApplicationHandle =
Tiger Huang721e26f2018-07-24 22:26:19 +08002100 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
2101
Michael Wrightd02c5b62014-02-10 15:10:22 -08002102 // If there is no currently focused window and no focused application
2103 // then drop the event.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002104 if (focusedWindowHandle == nullptr && focusedApplicationHandle == nullptr) {
2105 ALOGI("Dropping %s event because there is no focused window or focused application in "
2106 "display %" PRId32 ".",
Dominik Laskowski75788452021-02-09 18:51:25 -08002107 ftl::enum_string(entry.type).c_str(), displayId);
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002108 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002109 }
2110
Vishnu Nair062a8672021-09-03 16:07:44 -07002111 // Drop key events if requested by input feature
2112 if (focusedWindowHandle != nullptr && shouldDropInput(entry, focusedWindowHandle)) {
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002113 return nullptr;
Vishnu Nair062a8672021-09-03 16:07:44 -07002114 }
2115
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002116 // Compatibility behavior: raise ANR if there is a focused application, but no focused window.
2117 // Only start counting when we have a focused event to dispatch. The ANR is canceled if we
2118 // start interacting with another application via touch (app switch). This code can be removed
2119 // if the "no focused window ANR" is moved to the policy. Input doesn't know whether
2120 // an app is expected to have a focused window.
2121 if (focusedWindowHandle == nullptr && focusedApplicationHandle != nullptr) {
2122 if (!mNoFocusedWindowTimeoutTime.has_value()) {
2123 // We just discovered that there's no focused window. Start the ANR timer
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05002124 std::chrono::nanoseconds timeout = focusedApplicationHandle->getDispatchingTimeout(
2125 DEFAULT_INPUT_DISPATCHING_TIMEOUT);
2126 mNoFocusedWindowTimeoutTime = currentTime + timeout.count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002127 mAwaitedFocusedApplication = focusedApplicationHandle;
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05002128 mAwaitedApplicationDisplayId = displayId;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002129 ALOGW("Waiting because no window has focus but %s may eventually add a "
2130 "window when it finishes starting up. Will wait for %" PRId64 "ms",
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05002131 mAwaitedFocusedApplication->getName().c_str(), millis(timeout));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002132 *nextWakeupTime = *mNoFocusedWindowTimeoutTime;
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002133 outInjectionResult = InputEventInjectionResult::PENDING;
2134 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002135 } else if (currentTime > *mNoFocusedWindowTimeoutTime) {
2136 // Already raised ANR. Drop the event
2137 ALOGE("Dropping %s event because there is no focused window",
Dominik Laskowski75788452021-02-09 18:51:25 -08002138 ftl::enum_string(entry.type).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002139 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002140 } else {
2141 // Still waiting for the focused window
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002142 outInjectionResult = InputEventInjectionResult::PENDING;
2143 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002144 }
2145 }
2146
2147 // we have a valid, non-null focused window
2148 resetNoFocusedWindowTimeoutLocked();
2149
Prabir Pradhan5735a322022-04-11 17:23:34 +00002150 // Verify targeted injection.
2151 if (const auto err = verifyTargetedInjection(focusedWindowHandle, entry); err) {
2152 ALOGW("Dropping injected event: %s", (*err).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002153 outInjectionResult = InputEventInjectionResult::TARGET_MISMATCH;
2154 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002155 }
2156
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002157 if (focusedWindowHandle->getInfo()->inputConfig.test(
2158 WindowInfo::InputConfig::PAUSE_DISPATCHING)) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002159 ALOGI("Waiting because %s is paused", focusedWindowHandle->getName().c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002160 outInjectionResult = InputEventInjectionResult::PENDING;
2161 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002162 }
2163
2164 // If the event is a key event, then we must wait for all previous events to
2165 // complete before delivering it because previous events may have the
2166 // side-effect of transferring focus to a different window and we want to
2167 // ensure that the following keys are sent to the new window.
2168 //
2169 // Suppose the user touches a button in a window then immediately presses "A".
2170 // If the button causes a pop-up window to appear then we want to ensure that
2171 // the "A" key is delivered to the new pop-up window. This is because users
2172 // often anticipate pending UI changes when typing on a keyboard.
2173 // To obtain this behavior, we must serialize key events with respect to all
2174 // prior input events.
2175 if (entry.type == EventEntry::Type::KEY) {
2176 if (shouldWaitToSendKeyLocked(currentTime, focusedWindowHandle->getName().c_str())) {
2177 *nextWakeupTime = *mKeyIsWaitingForEventsTimeout;
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002178 outInjectionResult = InputEventInjectionResult::PENDING;
2179 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002180 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002181 }
2182
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002183 outInjectionResult = InputEventInjectionResult::SUCCEEDED;
2184 return focusedWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002185}
2186
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002187/**
2188 * Given a list of monitors, remove the ones we cannot find a connection for, and the ones
2189 * that are currently unresponsive.
2190 */
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002191std::vector<Monitor> InputDispatcher::selectResponsiveMonitorsLocked(
2192 const std::vector<Monitor>& monitors) const {
2193 std::vector<Monitor> responsiveMonitors;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002194 std::copy_if(monitors.begin(), monitors.end(), std::back_inserter(responsiveMonitors),
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002195 [this](const Monitor& monitor) REQUIRES(mLock) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07002196 std::shared_ptr<Connection> connection =
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002197 getConnectionLocked(monitor.inputChannel->getConnectionToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002198 if (connection == nullptr) {
2199 ALOGE("Could not find connection for monitor %s",
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002200 monitor.inputChannel->getName().c_str());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002201 return false;
2202 }
2203 if (!connection->responsive) {
2204 ALOGW("Unresponsive monitor %s will not get the new gesture",
2205 connection->inputChannel->getName().c_str());
2206 return false;
2207 }
2208 return true;
2209 });
2210 return responsiveMonitors;
2211}
2212
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07002213/**
2214 * In general, touch should be always split between windows. Some exceptions:
2215 * 1. Don't split touch is if we have an active pointer down, and a new pointer is going down that's
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002216 * from the same device, *and* the window that's receiving the current pointer does not support
2217 * split touch.
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07002218 * 2. Don't split mouse events
2219 */
2220bool InputDispatcher::shouldSplitTouch(const TouchState& touchState,
2221 const MotionEntry& entry) const {
2222 if (isFromSource(entry.source, AINPUT_SOURCE_MOUSE)) {
2223 // We should never split mouse events
2224 return false;
2225 }
2226 for (const TouchedWindow& touchedWindow : touchState.windows) {
2227 if (touchedWindow.windowHandle->getInfo()->isSpy()) {
2228 // Spy windows should not affect whether or not touch is split.
2229 continue;
2230 }
2231 if (touchedWindow.windowHandle->getInfo()->supportsSplitTouch()) {
2232 continue;
2233 }
Arthur Hungc539dbb2022-12-08 07:45:36 +00002234 if (touchedWindow.windowHandle->getInfo()->inputConfig.test(
2235 gui::WindowInfo::InputConfig::IS_WALLPAPER)) {
2236 // Wallpaper window should not affect whether or not touch is split
2237 continue;
2238 }
2239
Siarhei Vishniakou45504fe2023-05-05 16:05:10 -07002240 if (touchedWindow.hasTouchingPointers(entry.deviceId)) {
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07002241 return false;
2242 }
2243 }
2244 return true;
2245}
2246
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002247std::vector<InputTarget> InputDispatcher::findTouchedWindowTargetsLocked(
Siarhei Vishniakou4fe57392022-10-25 13:44:30 -07002248 nsecs_t currentTime, const MotionEntry& entry, bool* outConflictingPointerActions,
2249 InputEventInjectionResult& outInjectionResult) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002250 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002251
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002252 std::vector<InputTarget> targets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002253 // For security reasons, we defer updating the touch state until we are sure that
2254 // event injection will be allowed.
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002255 const int32_t displayId = entry.displayId;
2256 const int32_t action = entry.action;
Siarhei Vishniakoubf880522023-05-01 11:03:22 -07002257 const int32_t maskedAction = MotionEvent::getActionMasked(action);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002258
2259 // Update the touch state as needed based on the properties of the touch event.
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002260 outInjectionResult = InputEventInjectionResult::PENDING;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002261
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002262 // Copy current touch state into tempTouchState.
2263 // This state will be used to update mTouchStatesByDisplay at the end of this function.
2264 // If no state for the specified display exists, then our initial state will be empty.
Yi Kong9b14ac62018-07-17 13:48:38 -07002265 const TouchState* oldState = nullptr;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002266 TouchState tempTouchState;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002267 if (const auto it = mTouchStatesByDisplay.find(displayId); it != mTouchStatesByDisplay.end()) {
2268 oldState = &(it->second);
Prabir Pradhane680f9b2022-02-04 04:24:00 -08002269 tempTouchState = *oldState;
Jeff Brownf086ddb2014-02-11 14:28:48 -08002270 }
2271
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07002272 bool isSplit = shouldSplitTouch(tempTouchState, entry);
Siarhei Vishniakou45504fe2023-05-05 16:05:10 -07002273 bool switchedDevice = false;
2274 if (oldState != nullptr) {
2275 std::set<int32_t> oldActiveDevices = oldState->getActiveDeviceIds();
2276 const bool anotherDeviceIsActive =
2277 oldActiveDevices.count(entry.deviceId) == 0 && !oldActiveDevices.empty();
2278 switchedDevice |= anotherDeviceIsActive;
Siarhei Vishniakou45504fe2023-05-05 16:05:10 -07002279 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002280
2281 const bool isHoverAction = (maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE ||
2282 maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2283 maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT);
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002284 // A DOWN could be generated from POINTER_DOWN if the initial pointers did not land into any
2285 // touchable windows.
2286 const bool wasDown = oldState != nullptr && oldState->isDown();
2287 const bool isDown = (maskedAction == AMOTION_EVENT_ACTION_DOWN) ||
2288 (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN && !wasDown);
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07002289 const bool newGesture = isDown || maskedAction == AMOTION_EVENT_ACTION_SCROLL ||
2290 maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2291 maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE;
Prabir Pradhanaa561d12021-09-24 06:57:33 -07002292 const bool isFromMouse = isFromSource(entry.source, AINPUT_SOURCE_MOUSE);
Siarhei Vishniakou5cee1e32022-11-29 12:35:39 -08002293
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002294 // If pointers are already down, let's finish the current gesture and ignore the new events
2295 // from another device. However, if the new event is a down event, let's cancel the current
2296 // touch and let the new one take over.
2297 if (switchedDevice && wasDown && !isDown) {
Siarhei Vishniakou45504fe2023-05-05 16:05:10 -07002298 LOG(INFO) << "Dropping event because a pointer for another device "
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002299 << " is already down in display " << displayId << ": " << entry.getDescription();
2300 // TODO(b/211379801): test multiple simultaneous input streams.
2301 outInjectionResult = InputEventInjectionResult::FAILED;
2302 return {}; // wrong device
2303 }
2304
Michael Wrightd02c5b62014-02-10 15:10:22 -08002305 if (newGesture) {
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002306 // If a new gesture is starting, clear the touch state completely.
2307 tempTouchState.reset();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002308 isSplit = false;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04002309 } else if (switchedDevice && maskedAction == AMOTION_EVENT_ACTION_MOVE) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07002310 ALOGI("Dropping move event because a pointer for a different device is already active "
2311 "in display %" PRId32,
2312 displayId);
Siarhei Vishniakou16e4fa02023-02-16 17:48:56 -08002313 // TODO(b/211379801): test multiple simultaneous input streams.
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002314 outInjectionResult = InputEventInjectionResult::FAILED;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002315 return {}; // wrong device
Michael Wrightd02c5b62014-02-10 15:10:22 -08002316 }
2317
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002318 if (isHoverAction) {
2319 // For hover actions, we will treat 'tempTouchState' as a new state, so let's erase
2320 // all of the existing hovering pointers and recompute.
2321 tempTouchState.clearHoveringPointers();
2322 }
2323
Michael Wrightd02c5b62014-02-10 15:10:22 -08002324 if (newGesture || (isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN)) {
2325 /* Case 1: New splittable pointer going down, or need target for hover or scroll. */
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07002326 const auto [x, y] = resolveTouchedPosition(entry);
Siarhei Vishniakou5b9766d2023-07-18 14:06:29 -07002327 const int32_t pointerIndex = MotionEvent::getActionIndex(action);
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002328 // Outside targets should be added upon first dispatched DOWN event. That means, this should
2329 // be a pointer that would generate ACTION_DOWN, *and* touch should not already be down.
Prabir Pradhand65552b2021-10-07 11:23:50 -07002330 const bool isStylus = isPointerFromStylus(entry, pointerIndex);
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07002331 sp<WindowInfoHandle> newTouchedWindowHandle =
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002332 findTouchedWindowAtLocked(displayId, x, y, isStylus);
Michael Wright3dd60e22019-03-27 22:06:44 +00002333
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002334 if (isDown) {
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07002335 targets += findOutsideTargetsLocked(displayId, newTouchedWindowHandle);
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002336 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002337 // Handle the case where we did not find a window.
Yi Kong9b14ac62018-07-17 13:48:38 -07002338 if (newTouchedWindowHandle == nullptr) {
Prabir Pradhan82e081e2022-12-06 09:50:09 +00002339 ALOGD("No new touched window at (%.1f, %.1f) in display %" PRId32, x, y, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002340 // Try to assign the pointer to the first foreground window we find, if there is one.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002341 newTouchedWindowHandle = tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002342 }
2343
Prabir Pradhan5735a322022-04-11 17:23:34 +00002344 // Verify targeted injection.
2345 if (const auto err = verifyTargetedInjection(newTouchedWindowHandle, entry); err) {
2346 ALOGW("Dropping injected touch event: %s", (*err).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002347 outInjectionResult = os::InputEventInjectionResult::TARGET_MISMATCH;
Prabir Pradhan5735a322022-04-11 17:23:34 +00002348 newTouchedWindowHandle = nullptr;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002349 return {};
Prabir Pradhan5735a322022-04-11 17:23:34 +00002350 }
2351
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002352 // Figure out whether splitting will be allowed for this window.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002353 if (newTouchedWindowHandle != nullptr) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002354 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
2355 // New window supports splitting, but we should never split mouse events.
2356 isSplit = !isFromMouse;
2357 } else if (isSplit) {
2358 // New window does not support splitting but we have already split events.
2359 // Ignore the new window.
Siarhei Vishniakou25537f82023-07-18 14:35:47 -07002360 LOG(INFO) << "Skipping " << newTouchedWindowHandle->getName()
2361 << " because it doesn't support split touch";
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002362 newTouchedWindowHandle = nullptr;
2363 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002364 } else {
2365 // No window is touched, so set split to true. This will allow the next pointer down to
Prabir Pradhan713bb3e2021-12-20 02:07:40 -08002366 // be delivered to a new window which supports split touch. Pointers from a mouse device
2367 // should never be split.
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07002368 isSplit = !isFromMouse;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002369 }
2370
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002371 std::vector<sp<WindowInfoHandle>> newTouchedWindows =
Prabir Pradhand65552b2021-10-07 11:23:50 -07002372 findTouchedSpyWindowsAtLocked(displayId, x, y, isStylus);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002373 if (newTouchedWindowHandle != nullptr) {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002374 // Process the foreground window first so that it is the first to receive the event.
2375 newTouchedWindows.insert(newTouchedWindows.begin(), newTouchedWindowHandle);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002376 }
2377
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002378 if (newTouchedWindows.empty()) {
Prabir Pradhan82e081e2022-12-06 09:50:09 +00002379 ALOGI("Dropping event because there is no touchable window at (%.1f, %.1f) on display "
2380 "%d.",
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002381 x, y, displayId);
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002382 outInjectionResult = InputEventInjectionResult::FAILED;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002383 return {};
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002384 }
2385
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002386 for (const sp<WindowInfoHandle>& windowHandle : newTouchedWindows) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07002387 if (!canWindowReceiveMotionLocked(windowHandle, entry)) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002388 continue;
2389 }
2390
Siarhei Vishniakoub681c202023-05-01 11:22:33 -07002391 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2392 maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE) {
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002393 const int32_t pointerId = entry.pointerProperties[0].id;
Siarhei Vishniakoub681c202023-05-01 11:22:33 -07002394 // The "windowHandle" is the target of this hovering pointer.
2395 tempTouchState.addHoveringPointerToWindow(windowHandle, entry.deviceId, pointerId);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002396 }
2397
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002398 // Set target flags.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002399 ftl::Flags<InputTarget::Flags> targetFlags = InputTarget::Flags::DISPATCH_AS_IS;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002400
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002401 if (canReceiveForegroundTouches(*windowHandle->getInfo())) {
2402 // There should only be one touched window that can be "foreground" for the pointer.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002403 targetFlags |= InputTarget::Flags::FOREGROUND;
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002404 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002405
2406 if (isSplit) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002407 targetFlags |= InputTarget::Flags::SPLIT;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002408 }
2409 if (isWindowObscuredAtPointLocked(windowHandle, x, y)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002410 targetFlags |= InputTarget::Flags::WINDOW_IS_OBSCURED;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002411 } else if (isWindowObscuredLocked(windowHandle)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002412 targetFlags |= InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002413 }
Michael Wright3dd60e22019-03-27 22:06:44 +00002414
2415 // Update the temporary touch state.
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08002416 std::bitset<MAX_POINTER_ID + 1> pointerIds;
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002417 if (!isHoverAction) {
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08002418 pointerIds.set(entry.pointerProperties[pointerIndex].id);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002419 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002420
Siarhei Vishniakoue0431e42023-01-28 17:01:39 -08002421 const bool isDownOrPointerDown = maskedAction == AMOTION_EVENT_ACTION_DOWN ||
2422 maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN;
2423
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002424 // TODO(b/211379801): Currently, even if pointerIds are empty (hover case), we would
2425 // still add a window to the touch state. We should avoid doing that, but some of the
2426 // later checks ("at least one foreground window") rely on this in order to dispatch
2427 // the event properly, so that needs to be updated, possibly by looking at InputTargets.
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002428 tempTouchState.addOrUpdateWindow(windowHandle, targetFlags, entry.deviceId, pointerIds,
Siarhei Vishniakoue0431e42023-01-28 17:01:39 -08002429 isDownOrPointerDown
2430 ? std::make_optional(entry.eventTime)
2431 : std::nullopt);
Arthur Hungc539dbb2022-12-08 07:45:36 +00002432
2433 // If this is the pointer going down and the touched window has a wallpaper
2434 // then also add the touched wallpaper windows so they are locked in for the duration
2435 // of the touch gesture.
2436 // We do not collect wallpapers during HOVER_MOVE or SCROLL because the wallpaper
2437 // engine only supports touch events. We would need to add a mechanism similar
2438 // to View.onGenericMotionEvent to enable wallpapers to handle these events.
Siarhei Vishniakoue0431e42023-01-28 17:01:39 -08002439 if (isDownOrPointerDown) {
Arthur Hungc539dbb2022-12-08 07:45:36 +00002440 if (targetFlags.test(InputTarget::Flags::FOREGROUND) &&
2441 windowHandle->getInfo()->inputConfig.test(
2442 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER)) {
2443 sp<WindowInfoHandle> wallpaper = findWallpaperWindowBelow(windowHandle);
2444 if (wallpaper != nullptr) {
2445 ftl::Flags<InputTarget::Flags> wallpaperFlags =
2446 InputTarget::Flags::WINDOW_IS_OBSCURED |
2447 InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED |
2448 InputTarget::Flags::DISPATCH_AS_IS;
2449 if (isSplit) {
2450 wallpaperFlags |= InputTarget::Flags::SPLIT;
2451 }
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002452 tempTouchState.addOrUpdateWindow(wallpaper, wallpaperFlags, entry.deviceId,
2453 pointerIds, entry.eventTime);
Arthur Hungc539dbb2022-12-08 07:45:36 +00002454 }
2455 }
2456 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002457 }
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00002458
Siarhei Vishniakou060f82b2023-01-27 06:39:14 -08002459 // If a window is already pilfering some pointers, give it this new pointer as well and
2460 // make it pilfering. This will prevent other non-spy windows from getting this pointer,
2461 // which is a specific behaviour that we want.
2462 const int32_t pointerId = entry.pointerProperties[pointerIndex].id;
2463 for (TouchedWindow& touchedWindow : tempTouchState.windows) {
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002464 if (touchedWindow.hasTouchingPointer(entry.deviceId, pointerId) &&
2465 touchedWindow.hasPilferingPointers(entry.deviceId)) {
Siarhei Vishniakou060f82b2023-01-27 06:39:14 -08002466 // This window is already pilfering some pointers, and this new pointer is also
2467 // going to it. Therefore, take over this pointer and don't give it to anyone
2468 // else.
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002469 touchedWindow.addPilferingPointer(entry.deviceId, pointerId);
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00002470 }
2471 }
Siarhei Vishniakou060f82b2023-01-27 06:39:14 -08002472
2473 // Restrict all pilfered pointers to the pilfering windows.
2474 tempTouchState.cancelPointersForNonPilferingWindows();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002475 } else {
2476 /* Case 2: Pointer move, up, cancel or non-splittable pointer down. */
2477
2478 // If the pointer is not currently down, then ignore the event.
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07002479 if (!tempTouchState.isDown() && maskedAction != AMOTION_EVENT_ACTION_HOVER_EXIT) {
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002480 LOG(INFO) << "Dropping event because the pointer is not down or we previously "
2481 "dropped the pointer down event in display "
2482 << displayId << ": " << entry.getDescription();
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002483 outInjectionResult = InputEventInjectionResult::FAILED;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002484 return {};
Michael Wrightd02c5b62014-02-10 15:10:22 -08002485 }
2486
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07002487 // If the pointer is not currently hovering, then ignore the event.
2488 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT) {
2489 const int32_t pointerId = entry.pointerProperties[0].id;
2490 if (oldState == nullptr ||
2491 oldState->getWindowsWithHoveringPointer(entry.deviceId, pointerId).empty()) {
2492 LOG(INFO) << "Dropping event because the hovering pointer is not in any windows in "
2493 "display "
2494 << displayId << ": " << entry.getDescription();
2495 outInjectionResult = InputEventInjectionResult::FAILED;
2496 return {};
2497 }
2498 tempTouchState.removeHoveringPointer(entry.deviceId, pointerId);
2499 }
2500
arthurhung6d4bed92021-03-17 11:59:33 +08002501 addDragEventLocked(entry);
arthurhungb89ccb02020-12-30 16:19:01 +08002502
Michael Wrightd02c5b62014-02-10 15:10:22 -08002503 // Check whether touches should slip outside of the current foreground window.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002504 if (maskedAction == AMOTION_EVENT_ACTION_MOVE && entry.pointerCount == 1 &&
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002505 tempTouchState.isSlippery()) {
Siarhei Vishniakou9306c382022-09-30 15:30:31 -07002506 const auto [x, y] = resolveTouchedPosition(entry);
Harry Cutts33476232023-01-30 19:57:29 +00002507 const bool isStylus = isPointerFromStylus(entry, /*pointerIndex=*/0);
chaviw98318de2021-05-19 16:45:23 -05002508 sp<WindowInfoHandle> oldTouchedWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002509 tempTouchState.getFirstForegroundWindowHandle();
Siarhei Vishniakou0f6558d2023-04-21 12:05:13 -07002510 LOG_ALWAYS_FATAL_IF(oldTouchedWindowHandle == nullptr);
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07002511 sp<WindowInfoHandle> newTouchedWindowHandle =
2512 findTouchedWindowAtLocked(displayId, x, y, isStylus);
Vishnu Nair062a8672021-09-03 16:07:44 -07002513
Prabir Pradhan5735a322022-04-11 17:23:34 +00002514 // Verify targeted injection.
2515 if (const auto err = verifyTargetedInjection(newTouchedWindowHandle, entry); err) {
2516 ALOGW("Dropping injected event: %s", (*err).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002517 outInjectionResult = os::InputEventInjectionResult::TARGET_MISMATCH;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002518 return {};
Prabir Pradhan5735a322022-04-11 17:23:34 +00002519 }
2520
Vishnu Nair062a8672021-09-03 16:07:44 -07002521 // Drop touch events if requested by input feature
2522 if (newTouchedWindowHandle != nullptr &&
2523 shouldDropInput(entry, newTouchedWindowHandle)) {
2524 newTouchedWindowHandle = nullptr;
2525 }
2526
Siarhei Vishniakouafa08cc2023-05-08 22:35:50 -07002527 if (newTouchedWindowHandle != nullptr &&
2528 !haveSameToken(oldTouchedWindowHandle, newTouchedWindowHandle)) {
Siarhei Vishniakou0f6558d2023-04-21 12:05:13 -07002529 ALOGD("Touch is slipping out of window %s into window %s in display %" PRId32,
2530 oldTouchedWindowHandle->getName().c_str(),
2531 newTouchedWindowHandle->getName().c_str(), displayId);
2532
Michael Wrightd02c5b62014-02-10 15:10:22 -08002533 // Make a slippery exit from the old window.
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08002534 std::bitset<MAX_POINTER_ID + 1> pointerIds;
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002535 const int32_t pointerId = entry.pointerProperties[0].id;
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08002536 pointerIds.set(pointerId);
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002537
2538 const TouchedWindow& touchedWindow =
2539 tempTouchState.getTouchedWindow(oldTouchedWindowHandle);
2540 addWindowTargetLocked(oldTouchedWindowHandle,
2541 InputTarget::Flags::DISPATCH_AS_SLIPPERY_EXIT, pointerIds,
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002542 touchedWindow.getDownTimeInTarget(entry.deviceId), targets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002543
2544 // Make a slippery entrance into the new window.
2545 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
Prabir Pradhan713bb3e2021-12-20 02:07:40 -08002546 isSplit = !isFromMouse;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002547 }
2548
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002549 ftl::Flags<InputTarget::Flags> targetFlags =
2550 InputTarget::Flags::DISPATCH_AS_SLIPPERY_ENTER;
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002551 if (canReceiveForegroundTouches(*newTouchedWindowHandle->getInfo())) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002552 targetFlags |= InputTarget::Flags::FOREGROUND;
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002553 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002554 if (isSplit) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002555 targetFlags |= InputTarget::Flags::SPLIT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002556 }
2557 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002558 targetFlags |= InputTarget::Flags::WINDOW_IS_OBSCURED;
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002559 } else if (isWindowObscuredLocked(newTouchedWindowHandle)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002560 targetFlags |= InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002561 }
2562
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002563 tempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags,
2564 entry.deviceId, pointerIds, entry.eventTime);
Arthur Hungc539dbb2022-12-08 07:45:36 +00002565
2566 // Check if the wallpaper window should deliver the corresponding event.
2567 slipWallpaperTouch(targetFlags, oldTouchedWindowHandle, newTouchedWindowHandle,
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002568 tempTouchState, entry.deviceId, pointerId, targets);
2569 tempTouchState.removeTouchingPointerFromWindow(entry.deviceId, pointerId,
2570 oldTouchedWindowHandle);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002571 }
2572 }
Arthur Hung96483742022-11-15 03:30:48 +00002573
2574 // Update the pointerIds for non-splittable when it received pointer down.
2575 if (!isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN) {
2576 // If no split, we suppose all touched windows should receive pointer down.
Siarhei Vishniakou5b9766d2023-07-18 14:06:29 -07002577 const int32_t pointerIndex = MotionEvent::getActionIndex(action);
Arthur Hung96483742022-11-15 03:30:48 +00002578 for (size_t i = 0; i < tempTouchState.windows.size(); i++) {
2579 TouchedWindow& touchedWindow = tempTouchState.windows[i];
2580 // Ignore drag window for it should just track one pointer.
2581 if (mDragState && mDragState->dragWindow == touchedWindow.windowHandle) {
2582 continue;
2583 }
Siarhei Vishniakou5b9766d2023-07-18 14:06:29 -07002584 std::bitset<MAX_POINTER_ID + 1> touchingPointers;
2585 touchingPointers.set(entry.pointerProperties[pointerIndex].id);
2586 touchedWindow.addTouchingPointers(entry.deviceId, touchingPointers);
Arthur Hung96483742022-11-15 03:30:48 +00002587 }
2588 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002589 }
2590
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002591 // Update dispatching for hover enter and exit.
Sam Dubeyf886dec2023-01-27 13:28:19 +00002592 {
2593 std::vector<TouchedWindow> hoveringWindows =
2594 getHoveringWindowsLocked(oldState, tempTouchState, entry);
2595 for (const TouchedWindow& touchedWindow : hoveringWindows) {
Siarhei Vishniakoud5876ba2023-05-15 17:58:34 -07002596 std::optional<InputTarget> target =
2597 createInputTargetLocked(touchedWindow.windowHandle, touchedWindow.targetFlags,
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002598 touchedWindow.getDownTimeInTarget(entry.deviceId));
Siarhei Vishniakoud5876ba2023-05-15 17:58:34 -07002599 if (!target) {
2600 continue;
2601 }
2602 // Hardcode to single hovering pointer for now.
2603 std::bitset<MAX_POINTER_ID + 1> pointerIds;
2604 pointerIds.set(entry.pointerProperties[0].id);
2605 target->addPointers(pointerIds, touchedWindow.windowHandle->getInfo()->transform);
2606 targets.push_back(*target);
Sam Dubeyf886dec2023-01-27 13:28:19 +00002607 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002608 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002609
Prabir Pradhan5735a322022-04-11 17:23:34 +00002610 // Ensure that all touched windows are valid for injection.
2611 if (entry.injectionState != nullptr) {
2612 std::string errs;
2613 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Prabir Pradhan5735a322022-04-11 17:23:34 +00002614 const auto err = verifyTargetedInjection(touchedWindow.windowHandle, entry);
2615 if (err) errs += "\n - " + *err;
2616 }
2617 if (!errs.empty()) {
2618 ALOGW("Dropping targeted injection: At least one touched window is not owned by uid "
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00002619 "%s:%s",
2620 entry.injectionState->targetUid->toString().c_str(), errs.c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002621 outInjectionResult = InputEventInjectionResult::TARGET_MISMATCH;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002622 return {};
Prabir Pradhan5735a322022-04-11 17:23:34 +00002623 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002624 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002625
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002626 // Check whether windows listening for outside touches are owned by the same UID. If the owner
2627 // has a different UID, then we will not reveal coordinate information to this window.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002628 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
chaviw98318de2021-05-19 16:45:23 -05002629 sp<WindowInfoHandle> foregroundWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002630 tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002631 if (foregroundWindowHandle) {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00002632 const auto foregroundWindowUid = foregroundWindowHandle->getInfo()->ownerUid;
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002633 for (InputTarget& target : targets) {
2634 if (target.flags.test(InputTarget::Flags::DISPATCH_AS_OUTSIDE)) {
2635 sp<WindowInfoHandle> targetWindow =
2636 getWindowHandleLocked(target.inputChannel->getConnectionToken());
2637 if (targetWindow->getInfo()->ownerUid != foregroundWindowUid) {
2638 target.flags |= InputTarget::Flags::ZERO_COORDS;
Michael Wright3dd60e22019-03-27 22:06:44 +00002639 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002640 }
2641 }
2642 }
2643 }
2644
Harry Cuttsb166c002023-05-09 13:06:05 +00002645 // If this is a touchpad navigation gesture, it needs to only be sent to trusted targets, as we
2646 // only want the system UI to handle these gestures.
2647 const bool isTouchpadNavGesture = isFromSource(entry.source, AINPUT_SOURCE_MOUSE) &&
2648 entry.classification == MotionClassification::MULTI_FINGER_SWIPE;
2649 if (isTouchpadNavGesture) {
2650 filterUntrustedTargets(/* byref */ tempTouchState, /* byref */ targets);
2651 }
2652
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07002653 // Output targets from the touch state.
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002654 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002655 if (!touchedWindow.hasTouchingPointers(entry.deviceId) &&
2656 !touchedWindow.hasHoveringPointers(entry.deviceId)) {
Siarhei Vishniakoue0431e42023-01-28 17:01:39 -08002657 // Windows with hovering pointers are getting persisted inside TouchState.
2658 // Do not send this event to those windows.
2659 continue;
2660 }
Harry Cuttsb166c002023-05-09 13:06:05 +00002661
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002662 addWindowTargetLocked(touchedWindow.windowHandle, touchedWindow.targetFlags,
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002663 touchedWindow.getTouchingPointers(entry.deviceId),
2664 touchedWindow.getDownTimeInTarget(entry.deviceId), targets);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002665 }
Sam Dubey39d37cf2022-12-07 18:05:35 +00002666
Siarhei Vishniakou580fb3a2023-05-05 15:02:20 -07002667 // During targeted injection, only allow owned targets to receive events
2668 std::erase_if(targets, [&](const InputTarget& target) {
2669 LOG_ALWAYS_FATAL_IF(target.windowHandle == nullptr);
2670 const auto err = verifyTargetedInjection(target.windowHandle, entry);
2671 if (err) {
2672 LOG(WARNING) << "Dropping injected event from " << target.windowHandle->getName()
2673 << ": " << (*err);
2674 return true;
2675 }
2676 return false;
2677 });
2678
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07002679 if (targets.empty()) {
2680 LOG(INFO) << "Dropping event because no targets were found: " << entry.getDescription();
2681 outInjectionResult = InputEventInjectionResult::FAILED;
2682 return {};
2683 }
2684
2685 // If we only have windows getting ACTION_OUTSIDE, then drop the event, because there is no
2686 // window that is actually receiving the entire gesture.
2687 if (std::all_of(targets.begin(), targets.end(), [](const InputTarget& target) {
2688 return target.flags.test(InputTarget::Flags::DISPATCH_AS_OUTSIDE);
2689 })) {
2690 LOG(INFO) << "Dropping event because all windows would just receive ACTION_OUTSIDE: "
2691 << entry.getDescription();
2692 outInjectionResult = InputEventInjectionResult::FAILED;
2693 return {};
2694 }
2695
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002696 outInjectionResult = InputEventInjectionResult::SUCCEEDED;
Sam Dubeyf886dec2023-01-27 13:28:19 +00002697 // Drop the outside or hover touch windows since we will not care about them
2698 // in the next iteration.
2699 tempTouchState.filterNonAsIsTouchWindows();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002700
Michael Wrightd02c5b62014-02-10 15:10:22 -08002701 // Update final pieces of touch state if the injector had permission.
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002702 if (switchedDevice) {
2703 if (DEBUG_FOCUS) {
2704 ALOGD("Conflicting pointer actions: Switched to a different device.");
2705 }
2706 *outConflictingPointerActions = true;
2707 }
2708
2709 if (isHoverAction) {
2710 // Started hovering, therefore no longer down.
Siarhei Vishniakou3ad385b2022-11-04 10:09:53 -07002711 if (oldState && oldState->isDown()) {
Siarhei Vishniakou6e1e9872022-11-08 17:51:35 -08002712 ALOGD_IF(DEBUG_FOCUS,
2713 "Conflicting pointer actions: Hover received while pointer was down.");
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002714 *outConflictingPointerActions = true;
2715 }
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002716 } else if (maskedAction == AMOTION_EVENT_ACTION_UP) {
2717 // Pointer went up.
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002718 tempTouchState.removeTouchingPointer(entry.deviceId, entry.pointerProperties[0].id);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002719 } else if (maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002720 // All pointers up or canceled.
2721 tempTouchState.reset();
2722 } else if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
2723 // First pointer went down.
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002724 if (oldState && (oldState->isDown() || oldState->hasHoveringPointers())) {
2725 ALOGD("Conflicting pointer actions: Down received while already down or hovering.");
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002726 *outConflictingPointerActions = true;
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002727 }
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002728 } else if (maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
2729 // One pointer went up.
Siarhei Vishniakou5b9766d2023-07-18 14:06:29 -07002730 const int32_t pointerIndex = MotionEvent::getActionIndex(action);
2731 const uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
2732 tempTouchState.removeTouchingPointer(entry.deviceId, pointerId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002733 }
2734
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002735 // Save changes unless the action was scroll in which case the temporary touch
2736 // state was only valid for this one action.
2737 if (maskedAction != AMOTION_EVENT_ACTION_SCROLL) {
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07002738 if (displayId >= 0) {
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002739 tempTouchState.clearWindowsWithoutPointers();
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002740 mTouchStatesByDisplay[displayId] = tempTouchState;
2741 } else {
2742 mTouchStatesByDisplay.erase(displayId);
2743 }
2744 }
2745
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -08002746 if (tempTouchState.windows.empty()) {
2747 mTouchStatesByDisplay.erase(displayId);
2748 }
2749
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002750 return targets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002751}
2752
arthurhung6d4bed92021-03-17 11:59:33 +08002753void InputDispatcher::finishDragAndDrop(int32_t displayId, float x, float y) {
Prabir Pradhand65552b2021-10-07 11:23:50 -07002754 // Prevent stylus interceptor windows from affecting drag and drop behavior for now, until we
2755 // have an explicit reason to support it.
2756 constexpr bool isStylus = false;
2757
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07002758 sp<WindowInfoHandle> dropWindow =
Harry Cutts33476232023-01-30 19:57:29 +00002759 findTouchedWindowAtLocked(displayId, x, y, isStylus, /*ignoreDragWindow=*/true);
arthurhung6d4bed92021-03-17 11:59:33 +08002760 if (dropWindow) {
2761 vec2 local = dropWindow->getInfo()->transform.transform(x, y);
Prabir Pradhancef936d2021-07-21 16:17:52 +00002762 sendDropWindowCommandLocked(dropWindow->getToken(), local.x, local.y);
Arthur Hung6d0571e2021-04-09 20:18:16 +08002763 } else {
Arthur Hung54745652022-04-20 07:17:41 +00002764 ALOGW("No window found when drop.");
Prabir Pradhancef936d2021-07-21 16:17:52 +00002765 sendDropWindowCommandLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08002766 }
2767 mDragState.reset();
2768}
2769
2770void InputDispatcher::addDragEventLocked(const MotionEntry& entry) {
Arthur Hung3915c1f2022-05-31 07:17:17 +00002771 if (!mDragState || mDragState->dragWindow->getInfo()->displayId != entry.displayId) {
arthurhungb89ccb02020-12-30 16:19:01 +08002772 return;
2773 }
2774
arthurhung6d4bed92021-03-17 11:59:33 +08002775 if (!mDragState->isStartDrag) {
2776 mDragState->isStartDrag = true;
2777 mDragState->isStylusButtonDownAtStart =
2778 (entry.buttonState & AMOTION_EVENT_BUTTON_STYLUS_PRIMARY) != 0;
2779 }
2780
Arthur Hung54745652022-04-20 07:17:41 +00002781 // Find the pointer index by id.
2782 int32_t pointerIndex = 0;
2783 for (; static_cast<uint32_t>(pointerIndex) < entry.pointerCount; pointerIndex++) {
2784 const PointerProperties& pointerProperties = entry.pointerProperties[pointerIndex];
2785 if (pointerProperties.id == mDragState->pointerId) {
2786 break;
arthurhung6d4bed92021-03-17 11:59:33 +08002787 }
Arthur Hung54745652022-04-20 07:17:41 +00002788 }
arthurhung6d4bed92021-03-17 11:59:33 +08002789
Arthur Hung54745652022-04-20 07:17:41 +00002790 if (uint32_t(pointerIndex) == entry.pointerCount) {
2791 LOG_ALWAYS_FATAL("Should find a valid pointer index by id %d", mDragState->pointerId);
Arthur Hung54745652022-04-20 07:17:41 +00002792 }
2793
2794 const int32_t maskedAction = entry.action & AMOTION_EVENT_ACTION_MASK;
2795 const int32_t x = entry.pointerCoords[pointerIndex].getX();
2796 const int32_t y = entry.pointerCoords[pointerIndex].getY();
2797
2798 switch (maskedAction) {
2799 case AMOTION_EVENT_ACTION_MOVE: {
2800 // Handle the special case : stylus button no longer pressed.
2801 bool isStylusButtonDown =
2802 (entry.buttonState & AMOTION_EVENT_BUTTON_STYLUS_PRIMARY) != 0;
2803 if (mDragState->isStylusButtonDownAtStart && !isStylusButtonDown) {
2804 finishDragAndDrop(entry.displayId, x, y);
2805 return;
2806 }
2807
2808 // Prevent stylus interceptor windows from affecting drag and drop behavior for now,
2809 // until we have an explicit reason to support it.
2810 constexpr bool isStylus = false;
2811
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07002812 sp<WindowInfoHandle> hoverWindowHandle =
2813 findTouchedWindowAtLocked(entry.displayId, x, y, isStylus,
2814 /*ignoreDragWindow=*/true);
Arthur Hung54745652022-04-20 07:17:41 +00002815 // enqueue drag exit if needed.
2816 if (hoverWindowHandle != mDragState->dragHoverWindowHandle &&
2817 !haveSameToken(hoverWindowHandle, mDragState->dragHoverWindowHandle)) {
2818 if (mDragState->dragHoverWindowHandle != nullptr) {
Harry Cutts33476232023-01-30 19:57:29 +00002819 enqueueDragEventLocked(mDragState->dragHoverWindowHandle, /*isExiting=*/true, x,
Arthur Hung54745652022-04-20 07:17:41 +00002820 y);
2821 }
2822 mDragState->dragHoverWindowHandle = hoverWindowHandle;
2823 }
2824 // enqueue drag location if needed.
2825 if (hoverWindowHandle != nullptr) {
Harry Cutts33476232023-01-30 19:57:29 +00002826 enqueueDragEventLocked(hoverWindowHandle, /*isExiting=*/false, x, y);
Arthur Hung54745652022-04-20 07:17:41 +00002827 }
2828 break;
2829 }
2830
2831 case AMOTION_EVENT_ACTION_POINTER_UP:
Siarhei Vishniakou5b9766d2023-07-18 14:06:29 -07002832 if (MotionEvent::getActionIndex(entry.action) != pointerIndex) {
Arthur Hung54745652022-04-20 07:17:41 +00002833 break;
2834 }
2835 // The drag pointer is up.
2836 [[fallthrough]];
2837 case AMOTION_EVENT_ACTION_UP:
2838 finishDragAndDrop(entry.displayId, x, y);
2839 break;
2840 case AMOTION_EVENT_ACTION_CANCEL: {
2841 ALOGD("Receiving cancel when drag and drop.");
2842 sendDropWindowCommandLocked(nullptr, 0, 0);
2843 mDragState.reset();
2844 break;
2845 }
arthurhungb89ccb02020-12-30 16:19:01 +08002846 }
2847}
2848
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002849std::optional<InputTarget> InputDispatcher::createInputTargetLocked(
2850 const sp<android::gui::WindowInfoHandle>& windowHandle,
2851 ftl::Flags<InputTarget::Flags> targetFlags,
2852 std::optional<nsecs_t> firstDownTimeInTarget) const {
2853 std::shared_ptr<InputChannel> inputChannel = getInputChannelLocked(windowHandle->getToken());
2854 if (inputChannel == nullptr) {
2855 ALOGW("Not creating InputTarget for %s, no input channel", windowHandle->getName().c_str());
2856 return {};
2857 }
2858 InputTarget inputTarget;
2859 inputTarget.inputChannel = inputChannel;
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00002860 inputTarget.windowHandle = windowHandle;
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002861 inputTarget.flags = targetFlags;
2862 inputTarget.globalScaleFactor = windowHandle->getInfo()->globalScaleFactor;
2863 inputTarget.firstDownTimeInTarget = firstDownTimeInTarget;
2864 const auto& displayInfoIt = mDisplayInfos.find(windowHandle->getInfo()->displayId);
2865 if (displayInfoIt != mDisplayInfos.end()) {
2866 inputTarget.displayTransform = displayInfoIt->second.transform;
2867 } else {
Siarhei Vishniakou580fb3a2023-05-05 15:02:20 -07002868 // DisplayInfo not found for this window on display windowHandle->getInfo()->displayId.
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002869 // TODO(b/198444055): Make this an error message after 'setInputWindows' API is removed.
2870 }
2871 return inputTarget;
2872}
2873
chaviw98318de2021-05-19 16:45:23 -05002874void InputDispatcher::addWindowTargetLocked(const sp<WindowInfoHandle>& windowHandle,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002875 ftl::Flags<InputTarget::Flags> targetFlags,
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08002876 std::bitset<MAX_POINTER_ID + 1> pointerIds,
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002877 std::optional<nsecs_t> firstDownTimeInTarget,
Siarhei Vishniakouf75cddb2022-10-25 10:42:16 -07002878 std::vector<InputTarget>& inputTargets) const {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002879 std::vector<InputTarget>::iterator it =
2880 std::find_if(inputTargets.begin(), inputTargets.end(),
2881 [&windowHandle](const InputTarget& inputTarget) {
2882 return inputTarget.inputChannel->getConnectionToken() ==
2883 windowHandle->getToken();
2884 });
Chavi Weingarten97b8eec2020-01-09 18:09:08 +00002885
chaviw98318de2021-05-19 16:45:23 -05002886 const WindowInfo* windowInfo = windowHandle->getInfo();
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002887
2888 if (it == inputTargets.end()) {
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002889 std::optional<InputTarget> target =
2890 createInputTargetLocked(windowHandle, targetFlags, firstDownTimeInTarget);
2891 if (!target) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002892 return;
2893 }
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002894 inputTargets.push_back(*target);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002895 it = inputTargets.end() - 1;
2896 }
2897
2898 ALOG_ASSERT(it->flags == targetFlags);
2899 ALOG_ASSERT(it->globalScaleFactor == windowInfo->globalScaleFactor);
2900
chaviw1ff3d1e2020-07-01 15:53:47 -07002901 it->addPointers(pointerIds, windowInfo->transform);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002902}
2903
Michael Wright3dd60e22019-03-27 22:06:44 +00002904void InputDispatcher::addGlobalMonitoringTargetsLocked(std::vector<InputTarget>& inputTargets,
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002905 int32_t displayId) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002906 auto monitorsIt = mGlobalMonitorsByDisplay.find(displayId);
2907 if (monitorsIt == mGlobalMonitorsByDisplay.end()) return;
Michael Wright3dd60e22019-03-27 22:06:44 +00002908
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002909 for (const Monitor& monitor : selectResponsiveMonitorsLocked(monitorsIt->second)) {
2910 InputTarget target;
2911 target.inputChannel = monitor.inputChannel;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002912 target.flags = InputTarget::Flags::DISPATCH_AS_IS;
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002913 // target.firstDownTimeInTarget is not set for global monitors. It is only required in split
2914 // touch and global monitoring works as intended even without setting firstDownTimeInTarget
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002915 if (const auto& it = mDisplayInfos.find(displayId); it != mDisplayInfos.end()) {
2916 target.displayTransform = it->second.transform;
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002917 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002918 target.setDefaultPointerTransform(target.displayTransform);
2919 inputTargets.push_back(target);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002920 }
2921}
2922
Robert Carrc9bf1d32020-04-13 17:21:08 -07002923/**
2924 * Indicate whether one window handle should be considered as obscuring
2925 * another window handle. We only check a few preconditions. Actually
2926 * checking the bounds is left to the caller.
2927 */
chaviw98318de2021-05-19 16:45:23 -05002928static bool canBeObscuredBy(const sp<WindowInfoHandle>& windowHandle,
2929 const sp<WindowInfoHandle>& otherHandle) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002930 // Compare by token so cloned layers aren't counted
2931 if (haveSameToken(windowHandle, otherHandle)) {
2932 return false;
2933 }
2934 auto info = windowHandle->getInfo();
2935 auto otherInfo = otherHandle->getInfo();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002936 if (otherInfo->inputConfig.test(WindowInfo::InputConfig::NOT_VISIBLE)) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002937 return false;
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002938 } else if (otherInfo->alpha == 0 &&
2939 otherInfo->inputConfig.test(WindowInfo::InputConfig::NOT_TOUCHABLE)) {
Bernardo Rufino653d2e02020-10-20 17:32:40 +00002940 // Those act as if they were invisible, so we don't need to flag them.
2941 // We do want to potentially flag touchable windows even if they have 0
2942 // opacity, since they can consume touches and alter the effects of the
2943 // user interaction (eg. apps that rely on
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002944 // Flags::WINDOW_IS_PARTIALLY_OBSCURED should still be told about those
Bernardo Rufino653d2e02020-10-20 17:32:40 +00002945 // windows), hence we also check for FLAG_NOT_TOUCHABLE.
2946 return false;
Bernardo Rufino8007daf2020-09-22 09:40:01 +00002947 } else if (info->ownerUid == otherInfo->ownerUid) {
2948 // If ownerUid is the same we don't generate occlusion events as there
2949 // is no security boundary within an uid.
Robert Carrc9bf1d32020-04-13 17:21:08 -07002950 return false;
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002951 } else if (otherInfo->inputConfig.test(gui::WindowInfo::InputConfig::TRUSTED_OVERLAY)) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002952 return false;
2953 } else if (otherInfo->displayId != info->displayId) {
2954 return false;
2955 }
2956 return true;
2957}
2958
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002959/**
2960 * Returns touch occlusion information in the form of TouchOcclusionInfo. To check if the touch is
2961 * untrusted, one should check:
2962 *
2963 * 1. If result.hasBlockingOcclusion is true.
2964 * If it's, it means the touch should be blocked due to a window with occlusion mode of
2965 * BLOCK_UNTRUSTED.
2966 *
2967 * 2. If result.obscuringOpacity > mMaximumObscuringOpacityForTouch.
2968 * If it is (and 1 is false), then the touch should be blocked because a stack of windows
2969 * (possibly only one) with occlusion mode of USE_OPACITY from one UID resulted in a composed
2970 * obscuring opacity above the threshold. Note that if there was no window of occlusion mode
2971 * USE_OPACITY, result.obscuringOpacity would've been 0 and since
2972 * mMaximumObscuringOpacityForTouch >= 0, the condition above would never be true.
2973 *
2974 * If neither of those is true, then it means the touch can be allowed.
2975 */
2976InputDispatcher::TouchOcclusionInfo InputDispatcher::computeTouchOcclusionInfoLocked(
chaviw98318de2021-05-19 16:45:23 -05002977 const sp<WindowInfoHandle>& windowHandle, int32_t x, int32_t y) const {
2978 const WindowInfo* windowInfo = windowHandle->getInfo();
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002979 int32_t displayId = windowInfo->displayId;
chaviw98318de2021-05-19 16:45:23 -05002980 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002981 TouchOcclusionInfo info;
2982 info.hasBlockingOcclusion = false;
2983 info.obscuringOpacity = 0;
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00002984 info.obscuringUid = gui::Uid::INVALID;
2985 std::map<gui::Uid, float> opacityByUid;
chaviw98318de2021-05-19 16:45:23 -05002986 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002987 if (windowHandle == otherHandle) {
2988 break; // All future windows are below us. Exit early.
2989 }
chaviw98318de2021-05-19 16:45:23 -05002990 const WindowInfo* otherInfo = otherHandle->getInfo();
Bernardo Rufino1ff9d592021-01-18 16:58:57 +00002991 if (canBeObscuredBy(windowHandle, otherHandle) && otherInfo->frameContainsPoint(x, y) &&
2992 !haveSameApplicationToken(windowInfo, otherInfo)) {
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002993 if (DEBUG_TOUCH_OCCLUSION) {
2994 info.debugInfo.push_back(
Harry Cutts101ee9b2023-07-06 18:04:14 +00002995 dumpWindowForTouchOcclusion(otherInfo, /*isTouchedWindow=*/false));
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002996 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002997 // canBeObscuredBy() has returned true above, which means this window is untrusted, so
2998 // we perform the checks below to see if the touch can be propagated or not based on the
2999 // window's touch occlusion mode
3000 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::BLOCK_UNTRUSTED) {
3001 info.hasBlockingOcclusion = true;
3002 info.obscuringUid = otherInfo->ownerUid;
3003 info.obscuringPackage = otherInfo->packageName;
3004 break;
3005 }
3006 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::USE_OPACITY) {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003007 const auto uid = otherInfo->ownerUid;
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003008 float opacity =
3009 (opacityByUid.find(uid) == opacityByUid.end()) ? 0 : opacityByUid[uid];
3010 // Given windows A and B:
3011 // opacity(A, B) = 1 - [1 - opacity(A)] * [1 - opacity(B)]
3012 opacity = 1 - (1 - opacity) * (1 - otherInfo->alpha);
3013 opacityByUid[uid] = opacity;
3014 if (opacity > info.obscuringOpacity) {
3015 info.obscuringOpacity = opacity;
3016 info.obscuringUid = uid;
3017 info.obscuringPackage = otherInfo->packageName;
3018 }
3019 }
3020 }
3021 }
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00003022 if (DEBUG_TOUCH_OCCLUSION) {
Harry Cutts101ee9b2023-07-06 18:04:14 +00003023 info.debugInfo.push_back(dumpWindowForTouchOcclusion(windowInfo, /*isTouchedWindow=*/true));
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00003024 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003025 return info;
3026}
3027
chaviw98318de2021-05-19 16:45:23 -05003028std::string InputDispatcher::dumpWindowForTouchOcclusion(const WindowInfo* info,
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00003029 bool isTouchedWindow) const {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003030 return StringPrintf(INDENT2 "* %spackage=%s/%s, id=%" PRId32 ", mode=%s, alpha=%.2f, "
Prabir Pradhan51e7db02022-02-07 06:02:57 -08003031 "frame=[%" PRId32 ",%" PRId32 "][%" PRId32 ",%" PRId32
3032 "], touchableRegion=%s, window={%s}, inputConfig={%s}, "
3033 "hasToken=%s, applicationInfo.name=%s, applicationInfo.token=%s\n",
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08003034 isTouchedWindow ? "[TOUCHED] " : "", info->packageName.c_str(),
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003035 info->ownerUid.toString().c_str(), info->id,
Chavi Weingarten7f019192023-08-08 20:39:01 +00003036 toString(info->touchOcclusionMode).c_str(), info->alpha, info->frame.left,
3037 info->frame.top, info->frame.right, info->frame.bottom,
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003038 dumpRegion(info->touchableRegion).c_str(), info->name.c_str(),
3039 info->inputConfig.string().c_str(), toString(info->token != nullptr),
3040 info->applicationInfo.name.c_str(),
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07003041 binderToString(info->applicationInfo.token).c_str());
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00003042}
3043
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003044bool InputDispatcher::isTouchTrustedLocked(const TouchOcclusionInfo& occlusionInfo) const {
3045 if (occlusionInfo.hasBlockingOcclusion) {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003046 ALOGW("Untrusted touch due to occlusion by %s/%s", occlusionInfo.obscuringPackage.c_str(),
3047 occlusionInfo.obscuringUid.toString().c_str());
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003048 return false;
3049 }
3050 if (occlusionInfo.obscuringOpacity > mMaximumObscuringOpacityForTouch) {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003051 ALOGW("Untrusted touch due to occlusion by %s/%s (obscuring opacity = "
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003052 "%.2f, maximum allowed = %.2f)",
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003053 occlusionInfo.obscuringPackage.c_str(), occlusionInfo.obscuringUid.toString().c_str(),
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003054 occlusionInfo.obscuringOpacity, mMaximumObscuringOpacityForTouch);
3055 return false;
3056 }
3057 return true;
3058}
3059
chaviw98318de2021-05-19 16:45:23 -05003060bool InputDispatcher::isWindowObscuredAtPointLocked(const sp<WindowInfoHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003061 int32_t x, int32_t y) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003062 int32_t displayId = windowHandle->getInfo()->displayId;
chaviw98318de2021-05-19 16:45:23 -05003063 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
3064 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07003065 if (windowHandle == otherHandle) {
3066 break; // All future windows are below us. Exit early.
Michael Wrightd02c5b62014-02-10 15:10:22 -08003067 }
chaviw98318de2021-05-19 16:45:23 -05003068 const WindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07003069 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08003070 otherInfo->frameContainsPoint(x, y)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003071 return true;
3072 }
3073 }
3074 return false;
3075}
3076
chaviw98318de2021-05-19 16:45:23 -05003077bool InputDispatcher::isWindowObscuredLocked(const sp<WindowInfoHandle>& windowHandle) const {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07003078 int32_t displayId = windowHandle->getInfo()->displayId;
chaviw98318de2021-05-19 16:45:23 -05003079 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
3080 const WindowInfo* windowInfo = windowHandle->getInfo();
3081 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07003082 if (windowHandle == otherHandle) {
3083 break; // All future windows are below us. Exit early.
Michael Wrightcdcd8f22016-03-22 16:52:13 -07003084 }
chaviw98318de2021-05-19 16:45:23 -05003085 const WindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07003086 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08003087 otherInfo->overlaps(windowInfo)) {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07003088 return true;
3089 }
3090 }
3091 return false;
3092}
3093
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08003094std::string InputDispatcher::getApplicationWindowLabel(
chaviw98318de2021-05-19 16:45:23 -05003095 const InputApplicationHandle* applicationHandle, const sp<WindowInfoHandle>& windowHandle) {
Yi Kong9b14ac62018-07-17 13:48:38 -07003096 if (applicationHandle != nullptr) {
3097 if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07003098 return applicationHandle->getName() + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003099 } else {
3100 return applicationHandle->getName();
3101 }
Yi Kong9b14ac62018-07-17 13:48:38 -07003102 } else if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07003103 return windowHandle->getInfo()->applicationInfo.name + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003104 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003105 return "<unknown application or window>";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003106 }
3107}
3108
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003109void InputDispatcher::pokeUserActivityLocked(const EventEntry& eventEntry) {
Antonio Kantekf16f2832021-09-28 04:39:20 +00003110 if (!isUserActivityEvent(eventEntry)) {
3111 // Not poking user activity if the event type does not represent a user activity
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003112 return;
3113 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003114 int32_t displayId = getTargetDisplayId(eventEntry);
chaviw98318de2021-05-19 16:45:23 -05003115 sp<WindowInfoHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Josep del Riob3981622023-04-18 15:49:45 +00003116 const WindowInfo* windowDisablingUserActivityInfo = nullptr;
Tiger Huang721e26f2018-07-24 22:26:19 +08003117 if (focusedWindowHandle != nullptr) {
chaviw98318de2021-05-19 16:45:23 -05003118 const WindowInfo* info = focusedWindowHandle->getInfo();
Prabir Pradhan51e7db02022-02-07 06:02:57 -08003119 if (info->inputConfig.test(WindowInfo::InputConfig::DISABLE_USER_ACTIVITY)) {
Josep del Riob3981622023-04-18 15:49:45 +00003120 windowDisablingUserActivityInfo = info;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003121 }
3122 }
3123
3124 int32_t eventType = USER_ACTIVITY_EVENT_OTHER;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003125 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003126 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003127 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
3128 if (motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003129 return;
3130 }
Josep del Riob3981622023-04-18 15:49:45 +00003131 if (windowDisablingUserActivityInfo != nullptr) {
3132 if (DEBUG_DISPATCH_CYCLE) {
3133 ALOGD("Not poking user activity: disabled by window '%s'.",
3134 windowDisablingUserActivityInfo->name.c_str());
3135 }
3136 return;
3137 }
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003138 if (MotionEvent::isTouchEvent(motionEntry.source, motionEntry.action)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003139 eventType = USER_ACTIVITY_EVENT_TOUCH;
3140 }
3141 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003142 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003143 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003144 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
3145 if (keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003146 return;
3147 }
Josep del Riob3981622023-04-18 15:49:45 +00003148 // If the key code is unknown, we don't consider it user activity
3149 if (keyEntry.keyCode == AKEYCODE_UNKNOWN) {
3150 return;
3151 }
3152 // Don't inhibit events that were intercepted or are not passed to
3153 // the apps, like system shortcuts
3154 if (windowDisablingUserActivityInfo != nullptr &&
3155 keyEntry.interceptKeyResult != KeyEntry::InterceptKeyResult::SKIP &&
3156 keyEntry.policyFlags & POLICY_FLAG_PASS_TO_USER) {
3157 if (DEBUG_DISPATCH_CYCLE) {
3158 ALOGD("Not poking user activity: disabled by window '%s'.",
3159 windowDisablingUserActivityInfo->name.c_str());
3160 }
3161 return;
3162 }
3163
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003164 eventType = USER_ACTIVITY_EVENT_BUTTON;
3165 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003166 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00003167 default: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003168 LOG_ALWAYS_FATAL("%s events are not user activity",
Dominik Laskowski75788452021-02-09 18:51:25 -08003169 ftl::enum_string(eventEntry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003170 break;
3171 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003172 }
3173
Prabir Pradhancef936d2021-07-21 16:17:52 +00003174 auto command = [this, eventTime = eventEntry.eventTime, eventType, displayId]()
3175 REQUIRES(mLock) {
3176 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00003177 mPolicy.pokeUserActivity(eventTime, eventType, displayId);
Prabir Pradhancef936d2021-07-21 16:17:52 +00003178 };
3179 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003180}
3181
3182void InputDispatcher::prepareDispatchCycleLocked(nsecs_t currentTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003183 const std::shared_ptr<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003184 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003185 const InputTarget& inputTarget) {
Prabir Pradhan2dac8b82023-09-06 01:11:51 +00003186 ATRACE_NAME_IF(ATRACE_ENABLED(),
3187 StringPrintf("prepareDispatchCycleLocked(inputChannel=%s, id=0x%" PRIx32 ")",
3188 connection->getInputChannelName().c_str(), eventEntry->id));
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003189 if (DEBUG_DISPATCH_CYCLE) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003190 ALOGD("channel '%s' ~ prepareDispatchCycle - flags=%s, "
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08003191 "globalScaleFactor=%f, pointerIds=%s %s",
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003192 connection->getInputChannelName().c_str(), inputTarget.flags.string().c_str(),
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08003193 inputTarget.globalScaleFactor, bitsetToString(inputTarget.pointerIds).c_str(),
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003194 inputTarget.getPointerInfoString().c_str());
3195 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003196
3197 // Skip this event if the connection status is not normal.
3198 // We don't want to enqueue additional outbound events if the connection is broken.
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003199 if (connection->status != Connection::Status::NORMAL) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003200 if (DEBUG_DISPATCH_CYCLE) {
3201 ALOGD("channel '%s' ~ Dropping event because the channel status is %s",
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003202 connection->getInputChannelName().c_str(),
3203 ftl::enum_string(connection->status).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003204 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003205 return;
3206 }
3207
3208 // Split a motion event if needed.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003209 if (inputTarget.flags.test(InputTarget::Flags::SPLIT)) {
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003210 LOG_ALWAYS_FATAL_IF(eventEntry->type != EventEntry::Type::MOTION,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003211 "Entry type %s should not have Flags::SPLIT",
Dominik Laskowski75788452021-02-09 18:51:25 -08003212 ftl::enum_string(eventEntry->type).c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003213
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003214 const MotionEntry& originalMotionEntry = static_cast<const MotionEntry&>(*eventEntry);
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003215 if (inputTarget.pointerIds.count() != originalMotionEntry.pointerCount) {
Siarhei Vishniakou16e4fa02023-02-16 17:48:56 -08003216 if (!inputTarget.firstDownTimeInTarget.has_value()) {
3217 logDispatchStateLocked();
3218 LOG(FATAL) << "Splitting motion events requires a down time to be set for the "
3219 "target on connection "
3220 << connection->getInputChannelName() << " for "
3221 << originalMotionEntry.getDescription();
3222 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003223 std::unique_ptr<MotionEntry> splitMotionEntry =
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00003224 splitMotionEvent(originalMotionEntry, inputTarget.pointerIds,
3225 inputTarget.firstDownTimeInTarget.value());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003226 if (!splitMotionEntry) {
3227 return; // split event was dropped
3228 }
Arthur Hungb3307ee2021-10-14 10:57:37 +00003229 if (splitMotionEntry->action == AMOTION_EVENT_ACTION_CANCEL) {
3230 std::string reason = std::string("reason=pointer cancel on split window");
3231 android_log_event_list(LOGTAG_INPUT_CANCEL)
3232 << connection->getInputChannelName().c_str() << reason << LOG_ID_EVENTS;
3233 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003234 if (DEBUG_FOCUS) {
3235 ALOGD("channel '%s' ~ Split motion event.",
3236 connection->getInputChannelName().c_str());
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003237 logOutboundMotionDetails(" ", *splitMotionEntry);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003238 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003239 enqueueDispatchEntriesLocked(currentTime, connection, std::move(splitMotionEntry),
3240 inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003241 return;
3242 }
3243 }
3244
3245 // Not splitting. Enqueue dispatch entries for the event as is.
3246 enqueueDispatchEntriesLocked(currentTime, connection, eventEntry, inputTarget);
3247}
3248
3249void InputDispatcher::enqueueDispatchEntriesLocked(nsecs_t currentTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003250 const std::shared_ptr<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003251 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003252 const InputTarget& inputTarget) {
Prabir Pradhan2dac8b82023-09-06 01:11:51 +00003253 ATRACE_NAME_IF(ATRACE_ENABLED(),
3254 StringPrintf("enqueueDispatchEntriesLocked(inputChannel=%s, id=0x%" PRIx32 ")",
3255 connection->getInputChannelName().c_str(), eventEntry->id));
Siarhei Vishniakou5cee1e32022-11-29 12:35:39 -08003256 LOG_ALWAYS_FATAL_IF(!inputTarget.flags.any(InputTarget::DISPATCH_MASK),
3257 "No dispatch flags are set for %s", eventEntry->getDescription().c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00003258
hongzuo liu95785e22022-09-06 02:51:35 +00003259 const bool wasEmpty = connection->outboundQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003260
3261 // Enqueue dispatch entries for the requested modes.
chaviw8c9cf542019-03-25 13:02:48 -07003262 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003263 InputTarget::Flags::DISPATCH_AS_HOVER_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07003264 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003265 InputTarget::Flags::DISPATCH_AS_OUTSIDE);
chaviw8c9cf542019-03-25 13:02:48 -07003266 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003267 InputTarget::Flags::DISPATCH_AS_HOVER_ENTER);
chaviw8c9cf542019-03-25 13:02:48 -07003268 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003269 InputTarget::Flags::DISPATCH_AS_IS);
chaviw8c9cf542019-03-25 13:02:48 -07003270 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003271 InputTarget::Flags::DISPATCH_AS_SLIPPERY_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07003272 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003273 InputTarget::Flags::DISPATCH_AS_SLIPPERY_ENTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003274
3275 // If the outbound queue was previously empty, start the dispatch cycle going.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003276 if (wasEmpty && !connection->outboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003277 startDispatchCycleLocked(currentTime, connection);
3278 }
3279}
3280
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003281void InputDispatcher::enqueueDispatchEntryLocked(const std::shared_ptr<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003282 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003283 const InputTarget& inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003284 ftl::Flags<InputTarget::Flags> dispatchMode) {
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 Tan0fc2fa72019-08-29 17:22:15 -07003305 if (!connection->inputState.trackKey(keyEntry, dispatchEntry->resolvedAction,
3306 dispatchEntry->resolvedFlags)) {
Siarhei Vishniakouc94dafe2023-05-26 10:24:19 -07003307 LOG(WARNING) << "channel " << connection->getInputChannelName()
3308 << "~ dropping inconsistent event: " << *dispatchEntry;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003309 return; // skip the inconsistent event
3310 }
3311 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003312 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003313
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003314 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003315 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003316 // Assign a default value to dispatchEntry that will never be generated by InputReader,
3317 // and assign a InputDispatcher value if it doesn't change in the if-else chain below.
3318 constexpr int32_t DEFAULT_RESOLVED_EVENT_ID =
3319 static_cast<int32_t>(IdGenerator::Source::OTHER);
3320 dispatchEntry->resolvedEventId = DEFAULT_RESOLVED_EVENT_ID;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003321 if (dispatchMode.test(InputTarget::Flags::DISPATCH_AS_OUTSIDE)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003322 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_OUTSIDE;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003323 } else if (dispatchMode.test(InputTarget::Flags::DISPATCH_AS_HOVER_EXIT)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003324 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_EXIT;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003325 } else if (dispatchMode.test(InputTarget::Flags::DISPATCH_AS_HOVER_ENTER)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003326 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003327 } else if (dispatchMode.test(InputTarget::Flags::DISPATCH_AS_SLIPPERY_EXIT)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003328 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_CANCEL;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003329 } else if (dispatchMode.test(InputTarget::Flags::DISPATCH_AS_SLIPPERY_ENTER)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003330 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_DOWN;
3331 } else {
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003332 dispatchEntry->resolvedEventId = motionEntry.id;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003333 }
3334 if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_HOVER_MOVE &&
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003335 !connection->inputState.isHovering(motionEntry.deviceId, motionEntry.source,
3336 motionEntry.displayId)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003337 if (DEBUG_DISPATCH_CYCLE) {
3338 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: filling in missing hover "
3339 "enter event",
3340 connection->getInputChannelName().c_str());
3341 }
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00003342 // We keep the 'resolvedEventId' here equal to the original 'motionEntry.id' because
3343 // this is a one-to-one event conversion.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003344 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
3345 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003346
Siarhei Vishniakou1ae72f12023-01-29 12:55:30 -08003347 if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_CANCEL) {
3348 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_CANCELED;
3349 }
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003350 if (dispatchEntry->targetFlags.test(InputTarget::Flags::WINDOW_IS_OBSCURED)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003351 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED;
3352 }
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003353 if (dispatchEntry->targetFlags.test(InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003354 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
3355 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003356
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003357 if (!connection->inputState.trackMotion(motionEntry, dispatchEntry->resolvedAction,
3358 dispatchEntry->resolvedFlags)) {
Siarhei Vishniakouc94dafe2023-05-26 10:24:19 -07003359 LOG(WARNING) << "channel " << connection->getInputChannelName()
3360 << "~ dropping inconsistent event: " << *dispatchEntry;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003361 return; // skip the inconsistent event
3362 }
3363
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003364 dispatchEntry->resolvedEventId =
3365 dispatchEntry->resolvedEventId == DEFAULT_RESOLVED_EVENT_ID
3366 ? mIdGenerator.nextId()
3367 : motionEntry.id;
3368 if (ATRACE_ENABLED() && dispatchEntry->resolvedEventId != motionEntry.id) {
3369 std::string message = StringPrintf("Transmute MotionEvent(id=0x%" PRIx32
3370 ") to MotionEvent(id=0x%" PRIx32 ").",
3371 motionEntry.id, dispatchEntry->resolvedEventId);
3372 ATRACE_NAME(message.c_str());
3373 }
3374
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08003375 if ((motionEntry.flags & AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE) &&
3376 (motionEntry.policyFlags & POLICY_FLAG_TRUSTED)) {
3377 // Skip reporting pointer down outside focus to the policy.
3378 break;
3379 }
3380
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003381 dispatchPointerDownOutsideFocus(motionEntry.source, dispatchEntry->resolvedAction,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003382 inputTarget.inputChannel->getConnectionToken());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003383
3384 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003385 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003386 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003387 case EventEntry::Type::TOUCH_MODE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08003388 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
3389 case EventEntry::Type::DRAG: {
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003390 break;
3391 }
Chris Yef59a2f42020-10-16 12:55:26 -07003392 case EventEntry::Type::SENSOR: {
3393 LOG_ALWAYS_FATAL("SENSOR events should not go to apps via input channel");
3394 break;
3395 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003396 case EventEntry::Type::CONFIGURATION_CHANGED:
3397 case EventEntry::Type::DEVICE_RESET: {
3398 LOG_ALWAYS_FATAL("%s events should not go to apps",
Dominik Laskowski75788452021-02-09 18:51:25 -08003399 ftl::enum_string(newEntry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003400 break;
3401 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003402 }
3403
3404 // Remember that we are waiting for this dispatch to complete.
3405 if (dispatchEntry->hasForegroundTarget()) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003406 incrementPendingForegroundDispatches(newEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003407 }
3408
3409 // Enqueue the dispatch entry.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003410 connection->outboundQueue.push_back(dispatchEntry.release());
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003411 traceOutboundQueueLength(*connection);
chaviw8c9cf542019-03-25 13:02:48 -07003412}
3413
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003414/**
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003415 * This function is for debugging and metrics collection. It has two roles.
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003416 *
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003417 * The first role is to log input interaction with windows, which helps determine what the user was
3418 * interacting with. For example, if user is touching launcher, we will see an input_interaction log
3419 * that user started interacting with launcher window, as well as any other window that received
3420 * that gesture, such as the wallpaper or other spy windows. A new input_interaction is only logged
3421 * when the set of tokens that received the event changes. It is not logged again as long as the
3422 * user is interacting with the same windows.
3423 *
3424 * The second role is to track input device activity for metrics collection. For each input event,
3425 * we report the set of UIDs that the input device interacted with to the policy. Unlike for the
3426 * input_interaction logs, the device interaction is reported even when the set of interaction
3427 * tokens do not change.
3428 *
3429 * For these purposes, we do not count ACTION_OUTSIDE, ACTION_UP and ACTION_CANCEL actions as
3430 * interaction. This includes up and cancel events for both keys and motions.
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003431 */
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003432void InputDispatcher::processInteractionsLocked(const EventEntry& entry,
3433 const std::vector<InputTarget>& targets) {
3434 int32_t deviceId;
3435 nsecs_t eventTime;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003436 // Skip ACTION_UP events, and all events other than keys and motions
3437 if (entry.type == EventEntry::Type::KEY) {
3438 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
3439 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
3440 return;
3441 }
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003442 deviceId = keyEntry.deviceId;
3443 eventTime = keyEntry.eventTime;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003444 } else if (entry.type == EventEntry::Type::MOTION) {
3445 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
3446 if (motionEntry.action == AMOTION_EVENT_ACTION_UP ||
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003447 motionEntry.action == AMOTION_EVENT_ACTION_CANCEL ||
3448 MotionEvent::getActionMasked(motionEntry.action) == AMOTION_EVENT_ACTION_POINTER_UP) {
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003449 return;
3450 }
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003451 deviceId = motionEntry.deviceId;
3452 eventTime = motionEntry.eventTime;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003453 } else {
3454 return; // Not a key or a motion
3455 }
3456
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003457 std::set<gui::Uid> interactionUids;
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07003458 std::unordered_set<sp<IBinder>, StrongPointerHash<IBinder>> newConnectionTokens;
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003459 std::vector<std::shared_ptr<Connection>> newConnections;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003460 for (const InputTarget& target : targets) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003461 if (target.flags.test(InputTarget::Flags::DISPATCH_AS_OUTSIDE)) {
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003462 continue; // Skip windows that receive ACTION_OUTSIDE
3463 }
3464
3465 sp<IBinder> token = target.inputChannel->getConnectionToken();
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003466 std::shared_ptr<Connection> connection = getConnectionLocked(token);
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003467 if (connection == nullptr) {
3468 continue;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003469 }
3470 newConnectionTokens.insert(std::move(token));
3471 newConnections.emplace_back(connection);
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003472 if (target.windowHandle) {
3473 interactionUids.emplace(target.windowHandle->getInfo()->ownerUid);
3474 }
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003475 }
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003476
3477 auto command = [this, deviceId, eventTime, uids = std::move(interactionUids)]()
3478 REQUIRES(mLock) {
3479 scoped_unlock unlock(mLock);
3480 mPolicy.notifyDeviceInteraction(deviceId, eventTime, uids);
3481 };
3482 postCommandLocked(std::move(command));
3483
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003484 if (newConnectionTokens == mInteractionConnectionTokens) {
3485 return; // no change
3486 }
3487 mInteractionConnectionTokens = newConnectionTokens;
3488
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003489 std::string targetList;
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003490 for (const std::shared_ptr<Connection>& connection : newConnections) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003491 targetList += connection->getWindowName() + ", ";
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003492 }
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003493 std::string message = "Interaction with: " + targetList;
3494 if (targetList.empty()) {
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003495 message += "<none>";
3496 }
3497 android_log_event_list(LOGTAG_INPUT_INTERACTION) << message << LOG_ID_EVENTS;
3498}
3499
chaviwfd6d3512019-03-25 13:23:49 -07003500void InputDispatcher::dispatchPointerDownOutsideFocus(uint32_t source, int32_t action,
Vishnu Nairad321cd2020-08-20 16:40:21 -07003501 const sp<IBinder>& token) {
chaviw8c9cf542019-03-25 13:02:48 -07003502 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
chaviwfd6d3512019-03-25 13:23:49 -07003503 uint32_t maskedSource = source & AINPUT_SOURCE_CLASS_MASK;
3504 if (maskedSource != AINPUT_SOURCE_CLASS_POINTER || maskedAction != AMOTION_EVENT_ACTION_DOWN) {
chaviw8c9cf542019-03-25 13:02:48 -07003505 return;
3506 }
3507
Vishnu Nairc519ff72021-01-21 08:23:08 -08003508 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07003509 if (focusedToken == token) {
3510 // ignore since token is focused
chaviw8c9cf542019-03-25 13:02:48 -07003511 return;
3512 }
3513
Prabir Pradhancef936d2021-07-21 16:17:52 +00003514 auto command = [this, token]() REQUIRES(mLock) {
3515 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00003516 mPolicy.onPointerDownOutsideFocus(token);
Prabir Pradhancef936d2021-07-21 16:17:52 +00003517 };
3518 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003519}
3520
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003521status_t InputDispatcher::publishMotionEvent(Connection& connection,
3522 DispatchEntry& dispatchEntry) const {
3523 const EventEntry& eventEntry = *(dispatchEntry.eventEntry);
3524 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
3525
3526 PointerCoords scaledCoords[MAX_POINTERS];
3527 const PointerCoords* usingCoords = motionEntry.pointerCoords;
3528
3529 // Set the X and Y offset and X and Y scale depending on the input source.
3530 if ((motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) &&
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003531 !(dispatchEntry.targetFlags.test(InputTarget::Flags::ZERO_COORDS))) {
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003532 float globalScaleFactor = dispatchEntry.globalScaleFactor;
3533 if (globalScaleFactor != 1.0f) {
3534 for (uint32_t i = 0; i < motionEntry.pointerCount; i++) {
3535 scaledCoords[i] = motionEntry.pointerCoords[i];
3536 // Don't apply window scale here since we don't want scale to affect raw
3537 // coordinates. The scale will be sent back to the client and applied
3538 // later when requesting relative coordinates.
Harry Cutts33476232023-01-30 19:57:29 +00003539 scaledCoords[i].scale(globalScaleFactor, /*windowXScale=*/1, /*windowYScale=*/1);
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003540 }
3541 usingCoords = scaledCoords;
3542 }
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003543 } else if (dispatchEntry.targetFlags.test(InputTarget::Flags::ZERO_COORDS)) {
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003544 // We don't want the dispatch target to know the coordinates
3545 for (uint32_t i = 0; i < motionEntry.pointerCount; i++) {
3546 scaledCoords[i].clear();
3547 }
3548 usingCoords = scaledCoords;
3549 }
3550
3551 std::array<uint8_t, 32> hmac = getSignature(motionEntry, dispatchEntry);
3552
3553 // Publish the motion event.
3554 return connection.inputPublisher
3555 .publishMotionEvent(dispatchEntry.seq, dispatchEntry.resolvedEventId,
3556 motionEntry.deviceId, motionEntry.source, motionEntry.displayId,
3557 std::move(hmac), dispatchEntry.resolvedAction,
3558 motionEntry.actionButton, dispatchEntry.resolvedFlags,
3559 motionEntry.edgeFlags, motionEntry.metaState,
3560 motionEntry.buttonState, motionEntry.classification,
3561 dispatchEntry.transform, motionEntry.xPrecision,
3562 motionEntry.yPrecision, motionEntry.xCursorPosition,
3563 motionEntry.yCursorPosition, dispatchEntry.rawTransform,
3564 motionEntry.downTime, motionEntry.eventTime,
3565 motionEntry.pointerCount, motionEntry.pointerProperties,
3566 usingCoords);
3567}
3568
Michael Wrightd02c5b62014-02-10 15:10:22 -08003569void InputDispatcher::startDispatchCycleLocked(nsecs_t currentTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003570 const std::shared_ptr<Connection>& connection) {
Prabir Pradhan2dac8b82023-09-06 01:11:51 +00003571 ATRACE_NAME_IF(ATRACE_ENABLED(),
3572 StringPrintf("startDispatchCycleLocked(inputChannel=%s)",
3573 connection->getInputChannelName().c_str()));
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003574 if (DEBUG_DISPATCH_CYCLE) {
3575 ALOGD("channel '%s' ~ startDispatchCycle", connection->getInputChannelName().c_str());
3576 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003577
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003578 while (connection->status == Connection::Status::NORMAL && !connection->outboundQueue.empty()) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003579 DispatchEntry* dispatchEntry = connection->outboundQueue.front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003580 dispatchEntry->deliveryTime = currentTime;
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003581 const std::chrono::nanoseconds timeout = getDispatchingTimeoutLocked(connection);
Siarhei Vishniakou70622952020-07-30 11:17:23 -05003582 dispatchEntry->timeoutTime = currentTime + timeout.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003583
3584 // Publish the event.
3585 status_t status;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003586 const EventEntry& eventEntry = *(dispatchEntry->eventEntry);
3587 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003588 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003589 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
3590 std::array<uint8_t, 32> hmac = getSignature(keyEntry, *dispatchEntry);
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08003591 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07003592 LOG(INFO) << "Publishing " << *dispatchEntry << " to "
3593 << connection->getInputChannelName();
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08003594 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003595
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003596 // Publish the key event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003597 status = connection->inputPublisher
3598 .publishKeyEvent(dispatchEntry->seq,
3599 dispatchEntry->resolvedEventId, keyEntry.deviceId,
3600 keyEntry.source, keyEntry.displayId,
3601 std::move(hmac), dispatchEntry->resolvedAction,
3602 dispatchEntry->resolvedFlags, keyEntry.keyCode,
3603 keyEntry.scanCode, keyEntry.metaState,
3604 keyEntry.repeatCount, keyEntry.downTime,
3605 keyEntry.eventTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003606 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003607 }
3608
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003609 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08003610 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07003611 LOG(INFO) << "Publishing " << *dispatchEntry << " to "
3612 << connection->getInputChannelName();
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08003613 }
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003614 status = publishMotionEvent(*connection, *dispatchEntry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003615 break;
3616 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003617
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003618 case EventEntry::Type::FOCUS: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003619 const FocusEntry& focusEntry = static_cast<const FocusEntry&>(eventEntry);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003620 status = connection->inputPublisher.publishFocusEvent(dispatchEntry->seq,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003621 focusEntry.id,
Antonio Kantek3cfec7b2021-11-05 18:26:17 -07003622 focusEntry.hasFocus);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003623 break;
3624 }
3625
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003626 case EventEntry::Type::TOUCH_MODE_CHANGED: {
3627 const TouchModeEntry& touchModeEntry =
3628 static_cast<const TouchModeEntry&>(eventEntry);
3629 status = connection->inputPublisher
3630 .publishTouchModeEvent(dispatchEntry->seq, touchModeEntry.id,
3631 touchModeEntry.inTouchMode);
3632
3633 break;
3634 }
3635
Prabir Pradhan99987712020-11-10 18:43:05 -08003636 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
3637 const auto& captureEntry =
3638 static_cast<const PointerCaptureChangedEntry&>(eventEntry);
3639 status = connection->inputPublisher
3640 .publishCaptureEvent(dispatchEntry->seq, captureEntry.id,
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00003641 captureEntry.pointerCaptureRequest.enable);
Prabir Pradhan99987712020-11-10 18:43:05 -08003642 break;
3643 }
3644
arthurhungb89ccb02020-12-30 16:19:01 +08003645 case EventEntry::Type::DRAG: {
3646 const DragEntry& dragEntry = static_cast<const DragEntry&>(eventEntry);
3647 status = connection->inputPublisher.publishDragEvent(dispatchEntry->seq,
3648 dragEntry.id, dragEntry.x,
3649 dragEntry.y,
3650 dragEntry.isExiting);
3651 break;
3652 }
3653
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003654 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07003655 case EventEntry::Type::DEVICE_RESET:
3656 case EventEntry::Type::SENSOR: {
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003657 LOG_ALWAYS_FATAL("Should never start dispatch cycles for %s events",
Dominik Laskowski75788452021-02-09 18:51:25 -08003658 ftl::enum_string(eventEntry.type).c_str());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003659 return;
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003660 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003661 }
3662
3663 // Check the result.
3664 if (status) {
3665 if (status == WOULD_BLOCK) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003666 if (connection->waitQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003667 ALOGE("channel '%s' ~ Could not publish event because the pipe is full. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003668 "This is unexpected because the wait queue is empty, so the pipe "
3669 "should be empty and we shouldn't have any problems writing an "
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +00003670 "event to it, status=%s(%d)",
3671 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3672 status);
Harry Cutts33476232023-01-30 19:57:29 +00003673 abortBrokenDispatchCycleLocked(currentTime, connection, /*notify=*/true);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003674 } else {
3675 // Pipe is full and we are waiting for the app to finish process some events
3676 // before sending more events to it.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003677 if (DEBUG_DISPATCH_CYCLE) {
3678 ALOGD("channel '%s' ~ Could not publish event because the pipe is full, "
3679 "waiting for the application to catch up",
3680 connection->getInputChannelName().c_str());
3681 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003682 }
3683 } else {
3684 ALOGE("channel '%s' ~ Could not publish event due to an unexpected error, "
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +00003685 "status=%s(%d)",
3686 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3687 status);
Harry Cutts33476232023-01-30 19:57:29 +00003688 abortBrokenDispatchCycleLocked(currentTime, connection, /*notify=*/true);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003689 }
3690 return;
3691 }
3692
3693 // Re-enqueue the event on the wait queue.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003694 connection->outboundQueue.erase(std::remove(connection->outboundQueue.begin(),
3695 connection->outboundQueue.end(),
3696 dispatchEntry));
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003697 traceOutboundQueueLength(*connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003698 connection->waitQueue.push_back(dispatchEntry);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003699 if (connection->responsive) {
3700 mAnrTracker.insert(dispatchEntry->timeoutTime,
3701 connection->inputChannel->getConnectionToken());
3702 }
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003703 traceWaitQueueLength(*connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003704 }
3705}
3706
chaviw09c8d2d2020-08-24 15:48:26 -07003707std::array<uint8_t, 32> InputDispatcher::sign(const VerifiedInputEvent& event) const {
3708 size_t size;
3709 switch (event.type) {
3710 case VerifiedInputEvent::Type::KEY: {
3711 size = sizeof(VerifiedKeyEvent);
3712 break;
3713 }
3714 case VerifiedInputEvent::Type::MOTION: {
3715 size = sizeof(VerifiedMotionEvent);
3716 break;
3717 }
3718 }
3719 const uint8_t* start = reinterpret_cast<const uint8_t*>(&event);
3720 return mHmacKeyManager.sign(start, size);
3721}
3722
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003723const std::array<uint8_t, 32> InputDispatcher::getSignature(
3724 const MotionEntry& motionEntry, const DispatchEntry& dispatchEntry) const {
Siarhei Vishniakoubf880522023-05-01 11:03:22 -07003725 const int32_t actionMasked = MotionEvent::getActionMasked(dispatchEntry.resolvedAction);
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003726 if (actionMasked != AMOTION_EVENT_ACTION_UP && actionMasked != AMOTION_EVENT_ACTION_DOWN) {
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003727 // Only sign events up and down events as the purely move events
3728 // are tied to their up/down counterparts so signing would be redundant.
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003729 return INVALID_HMAC;
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003730 }
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003731
3732 VerifiedMotionEvent verifiedEvent =
3733 verifiedMotionEventFromMotionEntry(motionEntry, dispatchEntry.rawTransform);
3734 verifiedEvent.actionMasked = actionMasked;
3735 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_MOTION_EVENT_FLAGS;
3736 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003737}
3738
3739const std::array<uint8_t, 32> InputDispatcher::getSignature(
3740 const KeyEntry& keyEntry, const DispatchEntry& dispatchEntry) const {
3741 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEntry(keyEntry);
3742 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_KEY_EVENT_FLAGS;
3743 verifiedEvent.action = dispatchEntry.resolvedAction;
chaviw09c8d2d2020-08-24 15:48:26 -07003744 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003745}
3746
Michael Wrightd02c5b62014-02-10 15:10:22 -08003747void InputDispatcher::finishDispatchCycleLocked(nsecs_t currentTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003748 const std::shared_ptr<Connection>& connection,
3749 uint32_t seq, bool handled, nsecs_t consumeTime) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003750 if (DEBUG_DISPATCH_CYCLE) {
3751 ALOGD("channel '%s' ~ finishDispatchCycle - seq=%u, handled=%s",
3752 connection->getInputChannelName().c_str(), seq, toString(handled));
3753 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003754
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003755 if (connection->status == Connection::Status::BROKEN ||
3756 connection->status == Connection::Status::ZOMBIE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003757 return;
3758 }
3759
3760 // Notify other system components and prepare to start the next dispatch cycle.
Prabir Pradhancef936d2021-07-21 16:17:52 +00003761 auto command = [this, currentTime, connection, seq, handled, consumeTime]() REQUIRES(mLock) {
3762 doDispatchCycleFinishedCommand(currentTime, connection, seq, handled, consumeTime);
3763 };
3764 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003765}
3766
3767void InputDispatcher::abortBrokenDispatchCycleLocked(nsecs_t currentTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003768 const std::shared_ptr<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003769 bool notify) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003770 if (DEBUG_DISPATCH_CYCLE) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07003771 LOG(INFO) << "channel '" << connection->getInputChannelName() << "'~ " << __func__
3772 << " - notify=" << toString(notify);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003773 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003774
3775 // Clear the dispatch queues.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003776 drainDispatchQueue(connection->outboundQueue);
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003777 traceOutboundQueueLength(*connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003778 drainDispatchQueue(connection->waitQueue);
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003779 traceWaitQueueLength(*connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003780
3781 // The connection appears to be unrecoverably broken.
3782 // Ignore already broken or zombie connections.
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003783 if (connection->status == Connection::Status::NORMAL) {
3784 connection->status = Connection::Status::BROKEN;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003785
3786 if (notify) {
3787 // Notify other system components.
Prabir Pradhancef936d2021-07-21 16:17:52 +00003788 ALOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
3789 connection->getInputChannelName().c_str());
3790
3791 auto command = [this, connection]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00003792 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00003793 mPolicy.notifyInputChannelBroken(connection->inputChannel->getConnectionToken());
Prabir Pradhancef936d2021-07-21 16:17:52 +00003794 };
3795 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003796 }
3797 }
3798}
3799
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003800void InputDispatcher::drainDispatchQueue(std::deque<DispatchEntry*>& queue) {
3801 while (!queue.empty()) {
3802 DispatchEntry* dispatchEntry = queue.front();
3803 queue.pop_front();
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003804 releaseDispatchEntry(dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003805 }
3806}
3807
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003808void InputDispatcher::releaseDispatchEntry(DispatchEntry* dispatchEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003809 if (dispatchEntry->hasForegroundTarget()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003810 decrementPendingForegroundDispatches(*(dispatchEntry->eventEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003811 }
3812 delete dispatchEntry;
3813}
3814
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003815int InputDispatcher::handleReceiveCallback(int events, sp<IBinder> connectionToken) {
3816 std::scoped_lock _l(mLock);
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003817 std::shared_ptr<Connection> connection = getConnectionLocked(connectionToken);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003818 if (connection == nullptr) {
3819 ALOGW("Received looper callback for unknown input channel token %p. events=0x%x",
3820 connectionToken.get(), events);
3821 return 0; // remove the callback
3822 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003823
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003824 bool notify;
3825 if (!(events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP))) {
3826 if (!(events & ALOOPER_EVENT_INPUT)) {
3827 ALOGW("channel '%s' ~ Received spurious callback for unhandled poll event. "
3828 "events=0x%x",
3829 connection->getInputChannelName().c_str(), events);
3830 return 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003831 }
3832
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003833 nsecs_t currentTime = now();
3834 bool gotOne = false;
3835 status_t status = OK;
3836 for (;;) {
3837 Result<InputPublisher::ConsumerResponse> result =
3838 connection->inputPublisher.receiveConsumerResponse();
3839 if (!result.ok()) {
3840 status = result.error().code();
3841 break;
3842 }
3843
3844 if (std::holds_alternative<InputPublisher::Finished>(*result)) {
3845 const InputPublisher::Finished& finish =
3846 std::get<InputPublisher::Finished>(*result);
3847 finishDispatchCycleLocked(currentTime, connection, finish.seq, finish.handled,
3848 finish.consumeTime);
3849 } else if (std::holds_alternative<InputPublisher::Timeline>(*result)) {
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00003850 if (shouldReportMetricsForConnection(*connection)) {
3851 const InputPublisher::Timeline& timeline =
3852 std::get<InputPublisher::Timeline>(*result);
3853 mLatencyTracker
3854 .trackGraphicsLatency(timeline.inputEventId,
3855 connection->inputChannel->getConnectionToken(),
3856 std::move(timeline.graphicsTimeline));
3857 }
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003858 }
3859 gotOne = true;
3860 }
3861 if (gotOne) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00003862 runCommandsLockedInterruptable();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003863 if (status == WOULD_BLOCK) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003864 return 1;
3865 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003866 }
3867
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003868 notify = status != DEAD_OBJECT || !connection->monitor;
3869 if (notify) {
3870 ALOGE("channel '%s' ~ Failed to receive finished signal. status=%s(%d)",
3871 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3872 status);
3873 }
3874 } else {
3875 // Monitor channels are never explicitly unregistered.
3876 // We do it automatically when the remote endpoint is closed so don't warn about them.
3877 const bool stillHaveWindowHandle =
3878 getWindowHandleLocked(connection->inputChannel->getConnectionToken()) != nullptr;
3879 notify = !connection->monitor && stillHaveWindowHandle;
3880 if (notify) {
3881 ALOGW("channel '%s' ~ Consumer closed input channel or an error occurred. events=0x%x",
3882 connection->getInputChannelName().c_str(), events);
3883 }
3884 }
3885
3886 // Remove the channel.
3887 removeInputChannelLocked(connection->inputChannel->getConnectionToken(), notify);
3888 return 0; // remove the callback
Michael Wrightd02c5b62014-02-10 15:10:22 -08003889}
3890
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003891void InputDispatcher::synthesizeCancelationEventsForAllConnectionsLocked(
Michael Wrightd02c5b62014-02-10 15:10:22 -08003892 const CancelationOptions& options) {
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003893 for (const auto& [token, connection] : mConnectionsByToken) {
Siarhei Vishniakou2e2ea992020-12-15 02:57:19 +00003894 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003895 }
3896}
3897
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003898void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
Michael Wrightfa13dcf2015-06-12 13:25:11 +01003899 const CancelationOptions& options) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08003900 for (const auto& [_, monitors] : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003901 for (const Monitor& monitor : monitors) {
3902 synthesizeCancelationEventsForInputChannelLocked(monitor.inputChannel, options);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003903 }
Michael Wrightfa13dcf2015-06-12 13:25:11 +01003904 }
3905}
3906
Michael Wrightd02c5b62014-02-10 15:10:22 -08003907void InputDispatcher::synthesizeCancelationEventsForInputChannelLocked(
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05003908 const std::shared_ptr<InputChannel>& channel, const CancelationOptions& options) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003909 std::shared_ptr<Connection> connection = getConnectionLocked(channel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003910 if (connection == nullptr) {
3911 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003912 }
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003913
3914 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003915}
3916
3917void InputDispatcher::synthesizeCancelationEventsForConnectionLocked(
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003918 const std::shared_ptr<Connection>& connection, const CancelationOptions& options) {
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003919 if (connection->status == Connection::Status::BROKEN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003920 return;
3921 }
3922
3923 nsecs_t currentTime = now();
3924
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003925 std::vector<std::unique_ptr<EventEntry>> cancelationEvents =
Siarhei Vishniakou00fca7c2019-10-29 13:05:57 -07003926 connection->inputState.synthesizeCancelationEvents(currentTime, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003927
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003928 if (cancelationEvents.empty()) {
3929 return;
3930 }
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003931 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
3932 ALOGD("channel '%s' ~ Synthesized %zu cancelation events to bring channel back in sync "
Siarhei Vishniakou2e3e4432023-02-09 18:34:11 -08003933 "with reality: %s, mode=%s.",
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003934 connection->getInputChannelName().c_str(), cancelationEvents.size(), options.reason,
Siarhei Vishniakou2e3e4432023-02-09 18:34:11 -08003935 ftl::enum_string(options.mode).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003936 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08003937
Arthur Hungb3307ee2021-10-14 10:57:37 +00003938 std::string reason = std::string("reason=").append(options.reason);
3939 android_log_event_list(LOGTAG_INPUT_CANCEL)
3940 << connection->getInputChannelName().c_str() << reason << LOG_ID_EVENTS;
3941
Svet Ganov5d3bc372020-01-26 23:11:07 -08003942 InputTarget target;
chaviw98318de2021-05-19 16:45:23 -05003943 sp<WindowInfoHandle> windowHandle =
Svet Ganov5d3bc372020-01-26 23:11:07 -08003944 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
3945 if (windowHandle != nullptr) {
chaviw98318de2021-05-19 16:45:23 -05003946 const WindowInfo* windowInfo = windowHandle->getInfo();
chaviw1ff3d1e2020-07-01 15:53:47 -07003947 target.setDefaultPointerTransform(windowInfo->transform);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003948 target.globalScaleFactor = windowInfo->globalScaleFactor;
3949 }
3950 target.inputChannel = connection->inputChannel;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003951 target.flags = InputTarget::Flags::DISPATCH_AS_IS;
Svet Ganov5d3bc372020-01-26 23:11:07 -08003952
hongzuo liu95785e22022-09-06 02:51:35 +00003953 const bool wasEmpty = connection->outboundQueue.empty();
3954
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003955 for (size_t i = 0; i < cancelationEvents.size(); i++) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003956 std::unique_ptr<EventEntry> cancelationEventEntry = std::move(cancelationEvents[i]);
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003957 switch (cancelationEventEntry->type) {
3958 case EventEntry::Type::KEY: {
3959 logOutboundKeyDetails("cancel - ",
3960 static_cast<const KeyEntry&>(*cancelationEventEntry));
3961 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003962 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003963 case EventEntry::Type::MOTION: {
3964 logOutboundMotionDetails("cancel - ",
3965 static_cast<const MotionEntry&>(*cancelationEventEntry));
3966 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003967 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003968 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003969 case EventEntry::Type::TOUCH_MODE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08003970 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
3971 case EventEntry::Type::DRAG: {
Prabir Pradhan99987712020-11-10 18:43:05 -08003972 LOG_ALWAYS_FATAL("Canceling %s events is not supported",
Dominik Laskowski75788452021-02-09 18:51:25 -08003973 ftl::enum_string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003974 break;
3975 }
3976 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07003977 case EventEntry::Type::DEVICE_RESET:
3978 case EventEntry::Type::SENSOR: {
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003979 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Dominik Laskowski75788452021-02-09 18:51:25 -08003980 ftl::enum_string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003981 break;
3982 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003983 }
3984
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003985 enqueueDispatchEntryLocked(connection, std::move(cancelationEventEntry), target,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003986 InputTarget::Flags::DISPATCH_AS_IS);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003987 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003988
hongzuo liu95785e22022-09-06 02:51:35 +00003989 // If the outbound queue was previously empty, start the dispatch cycle going.
3990 if (wasEmpty && !connection->outboundQueue.empty()) {
3991 startDispatchCycleLocked(currentTime, connection);
3992 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003993}
3994
Svet Ganov5d3bc372020-01-26 23:11:07 -08003995void InputDispatcher::synthesizePointerDownEventsForConnectionLocked(
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003996 const nsecs_t downTime, const std::shared_ptr<Connection>& connection,
Arthur Hungc539dbb2022-12-08 07:45:36 +00003997 ftl::Flags<InputTarget::Flags> targetFlags) {
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003998 if (connection->status == Connection::Status::BROKEN) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003999 return;
4000 }
4001
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004002 std::vector<std::unique_ptr<EventEntry>> downEvents =
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00004003 connection->inputState.synthesizePointerDownEvents(downTime);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004004
4005 if (downEvents.empty()) {
4006 return;
4007 }
4008
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004009 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08004010 ALOGD("channel '%s' ~ Synthesized %zu down events to ensure consistent event stream.",
4011 connection->getInputChannelName().c_str(), downEvents.size());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004012 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08004013
4014 InputTarget target;
chaviw98318de2021-05-19 16:45:23 -05004015 sp<WindowInfoHandle> windowHandle =
Svet Ganov5d3bc372020-01-26 23:11:07 -08004016 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
4017 if (windowHandle != nullptr) {
chaviw98318de2021-05-19 16:45:23 -05004018 const WindowInfo* windowInfo = windowHandle->getInfo();
chaviw1ff3d1e2020-07-01 15:53:47 -07004019 target.setDefaultPointerTransform(windowInfo->transform);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004020 target.globalScaleFactor = windowInfo->globalScaleFactor;
4021 }
4022 target.inputChannel = connection->inputChannel;
Arthur Hungc539dbb2022-12-08 07:45:36 +00004023 target.flags = targetFlags;
Svet Ganov5d3bc372020-01-26 23:11:07 -08004024
hongzuo liu95785e22022-09-06 02:51:35 +00004025 const bool wasEmpty = connection->outboundQueue.empty();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004026 for (std::unique_ptr<EventEntry>& downEventEntry : downEvents) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08004027 switch (downEventEntry->type) {
4028 case EventEntry::Type::MOTION: {
4029 logOutboundMotionDetails("down - ",
4030 static_cast<const MotionEntry&>(*downEventEntry));
4031 break;
4032 }
4033
4034 case EventEntry::Type::KEY:
4035 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07004036 case EventEntry::Type::TOUCH_MODE_CHANGED:
Svet Ganov5d3bc372020-01-26 23:11:07 -08004037 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08004038 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07004039 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08004040 case EventEntry::Type::SENSOR:
4041 case EventEntry::Type::DRAG: {
Svet Ganov5d3bc372020-01-26 23:11:07 -08004042 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Dominik Laskowski75788452021-02-09 18:51:25 -08004043 ftl::enum_string(downEventEntry->type).c_str());
Svet Ganov5d3bc372020-01-26 23:11:07 -08004044 break;
4045 }
4046 }
4047
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004048 enqueueDispatchEntryLocked(connection, std::move(downEventEntry), target,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08004049 InputTarget::Flags::DISPATCH_AS_IS);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004050 }
4051
hongzuo liu95785e22022-09-06 02:51:35 +00004052 // If the outbound queue was previously empty, start the dispatch cycle going.
4053 if (wasEmpty && !connection->outboundQueue.empty()) {
4054 startDispatchCycleLocked(downTime, connection);
4055 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08004056}
4057
Arthur Hungc539dbb2022-12-08 07:45:36 +00004058void InputDispatcher::synthesizeCancelationEventsForWindowLocked(
4059 const sp<WindowInfoHandle>& windowHandle, const CancelationOptions& options) {
4060 if (windowHandle != nullptr) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07004061 std::shared_ptr<Connection> wallpaperConnection =
4062 getConnectionLocked(windowHandle->getToken());
Arthur Hungc539dbb2022-12-08 07:45:36 +00004063 if (wallpaperConnection != nullptr) {
4064 synthesizeCancelationEventsForConnectionLocked(wallpaperConnection, options);
4065 }
4066 }
4067}
4068
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004069std::unique_ptr<MotionEntry> InputDispatcher::splitMotionEvent(
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08004070 const MotionEntry& originalMotionEntry, std::bitset<MAX_POINTER_ID + 1> pointerIds,
4071 nsecs_t splitDownTime) {
4072 ALOG_ASSERT(pointerIds.any());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004073
4074 uint32_t splitPointerIndexMap[MAX_POINTERS];
4075 PointerProperties splitPointerProperties[MAX_POINTERS];
4076 PointerCoords splitPointerCoords[MAX_POINTERS];
4077
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07004078 uint32_t originalPointerCount = originalMotionEntry.pointerCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004079 uint32_t splitPointerCount = 0;
4080
4081 for (uint32_t originalPointerIndex = 0; originalPointerIndex < originalPointerCount;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004082 originalPointerIndex++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004083 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07004084 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08004085 uint32_t pointerId = uint32_t(pointerProperties.id);
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08004086 if (pointerIds.test(pointerId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004087 splitPointerIndexMap[splitPointerCount] = originalPointerIndex;
Siarhei Vishniakou73e6d372023-07-06 18:07:21 -07004088 splitPointerProperties[splitPointerCount] = pointerProperties;
4089 splitPointerCoords[splitPointerCount] =
4090 originalMotionEntry.pointerCoords[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08004091 splitPointerCount += 1;
4092 }
4093 }
4094
4095 if (splitPointerCount != pointerIds.count()) {
4096 // This is bad. We are missing some of the pointers that we expected to deliver.
4097 // Most likely this indicates that we received an ACTION_MOVE events that has
4098 // different pointer ids than we expected based on the previous ACTION_DOWN
4099 // or ACTION_POINTER_DOWN events that caused us to decide to split the pointers
4100 // in this way.
4101 ALOGW("Dropping split motion event because the pointer count is %d but "
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08004102 "we expected there to be %zu pointers. This probably means we received "
Siarhei Vishniakou16e4fa02023-02-16 17:48:56 -08004103 "a broken sequence of pointer ids from the input device: %s",
4104 splitPointerCount, pointerIds.count(), originalMotionEntry.getDescription().c_str());
Yi Kong9b14ac62018-07-17 13:48:38 -07004105 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004106 }
4107
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07004108 int32_t action = originalMotionEntry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004109 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004110 if (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN ||
4111 maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
Siarhei Vishniakou5b9766d2023-07-18 14:06:29 -07004112 int32_t originalPointerIndex = MotionEvent::getActionIndex(action);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004113 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07004114 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08004115 uint32_t pointerId = uint32_t(pointerProperties.id);
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08004116 if (pointerIds.test(pointerId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004117 if (pointerIds.count() == 1) {
4118 // The first/last pointer went down/up.
4119 action = maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004120 ? AMOTION_EVENT_ACTION_DOWN
arthurhungea3f4fc2020-12-21 23:18:53 +08004121 : (originalMotionEntry.flags & AMOTION_EVENT_FLAG_CANCELED) != 0
4122 ? AMOTION_EVENT_ACTION_CANCEL
4123 : AMOTION_EVENT_ACTION_UP;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004124 } else {
4125 // A secondary pointer went down/up.
4126 uint32_t splitPointerIndex = 0;
4127 while (pointerId != uint32_t(splitPointerProperties[splitPointerIndex].id)) {
4128 splitPointerIndex += 1;
4129 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004130 action = maskedAction |
4131 (splitPointerIndex << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004132 }
4133 } else {
4134 // An unrelated pointer changed.
4135 action = AMOTION_EVENT_ACTION_MOVE;
4136 }
4137 }
4138
Siarhei Vishniakou59e302b2023-06-05 08:04:53 -07004139 if (action == AMOTION_EVENT_ACTION_DOWN && splitDownTime != originalMotionEntry.eventTime) {
4140 logDispatchStateLocked();
4141 LOG_ALWAYS_FATAL("Split motion event has mismatching downTime and eventTime for "
4142 "ACTION_DOWN, motionEntry=%s, splitDownTime=%" PRId64,
4143 originalMotionEntry.getDescription().c_str(), splitDownTime);
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00004144 }
4145
Garfield Tanff1f1bb2020-01-28 13:24:04 -08004146 int32_t newId = mIdGenerator.nextId();
Prabir Pradhan2dac8b82023-09-06 01:11:51 +00004147 ATRACE_NAME_IF(ATRACE_ENABLED(),
4148 StringPrintf("Split MotionEvent(id=0x%" PRIx32 ") to MotionEvent(id=0x%" PRIx32
4149 ").",
4150 originalMotionEntry.id, newId));
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004151 std::unique_ptr<MotionEntry> splitMotionEntry =
4152 std::make_unique<MotionEntry>(newId, originalMotionEntry.eventTime,
4153 originalMotionEntry.deviceId, originalMotionEntry.source,
4154 originalMotionEntry.displayId,
4155 originalMotionEntry.policyFlags, action,
4156 originalMotionEntry.actionButton,
4157 originalMotionEntry.flags, originalMotionEntry.metaState,
4158 originalMotionEntry.buttonState,
4159 originalMotionEntry.classification,
4160 originalMotionEntry.edgeFlags,
4161 originalMotionEntry.xPrecision,
4162 originalMotionEntry.yPrecision,
4163 originalMotionEntry.xCursorPosition,
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00004164 originalMotionEntry.yCursorPosition, splitDownTime,
4165 splitPointerCount, splitPointerProperties,
4166 splitPointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004167
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07004168 if (originalMotionEntry.injectionState) {
4169 splitMotionEntry->injectionState = originalMotionEntry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004170 splitMotionEntry->injectionState->refCount += 1;
4171 }
4172
4173 return splitMotionEntry;
4174}
4175
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004176void InputDispatcher::notifyConfigurationChanged(const NotifyConfigurationChangedArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004177 if (debugInboundEventDetails()) {
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004178 ALOGD("notifyConfigurationChanged - eventTime=%" PRId64, args.eventTime);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004179 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004180
Antonio Kantekf16f2832021-09-28 04:39:20 +00004181 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004182 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004183 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004184
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004185 std::unique_ptr<ConfigurationChangedEntry> newEntry =
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004186 std::make_unique<ConfigurationChangedEntry>(args.id, args.eventTime);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004187 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004188 } // release lock
4189
4190 if (needWake) {
4191 mLooper->wake();
4192 }
4193}
4194
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004195void InputDispatcher::notifyKey(const NotifyKeyArgs& args) {
Prabir Pradhan96282b02023-02-24 22:36:17 +00004196 ALOGD_IF(debugInboundEventDetails(),
4197 "notifyKey - id=%" PRIx32 ", eventTime=%" PRId64
4198 ", deviceId=%d, source=%s, displayId=%" PRId32
4199 "policyFlags=0x%x, action=%s, flags=0x%x, keyCode=%s, scanCode=0x%x, metaState=0x%x, "
4200 "downTime=%" PRId64,
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004201 args.id, args.eventTime, args.deviceId, inputEventSourceToString(args.source).c_str(),
4202 args.displayId, args.policyFlags, KeyEvent::actionToString(args.action), args.flags,
4203 KeyEvent::getLabel(args.keyCode), args.scanCode, args.metaState, args.downTime);
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004204 Result<void> keyCheck = validateKeyEvent(args.action);
4205 if (!keyCheck.ok()) {
4206 LOG(ERROR) << "invalid key event: " << keyCheck.error();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004207 return;
4208 }
4209
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004210 uint32_t policyFlags = args.policyFlags;
4211 int32_t flags = args.flags;
4212 int32_t metaState = args.metaState;
Siarhei Vishniakou622bd322018-10-29 18:02:27 -07004213 // InputDispatcher tracks and generates key repeats on behalf of
4214 // whatever notifies it, so repeatCount should always be set to 0
4215 constexpr int32_t repeatCount = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004216 if ((policyFlags & POLICY_FLAG_VIRTUAL) || (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY)) {
4217 policyFlags |= POLICY_FLAG_VIRTUAL;
4218 flags |= AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
4219 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004220 if (policyFlags & POLICY_FLAG_FUNCTION) {
4221 metaState |= AMETA_FUNCTION_ON;
4222 }
4223
4224 policyFlags |= POLICY_FLAG_TRUSTED;
4225
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004226 int32_t keyCode = args.keyCode;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004227 KeyEvent event;
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004228 event.initialize(args.id, args.deviceId, args.source, args.displayId, INVALID_HMAC, args.action,
4229 flags, keyCode, args.scanCode, metaState, repeatCount, args.downTime,
4230 args.eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004231
Michael Wright2b3c3302018-03-02 17:19:13 +00004232 android::base::Timer t;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004233 mPolicy.interceptKeyBeforeQueueing(event, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00004234 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4235 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004236 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00004237 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004238
Antonio Kantekf16f2832021-09-28 04:39:20 +00004239 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004240 { // acquire lock
4241 mLock.lock();
4242
4243 if (shouldSendKeyToInputFilterLocked(args)) {
4244 mLock.unlock();
4245
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004246 policyFlags |= POLICY_FLAG_FILTERED;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004247 if (!mPolicy.filterInputEvent(event, policyFlags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004248 return; // event was consumed by the filter
4249 }
4250
4251 mLock.lock();
4252 }
4253
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004254 std::unique_ptr<KeyEntry> newEntry =
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004255 std::make_unique<KeyEntry>(args.id, args.eventTime, args.deviceId, args.source,
4256 args.displayId, policyFlags, args.action, flags, keyCode,
4257 args.scanCode, metaState, repeatCount, args.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004258
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004259 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004260 mLock.unlock();
4261 } // release lock
4262
4263 if (needWake) {
4264 mLooper->wake();
4265 }
4266}
4267
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004268bool InputDispatcher::shouldSendKeyToInputFilterLocked(const NotifyKeyArgs& args) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004269 return mInputFilterEnabled;
4270}
4271
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004272void InputDispatcher::notifyMotion(const NotifyMotionArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004273 if (debugInboundEventDetails()) {
Prabir Pradhan96282b02023-02-24 22:36:17 +00004274 ALOGD("notifyMotion - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=%s, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004275 "displayId=%" PRId32 ", policyFlags=0x%x, "
Siarhei Vishniakou6ebd0692022-10-20 15:05:45 -07004276 "action=%s, actionButton=0x%x, flags=0x%x, metaState=0x%x, buttonState=0x%x, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004277 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, xCursorPosition=%f, "
4278 "yCursorPosition=%f, downTime=%" PRId64,
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004279 args.id, args.eventTime, args.deviceId, inputEventSourceToString(args.source).c_str(),
4280 args.displayId, args.policyFlags, MotionEvent::actionToString(args.action).c_str(),
4281 args.actionButton, args.flags, args.metaState, args.buttonState, args.edgeFlags,
4282 args.xPrecision, args.yPrecision, args.xCursorPosition, args.yCursorPosition,
4283 args.downTime);
Siarhei Vishniakou3218fc02023-06-15 20:41:02 -07004284 for (uint32_t i = 0; i < args.getPointerCount(); i++) {
Prabir Pradhan96282b02023-02-24 22:36:17 +00004285 ALOGD(" Pointer %d: id=%d, toolType=%s, x=%f, y=%f, pressure=%f, size=%f, "
4286 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, orientation=%f",
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004287 i, args.pointerProperties[i].id,
4288 ftl::enum_string(args.pointerProperties[i].toolType).c_str(),
4289 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
4290 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
4291 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
4292 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
4293 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
4294 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
4295 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
4296 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
4297 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004298 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004299 }
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004300
Siarhei Vishniakou3218fc02023-06-15 20:41:02 -07004301 Result<void> motionCheck =
4302 validateMotionEvent(args.action, args.actionButton, args.getPointerCount(),
4303 args.pointerProperties.data());
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004304 if (!motionCheck.ok()) {
4305 LOG(FATAL) << "Invalid event: " << args.dump() << "; reason: " << motionCheck.error();
4306 return;
4307 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004308
Siarhei Vishniakou5c02a712023-05-15 15:45:02 -07004309 if (DEBUG_VERIFY_EVENTS) {
4310 auto [it, _] =
4311 mVerifiersByDisplay.try_emplace(args.displayId,
4312 StringPrintf("display %" PRId32, args.displayId));
4313 Result<void> result =
Siarhei Vishniakou3218fc02023-06-15 20:41:02 -07004314 it->second.processMovement(args.deviceId, args.action, args.getPointerCount(),
4315 args.pointerProperties.data(), args.pointerCoords.data(),
4316 args.flags);
Siarhei Vishniakou5c02a712023-05-15 15:45:02 -07004317 if (!result.ok()) {
4318 LOG(FATAL) << "Bad stream: " << result.error() << " caused by " << args.dump();
4319 }
4320 }
4321
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004322 uint32_t policyFlags = args.policyFlags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004323 policyFlags |= POLICY_FLAG_TRUSTED;
Michael Wright2b3c3302018-03-02 17:19:13 +00004324
4325 android::base::Timer t;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004326 mPolicy.interceptMotionBeforeQueueing(args.displayId, args.eventTime, policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00004327 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4328 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004329 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00004330 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004331
Antonio Kantekf16f2832021-09-28 04:39:20 +00004332 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004333 { // acquire lock
4334 mLock.lock();
Siarhei Vishniakou5bf25d92023-02-08 15:43:38 -08004335 if (!(policyFlags & POLICY_FLAG_PASS_TO_USER)) {
4336 // Set the flag anyway if we already have an ongoing gesture. That would allow us to
4337 // complete the processing of the current stroke.
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004338 const auto touchStateIt = mTouchStatesByDisplay.find(args.displayId);
Siarhei Vishniakou5bf25d92023-02-08 15:43:38 -08004339 if (touchStateIt != mTouchStatesByDisplay.end()) {
4340 const TouchState& touchState = touchStateIt->second;
Siarhei Vishniakou45504fe2023-05-05 16:05:10 -07004341 if (touchState.hasTouchingPointers(args.deviceId)) {
Siarhei Vishniakou5bf25d92023-02-08 15:43:38 -08004342 policyFlags |= POLICY_FLAG_PASS_TO_USER;
4343 }
4344 }
4345 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004346
4347 if (shouldSendMotionToInputFilterLocked(args)) {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004348 ui::Transform displayTransform;
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004349 if (const auto it = mDisplayInfos.find(args.displayId); it != mDisplayInfos.end()) {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004350 displayTransform = it->second.transform;
4351 }
4352
Michael Wrightd02c5b62014-02-10 15:10:22 -08004353 mLock.unlock();
4354
4355 MotionEvent event;
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004356 event.initialize(args.id, args.deviceId, args.source, args.displayId, INVALID_HMAC,
4357 args.action, args.actionButton, args.flags, args.edgeFlags,
4358 args.metaState, args.buttonState, args.classification,
4359 displayTransform, args.xPrecision, args.yPrecision,
4360 args.xCursorPosition, args.yCursorPosition, displayTransform,
Siarhei Vishniakou3218fc02023-06-15 20:41:02 -07004361 args.downTime, args.eventTime, args.getPointerCount(),
4362 args.pointerProperties.data(), args.pointerCoords.data());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004363
4364 policyFlags |= POLICY_FLAG_FILTERED;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004365 if (!mPolicy.filterInputEvent(event, policyFlags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004366 return; // event was consumed by the filter
4367 }
4368
4369 mLock.lock();
4370 }
4371
4372 // Just enqueue a new motion event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004373 std::unique_ptr<MotionEntry> newEntry =
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004374 std::make_unique<MotionEntry>(args.id, args.eventTime, args.deviceId, args.source,
4375 args.displayId, policyFlags, args.action,
4376 args.actionButton, args.flags, args.metaState,
4377 args.buttonState, args.classification, args.edgeFlags,
4378 args.xPrecision, args.yPrecision,
4379 args.xCursorPosition, args.yCursorPosition,
Siarhei Vishniakou3218fc02023-06-15 20:41:02 -07004380 args.downTime, args.getPointerCount(),
4381 args.pointerProperties.data(),
4382 args.pointerCoords.data());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004383
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004384 if (args.id != android::os::IInputConstants::INVALID_INPUT_EVENT_ID &&
4385 IdGenerator::getSource(args.id) == IdGenerator::Source::INPUT_READER &&
Siarhei Vishniakou363e7292021-07-09 03:22:42 +00004386 !mInputFilterEnabled) {
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004387 const bool isDown = args.action == AMOTION_EVENT_ACTION_DOWN;
4388 mLatencyTracker.trackListener(args.id, isDown, args.eventTime, args.readTime);
Siarhei Vishniakou363e7292021-07-09 03:22:42 +00004389 }
4390
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004391 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004392 mLock.unlock();
4393 } // release lock
4394
4395 if (needWake) {
4396 mLooper->wake();
4397 }
4398}
4399
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004400void InputDispatcher::notifySensor(const NotifySensorArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004401 if (debugInboundEventDetails()) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004402 ALOGD("notifySensor - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=0x%x, "
4403 " sensorType=%s",
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004404 args.id, args.eventTime, args.deviceId, args.source,
4405 ftl::enum_string(args.sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004406 }
Chris Yef59a2f42020-10-16 12:55:26 -07004407
Antonio Kantekf16f2832021-09-28 04:39:20 +00004408 bool needWake = false;
Chris Yef59a2f42020-10-16 12:55:26 -07004409 { // acquire lock
4410 mLock.lock();
4411
4412 // Just enqueue a new sensor event.
4413 std::unique_ptr<SensorEntry> newEntry =
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004414 std::make_unique<SensorEntry>(args.id, args.eventTime, args.deviceId, args.source,
4415 /* policyFlags=*/0, args.hwTimestamp, args.sensorType,
4416 args.accuracy, args.accuracyChanged, args.values);
Chris Yef59a2f42020-10-16 12:55:26 -07004417
4418 needWake = enqueueInboundEventLocked(std::move(newEntry));
4419 mLock.unlock();
4420 } // release lock
4421
4422 if (needWake) {
4423 mLooper->wake();
4424 }
4425}
4426
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004427void InputDispatcher::notifyVibratorState(const NotifyVibratorStateArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004428 if (debugInboundEventDetails()) {
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004429 ALOGD("notifyVibratorState - eventTime=%" PRId64 ", device=%d, isOn=%d", args.eventTime,
4430 args.deviceId, args.isOn);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004431 }
Prabir Pradhana41d2442023-04-20 21:30:40 +00004432 mPolicy.notifyVibratorState(args.deviceId, args.isOn);
Chris Yefb552902021-02-03 17:18:37 -08004433}
4434
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004435bool InputDispatcher::shouldSendMotionToInputFilterLocked(const NotifyMotionArgs& args) {
Jackal Guof9696682018-10-05 12:23:23 +08004436 return mInputFilterEnabled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004437}
4438
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004439void InputDispatcher::notifySwitch(const NotifySwitchArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004440 if (debugInboundEventDetails()) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004441 ALOGD("notifySwitch - eventTime=%" PRId64 ", policyFlags=0x%x, switchValues=0x%08x, "
4442 "switchMask=0x%08x",
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004443 args.eventTime, args.policyFlags, args.switchValues, args.switchMask);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004444 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004445
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004446 uint32_t policyFlags = args.policyFlags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004447 policyFlags |= POLICY_FLAG_TRUSTED;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004448 mPolicy.notifySwitch(args.eventTime, args.switchValues, args.switchMask, policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004449}
4450
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004451void InputDispatcher::notifyDeviceReset(const NotifyDeviceResetArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004452 if (debugInboundEventDetails()) {
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004453 ALOGD("notifyDeviceReset - eventTime=%" PRId64 ", deviceId=%d", args.eventTime,
4454 args.deviceId);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004455 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004456
Antonio Kantekf16f2832021-09-28 04:39:20 +00004457 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004458 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004459 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004460
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004461 std::unique_ptr<DeviceResetEntry> newEntry =
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004462 std::make_unique<DeviceResetEntry>(args.id, args.eventTime, args.deviceId);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004463 needWake = enqueueInboundEventLocked(std::move(newEntry));
Siarhei Vishniakou1160ecd2023-06-28 15:57:47 -07004464
4465 for (auto& [_, verifier] : mVerifiersByDisplay) {
4466 verifier.resetDevice(args.deviceId);
4467 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004468 } // release lock
4469
4470 if (needWake) {
4471 mLooper->wake();
4472 }
4473}
4474
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004475void InputDispatcher::notifyPointerCaptureChanged(const NotifyPointerCaptureChangedArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004476 if (debugInboundEventDetails()) {
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004477 ALOGD("notifyPointerCaptureChanged - eventTime=%" PRId64 ", enabled=%s", args.eventTime,
4478 args.request.enable ? "true" : "false");
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004479 }
Prabir Pradhan7e186182020-11-10 13:56:45 -08004480
Antonio Kantekf16f2832021-09-28 04:39:20 +00004481 bool needWake = false;
Prabir Pradhan99987712020-11-10 18:43:05 -08004482 { // acquire lock
4483 std::scoped_lock _l(mLock);
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004484 auto entry =
4485 std::make_unique<PointerCaptureChangedEntry>(args.id, args.eventTime, args.request);
Prabir Pradhan99987712020-11-10 18:43:05 -08004486 needWake = enqueueInboundEventLocked(std::move(entry));
4487 } // release lock
4488
4489 if (needWake) {
4490 mLooper->wake();
4491 }
Prabir Pradhan7e186182020-11-10 13:56:45 -08004492}
4493
Prabir Pradhan5735a322022-04-11 17:23:34 +00004494InputEventInjectionResult InputDispatcher::injectInputEvent(const InputEvent* event,
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00004495 std::optional<gui::Uid> targetUid,
Prabir Pradhan5735a322022-04-11 17:23:34 +00004496 InputEventInjectionSync syncMode,
4497 std::chrono::milliseconds timeout,
4498 uint32_t policyFlags) {
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004499 Result<void> eventValidation = validateInputEvent(*event);
4500 if (!eventValidation.ok()) {
4501 LOG(INFO) << "Injection failed: invalid event: " << eventValidation.error();
4502 return InputEventInjectionResult::FAILED;
4503 }
4504
Prabir Pradhan65613802023-02-22 23:36:58 +00004505 if (debugInboundEventDetails()) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07004506 LOG(INFO) << __func__ << ": targetUid=" << toString(targetUid, &uidString)
4507 << ", syncMode=" << ftl::enum_string(syncMode) << ", timeout=" << timeout.count()
4508 << "ms, policyFlags=0x" << std::hex << policyFlags << std::dec
4509 << ", event=" << *event;
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004510 }
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07004511 nsecs_t endTime = now() + std::chrono::duration_cast<std::chrono::nanoseconds>(timeout).count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004512
Prabir Pradhan5735a322022-04-11 17:23:34 +00004513 policyFlags |= POLICY_FLAG_INJECTED | POLICY_FLAG_TRUSTED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004514
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004515 // For all injected events, set device id = VIRTUAL_KEYBOARD_ID. The only exception is events
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004516 // that have gone through the InputFilter. If the event passed through the InputFilter, assign
4517 // the provided device id. If the InputFilter is accessibility, and it modifies or synthesizes
4518 // the injected event, it is responsible for setting POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY.
4519 // For those events, we will set FLAG_IS_ACCESSIBILITY_EVENT to allow apps to distinguish them
4520 // from events that originate from actual hardware.
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004521 int32_t resolvedDeviceId = VIRTUAL_KEYBOARD_ID;
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004522 if (policyFlags & POLICY_FLAG_FILTERED) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004523 resolvedDeviceId = event->getDeviceId();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004524 }
4525
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004526 std::queue<std::unique_ptr<EventEntry>> injectedEntries;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004527 switch (event->getType()) {
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004528 case InputEventType::KEY: {
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004529 const KeyEvent& incomingKey = static_cast<const KeyEvent&>(*event);
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004530 const int32_t action = incomingKey.getAction();
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004531 int32_t flags = incomingKey.getFlags();
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004532 if (policyFlags & POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY) {
4533 flags |= AKEY_EVENT_FLAG_IS_ACCESSIBILITY_EVENT;
4534 }
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004535 int32_t keyCode = incomingKey.getKeyCode();
4536 int32_t metaState = incomingKey.getMetaState();
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004537 KeyEvent keyEvent;
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004538 keyEvent.initialize(incomingKey.getId(), resolvedDeviceId, incomingKey.getSource(),
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004539 incomingKey.getDisplayId(), INVALID_HMAC, action, flags, keyCode,
4540 incomingKey.getScanCode(), metaState, incomingKey.getRepeatCount(),
4541 incomingKey.getDownTime(), incomingKey.getEventTime());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004542
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004543 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
4544 policyFlags |= POLICY_FLAG_VIRTUAL;
Michael Wright2b3c3302018-03-02 17:19:13 +00004545 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004546
4547 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
4548 android::base::Timer t;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004549 mPolicy.interceptKeyBeforeQueueing(keyEvent, /*byref*/ policyFlags);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004550 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4551 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
4552 std::to_string(t.duration().count()).c_str());
4553 }
4554 }
4555
4556 mLock.lock();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004557 std::unique_ptr<KeyEntry> injectedEntry =
4558 std::make_unique<KeyEntry>(incomingKey.getId(), incomingKey.getEventTime(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004559 resolvedDeviceId, incomingKey.getSource(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004560 incomingKey.getDisplayId(), policyFlags, action,
4561 flags, keyCode, incomingKey.getScanCode(), metaState,
4562 incomingKey.getRepeatCount(),
4563 incomingKey.getDownTime());
4564 injectedEntries.push(std::move(injectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004565 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004566 }
4567
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004568 case InputEventType::MOTION: {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004569 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(*event);
Prabir Pradhanaa561d12021-09-24 06:57:33 -07004570 const bool isPointerEvent =
4571 isFromSource(event->getSource(), AINPUT_SOURCE_CLASS_POINTER);
4572 // If a pointer event has no displayId specified, inject it to the default display.
4573 const uint32_t displayId = isPointerEvent && (event->getDisplayId() == ADISPLAY_ID_NONE)
4574 ? ADISPLAY_ID_DEFAULT
4575 : event->getDisplayId();
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004576 int32_t flags = motionEvent.getFlags();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004577
4578 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004579 nsecs_t eventTime = motionEvent.getEventTime();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004580 android::base::Timer t;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004581 mPolicy.interceptMotionBeforeQueueing(displayId, eventTime, /*byref*/ policyFlags);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004582 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4583 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
4584 std::to_string(t.duration().count()).c_str());
4585 }
4586 }
4587
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004588 if (policyFlags & POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY) {
4589 flags |= AMOTION_EVENT_FLAG_IS_ACCESSIBILITY_EVENT;
4590 }
4591
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004592 mLock.lock();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004593 const nsecs_t* sampleEventTimes = motionEvent.getSampleEventTimes();
4594 const PointerCoords* samplePointerCoords = motionEvent.getSamplePointerCoords();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004595 std::unique_ptr<MotionEntry> injectedEntry =
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004596 std::make_unique<MotionEntry>(motionEvent.getId(), *sampleEventTimes,
4597 resolvedDeviceId, motionEvent.getSource(),
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004598 displayId, policyFlags, motionEvent.getAction(),
4599 motionEvent.getActionButton(), flags,
4600 motionEvent.getMetaState(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004601 motionEvent.getButtonState(),
4602 motionEvent.getClassification(),
4603 motionEvent.getEdgeFlags(),
4604 motionEvent.getXPrecision(),
4605 motionEvent.getYPrecision(),
4606 motionEvent.getRawXCursorPosition(),
4607 motionEvent.getRawYCursorPosition(),
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004608 motionEvent.getDownTime(),
4609 motionEvent.getPointerCount(),
4610 motionEvent.getPointerProperties(),
4611 samplePointerCoords);
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004612 transformMotionEntryForInjectionLocked(*injectedEntry, motionEvent.getTransform());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004613 injectedEntries.push(std::move(injectedEntry));
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004614 for (size_t i = motionEvent.getHistorySize(); i > 0; i--) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004615 sampleEventTimes += 1;
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004616 samplePointerCoords += motionEvent.getPointerCount();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004617 std::unique_ptr<MotionEntry> nextInjectedEntry =
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004618 std::make_unique<MotionEntry>(motionEvent.getId(), *sampleEventTimes,
4619 resolvedDeviceId, motionEvent.getSource(),
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004620 displayId, policyFlags,
4621 motionEvent.getAction(),
4622 motionEvent.getActionButton(), flags,
4623 motionEvent.getMetaState(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004624 motionEvent.getButtonState(),
4625 motionEvent.getClassification(),
4626 motionEvent.getEdgeFlags(),
4627 motionEvent.getXPrecision(),
4628 motionEvent.getYPrecision(),
4629 motionEvent.getRawXCursorPosition(),
4630 motionEvent.getRawYCursorPosition(),
4631 motionEvent.getDownTime(),
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004632 motionEvent.getPointerCount(),
4633 motionEvent.getPointerProperties(),
Prabir Pradhan5beda762021-12-10 09:30:08 +00004634 samplePointerCoords);
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004635 transformMotionEntryForInjectionLocked(*nextInjectedEntry,
4636 motionEvent.getTransform());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004637 injectedEntries.push(std::move(nextInjectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004638 }
4639 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004640 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004641
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004642 default:
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004643 LOG(WARNING) << "Cannot inject " << ftl::enum_string(event->getType()) << " events";
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004644 return InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004645 }
4646
Prabir Pradhan5735a322022-04-11 17:23:34 +00004647 InjectionState* injectionState = new InjectionState(targetUid);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004648 if (syncMode == InputEventInjectionSync::NONE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004649 injectionState->injectionIsAsync = true;
4650 }
4651
4652 injectionState->refCount += 1;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004653 injectedEntries.back()->injectionState = injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004654
4655 bool needWake = false;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004656 while (!injectedEntries.empty()) {
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08004657 if (DEBUG_INJECTION) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07004658 LOG(INFO) << "Injecting " << injectedEntries.front()->getDescription();
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08004659 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004660 needWake |= enqueueInboundEventLocked(std::move(injectedEntries.front()));
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004661 injectedEntries.pop();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004662 }
4663
4664 mLock.unlock();
4665
4666 if (needWake) {
4667 mLooper->wake();
4668 }
4669
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004670 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004671 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004672 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004673
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004674 if (syncMode == InputEventInjectionSync::NONE) {
4675 injectionResult = InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004676 } else {
4677 for (;;) {
4678 injectionResult = injectionState->injectionResult;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004679 if (injectionResult != InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004680 break;
4681 }
4682
4683 nsecs_t remainingTimeout = endTime - now();
4684 if (remainingTimeout <= 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004685 if (DEBUG_INJECTION) {
4686 ALOGD("injectInputEvent - Timed out waiting for injection result "
4687 "to become available.");
4688 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004689 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004690 break;
4691 }
4692
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004693 mInjectionResultAvailable.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004694 }
4695
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004696 if (injectionResult == InputEventInjectionResult::SUCCEEDED &&
4697 syncMode == InputEventInjectionSync::WAIT_FOR_FINISHED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004698 while (injectionState->pendingForegroundDispatches != 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004699 if (DEBUG_INJECTION) {
4700 ALOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
4701 injectionState->pendingForegroundDispatches);
4702 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004703 nsecs_t remainingTimeout = endTime - now();
4704 if (remainingTimeout <= 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004705 if (DEBUG_INJECTION) {
4706 ALOGD("injectInputEvent - Timed out waiting for pending foreground "
4707 "dispatches to finish.");
4708 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004709 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004710 break;
4711 }
4712
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004713 mInjectionSyncFinished.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004714 }
4715 }
4716 }
4717
4718 injectionState->release();
4719 } // release lock
4720
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004721 if (DEBUG_INJECTION) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07004722 LOG(INFO) << "injectInputEvent - Finished with result "
4723 << ftl::enum_string(injectionResult);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004724 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004725
4726 return injectionResult;
4727}
4728
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004729std::unique_ptr<VerifiedInputEvent> InputDispatcher::verifyInputEvent(const InputEvent& event) {
Gang Wange9087892020-01-07 12:17:14 -05004730 std::array<uint8_t, 32> calculatedHmac;
4731 std::unique_ptr<VerifiedInputEvent> result;
4732 switch (event.getType()) {
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004733 case InputEventType::KEY: {
Gang Wange9087892020-01-07 12:17:14 -05004734 const KeyEvent& keyEvent = static_cast<const KeyEvent&>(event);
4735 VerifiedKeyEvent verifiedKeyEvent = verifiedKeyEventFromKeyEvent(keyEvent);
4736 result = std::make_unique<VerifiedKeyEvent>(verifiedKeyEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004737 calculatedHmac = sign(verifiedKeyEvent);
Gang Wange9087892020-01-07 12:17:14 -05004738 break;
4739 }
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004740 case InputEventType::MOTION: {
Gang Wange9087892020-01-07 12:17:14 -05004741 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(event);
4742 VerifiedMotionEvent verifiedMotionEvent =
4743 verifiedMotionEventFromMotionEvent(motionEvent);
4744 result = std::make_unique<VerifiedMotionEvent>(verifiedMotionEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004745 calculatedHmac = sign(verifiedMotionEvent);
Gang Wange9087892020-01-07 12:17:14 -05004746 break;
4747 }
4748 default: {
4749 ALOGE("Cannot verify events of type %" PRId32, event.getType());
4750 return nullptr;
4751 }
4752 }
4753 if (calculatedHmac == INVALID_HMAC) {
4754 return nullptr;
4755 }
tyiu1573a672023-02-21 22:38:32 +00004756 if (0 != CRYPTO_memcmp(calculatedHmac.data(), event.getHmac().data(), calculatedHmac.size())) {
Gang Wange9087892020-01-07 12:17:14 -05004757 return nullptr;
4758 }
4759 return result;
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004760}
4761
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004762void InputDispatcher::setInjectionResult(EventEntry& entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004763 InputEventInjectionResult injectionResult) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004764 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004765 if (injectionState) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004766 if (DEBUG_INJECTION) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07004767 LOG(INFO) << "Setting input event injection result to "
4768 << ftl::enum_string(injectionResult);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004769 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004770
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004771 if (injectionState->injectionIsAsync && !(entry.policyFlags & POLICY_FLAG_FILTERED)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004772 // Log the outcome since the injector did not wait for the injection result.
4773 switch (injectionResult) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004774 case InputEventInjectionResult::SUCCEEDED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004775 ALOGV("Asynchronous input event injection succeeded.");
4776 break;
Prabir Pradhan5735a322022-04-11 17:23:34 +00004777 case InputEventInjectionResult::TARGET_MISMATCH:
4778 ALOGV("Asynchronous input event injection target mismatch.");
4779 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004780 case InputEventInjectionResult::FAILED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004781 ALOGW("Asynchronous input event injection failed.");
4782 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004783 case InputEventInjectionResult::TIMED_OUT:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004784 ALOGW("Asynchronous input event injection timed out.");
4785 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004786 case InputEventInjectionResult::PENDING:
4787 ALOGE("Setting result to 'PENDING' for asynchronous injection");
4788 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004789 }
4790 }
4791
4792 injectionState->injectionResult = injectionResult;
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004793 mInjectionResultAvailable.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004794 }
4795}
4796
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004797void InputDispatcher::transformMotionEntryForInjectionLocked(
4798 MotionEntry& entry, const ui::Transform& injectedTransform) const {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004799 // Input injection works in the logical display coordinate space, but the input pipeline works
4800 // display space, so we need to transform the injected events accordingly.
4801 const auto it = mDisplayInfos.find(entry.displayId);
4802 if (it == mDisplayInfos.end()) return;
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004803 const auto& transformToDisplay = it->second.transform.inverse() * injectedTransform;
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004804
Prabir Pradhand9a2ebe2022-07-20 19:25:13 +00004805 if (entry.xCursorPosition != AMOTION_EVENT_INVALID_CURSOR_POSITION &&
4806 entry.yCursorPosition != AMOTION_EVENT_INVALID_CURSOR_POSITION) {
4807 const vec2 cursor =
4808 MotionEvent::calculateTransformedXY(entry.source, transformToDisplay,
4809 {entry.xCursorPosition, entry.yCursorPosition});
4810 entry.xCursorPosition = cursor.x;
4811 entry.yCursorPosition = cursor.y;
4812 }
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004813 for (uint32_t i = 0; i < entry.pointerCount; i++) {
Prabir Pradhan8e6ce222022-02-24 09:08:54 -08004814 entry.pointerCoords[i] =
4815 MotionEvent::calculateTransformedCoords(entry.source, transformToDisplay,
4816 entry.pointerCoords[i]);
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004817 }
4818}
4819
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004820void InputDispatcher::incrementPendingForegroundDispatches(EventEntry& entry) {
4821 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004822 if (injectionState) {
4823 injectionState->pendingForegroundDispatches += 1;
4824 }
4825}
4826
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004827void InputDispatcher::decrementPendingForegroundDispatches(EventEntry& entry) {
4828 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004829 if (injectionState) {
4830 injectionState->pendingForegroundDispatches -= 1;
4831
4832 if (injectionState->pendingForegroundDispatches == 0) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004833 mInjectionSyncFinished.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004834 }
4835 }
4836}
4837
chaviw98318de2021-05-19 16:45:23 -05004838const std::vector<sp<WindowInfoHandle>>& InputDispatcher::getWindowHandlesLocked(
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004839 int32_t displayId) const {
chaviw98318de2021-05-19 16:45:23 -05004840 static const std::vector<sp<WindowInfoHandle>> EMPTY_WINDOW_HANDLES;
Vishnu Nairad321cd2020-08-20 16:40:21 -07004841 auto it = mWindowHandlesByDisplay.find(displayId);
4842 return it != mWindowHandlesByDisplay.end() ? it->second : EMPTY_WINDOW_HANDLES;
Arthur Hungb92218b2018-08-14 12:00:21 +08004843}
4844
chaviw98318de2021-05-19 16:45:23 -05004845sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(
chaviwfbe5d9c2018-12-26 12:23:37 -08004846 const sp<IBinder>& windowHandleToken) const {
arthurhungbe737672020-06-24 12:29:21 +08004847 if (windowHandleToken == nullptr) {
4848 return nullptr;
4849 }
4850
Arthur Hungb92218b2018-08-14 12:00:21 +08004851 for (auto& it : mWindowHandlesByDisplay) {
chaviw98318de2021-05-19 16:45:23 -05004852 const std::vector<sp<WindowInfoHandle>>& windowHandles = it.second;
4853 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
chaviwfbe5d9c2018-12-26 12:23:37 -08004854 if (windowHandle->getToken() == windowHandleToken) {
Arthur Hungb92218b2018-08-14 12:00:21 +08004855 return windowHandle;
4856 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004857 }
4858 }
Yi Kong9b14ac62018-07-17 13:48:38 -07004859 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004860}
4861
chaviw98318de2021-05-19 16:45:23 -05004862sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(const sp<IBinder>& windowHandleToken,
4863 int displayId) const {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004864 if (windowHandleToken == nullptr) {
4865 return nullptr;
4866 }
4867
chaviw98318de2021-05-19 16:45:23 -05004868 for (const sp<WindowInfoHandle>& windowHandle : getWindowHandlesLocked(displayId)) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004869 if (windowHandle->getToken() == windowHandleToken) {
4870 return windowHandle;
4871 }
4872 }
4873 return nullptr;
4874}
4875
chaviw98318de2021-05-19 16:45:23 -05004876sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(
4877 const sp<WindowInfoHandle>& windowHandle) const {
Mady Mellor017bcd12020-06-23 19:12:00 +00004878 for (auto& it : mWindowHandlesByDisplay) {
chaviw98318de2021-05-19 16:45:23 -05004879 const std::vector<sp<WindowInfoHandle>>& windowHandles = it.second;
4880 for (const sp<WindowInfoHandle>& handle : windowHandles) {
arthurhungbe737672020-06-24 12:29:21 +08004881 if (handle->getId() == windowHandle->getId() &&
4882 handle->getToken() == windowHandle->getToken()) {
Mady Mellor017bcd12020-06-23 19:12:00 +00004883 if (windowHandle->getInfo()->displayId != it.first) {
4884 ALOGE("Found window %s in display %" PRId32
4885 ", but it should belong to display %" PRId32,
4886 windowHandle->getName().c_str(), it.first,
4887 windowHandle->getInfo()->displayId);
4888 }
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004889 return handle;
Arthur Hungb92218b2018-08-14 12:00:21 +08004890 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004891 }
4892 }
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004893 return nullptr;
4894}
4895
chaviw98318de2021-05-19 16:45:23 -05004896sp<WindowInfoHandle> InputDispatcher::getFocusedWindowHandleLocked(int displayId) const {
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004897 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(displayId);
4898 return getWindowHandleLocked(focusedToken, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004899}
4900
Prabir Pradhan33e3baa2022-12-06 20:30:22 +00004901ui::Transform InputDispatcher::getTransformLocked(int32_t displayId) const {
4902 auto displayInfoIt = mDisplayInfos.find(displayId);
4903 return displayInfoIt != mDisplayInfos.end() ? displayInfoIt->second.transform
4904 : kIdentityTransform;
4905}
4906
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004907bool InputDispatcher::canWindowReceiveMotionLocked(const sp<WindowInfoHandle>& window,
4908 const MotionEntry& motionEntry) const {
4909 const WindowInfo& info = *window->getInfo();
4910
4911 // Skip spy window targets that are not valid for targeted injection.
4912 if (const auto err = verifyTargetedInjection(window, motionEntry); err) {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004913 return false;
4914 }
4915
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004916 if (info.inputConfig.test(WindowInfo::InputConfig::PAUSE_DISPATCHING)) {
4917 ALOGI("Not sending touch event to %s because it is paused", window->getName().c_str());
4918 return false;
4919 }
4920
4921 if (info.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL)) {
4922 ALOGW("Not sending touch gesture to %s because it has config NO_INPUT_CHANNEL",
4923 window->getName().c_str());
4924 return false;
4925 }
4926
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07004927 std::shared_ptr<Connection> connection = getConnectionLocked(window->getToken());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004928 if (connection == nullptr) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004929 ALOGW("Not sending touch to %s because there's no corresponding connection",
4930 window->getName().c_str());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004931 return false;
4932 }
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004933
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004934 if (!connection->responsive) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004935 ALOGW("Not sending touch to %s because it is not responsive", window->getName().c_str());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004936 return false;
4937 }
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004938
4939 // Drop events that can't be trusted due to occlusion
4940 const auto [x, y] = resolveTouchedPosition(motionEntry);
4941 TouchOcclusionInfo occlusionInfo = computeTouchOcclusionInfoLocked(window, x, y);
4942 if (!isTouchTrustedLocked(occlusionInfo)) {
4943 if (DEBUG_TOUCH_OCCLUSION) {
Prabir Pradhan82e081e2022-12-06 09:50:09 +00004944 ALOGD("Stack of obscuring windows during untrusted touch (%.1f, %.1f):", x, y);
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004945 for (const auto& log : occlusionInfo.debugInfo) {
4946 ALOGD("%s", log.c_str());
4947 }
4948 }
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00004949 ALOGW("Dropping untrusted touch event due to %s/%s", occlusionInfo.obscuringPackage.c_str(),
4950 occlusionInfo.obscuringUid.toString().c_str());
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004951 return false;
4952 }
4953
4954 // Drop touch events if requested by input feature
4955 if (shouldDropInput(motionEntry, window)) {
4956 return false;
4957 }
4958
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004959 return true;
4960}
4961
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004962std::shared_ptr<InputChannel> InputDispatcher::getInputChannelLocked(
4963 const sp<IBinder>& token) const {
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00004964 auto connectionIt = mConnectionsByToken.find(token);
4965 if (connectionIt == mConnectionsByToken.end()) {
Robert Carr5c8a0262018-10-03 16:30:44 -07004966 return nullptr;
4967 }
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00004968 return connectionIt->second->inputChannel;
Robert Carr5c8a0262018-10-03 16:30:44 -07004969}
4970
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004971void InputDispatcher::updateWindowHandlesForDisplayLocked(
chaviw98318de2021-05-19 16:45:23 -05004972 const std::vector<sp<WindowInfoHandle>>& windowInfoHandles, int32_t displayId) {
4973 if (windowInfoHandles.empty()) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004974 // Remove all handles on a display if there are no windows left.
4975 mWindowHandlesByDisplay.erase(displayId);
4976 return;
4977 }
4978
4979 // Since we compare the pointer of input window handles across window updates, we need
4980 // to make sure the handle object for the same window stays unchanged across updates.
chaviw98318de2021-05-19 16:45:23 -05004981 const std::vector<sp<WindowInfoHandle>>& oldHandles = getWindowHandlesLocked(displayId);
4982 std::unordered_map<int32_t /*id*/, sp<WindowInfoHandle>> oldHandlesById;
4983 for (const sp<WindowInfoHandle>& handle : oldHandles) {
chaviwaf87b3e2019-10-01 16:59:28 -07004984 oldHandlesById[handle->getId()] = handle;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004985 }
4986
chaviw98318de2021-05-19 16:45:23 -05004987 std::vector<sp<WindowInfoHandle>> newHandles;
4988 for (const sp<WindowInfoHandle>& handle : windowInfoHandles) {
chaviw98318de2021-05-19 16:45:23 -05004989 const WindowInfo* info = handle->getInfo();
Siarhei Vishniakou64452932020-11-06 17:51:32 -06004990 if (getInputChannelLocked(handle->getToken()) == nullptr) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004991 const bool noInputChannel =
Prabir Pradhan51e7db02022-02-07 06:02:57 -08004992 info->inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08004993 const bool canReceiveInput =
4994 !info->inputConfig.test(WindowInfo::InputConfig::NOT_TOUCHABLE) ||
4995 !info->inputConfig.test(WindowInfo::InputConfig::NOT_FOCUSABLE);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004996 if (canReceiveInput && !noInputChannel) {
John Recke0710582019-09-26 13:46:12 -07004997 ALOGV("Window handle %s has no registered input channel",
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004998 handle->getName().c_str());
Robert Carr2984b7a2020-04-13 17:06:45 -07004999 continue;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005000 }
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005001 }
5002
5003 if (info->displayId != displayId) {
5004 ALOGE("Window %s updated by wrong display %d, should belong to display %d",
5005 handle->getName().c_str(), displayId, info->displayId);
5006 continue;
5007 }
5008
Robert Carredd13602020-04-13 17:24:34 -07005009 if ((oldHandlesById.find(handle->getId()) != oldHandlesById.end()) &&
5010 (oldHandlesById.at(handle->getId())->getToken() == handle->getToken())) {
chaviw98318de2021-05-19 16:45:23 -05005011 const sp<WindowInfoHandle>& oldHandle = oldHandlesById.at(handle->getId());
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005012 oldHandle->updateFrom(handle);
5013 newHandles.push_back(oldHandle);
5014 } else {
5015 newHandles.push_back(handle);
5016 }
5017 }
5018
5019 // Insert or replace
5020 mWindowHandlesByDisplay[displayId] = newHandles;
5021}
5022
Arthur Hungb92218b2018-08-14 12:00:21 +08005023/**
5024 * Called from InputManagerService, update window handle list by displayId that can receive input.
5025 * A window handle contains information about InputChannel, Touch Region, Types, Focused,...
5026 * If set an empty list, remove all handles from the specific display.
5027 * For focused handle, check if need to change and send a cancel event to previous one.
5028 * For removed handle, check if need to send a cancel event if already in touch.
5029 */
Arthur Hung72d8dc32020-03-28 00:48:39 +00005030void InputDispatcher::setInputWindowsLocked(
chaviw98318de2021-05-19 16:45:23 -05005031 const std::vector<sp<WindowInfoHandle>>& windowInfoHandles, int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005032 if (DEBUG_FOCUS) {
5033 std::string windowList;
chaviw98318de2021-05-19 16:45:23 -05005034 for (const sp<WindowInfoHandle>& iwh : windowInfoHandles) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005035 windowList += iwh->getName() + " ";
5036 }
5037 ALOGD("setInputWindows displayId=%" PRId32 " %s", displayId, windowList.c_str());
5038 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005039
Prabir Pradhand65552b2021-10-07 11:23:50 -07005040 // Check preconditions for new input windows
chaviw98318de2021-05-19 16:45:23 -05005041 for (const sp<WindowInfoHandle>& window : windowInfoHandles) {
Prabir Pradhand65552b2021-10-07 11:23:50 -07005042 const WindowInfo& info = *window->getInfo();
5043
5044 // Ensure all tokens are null if the window has feature NO_INPUT_CHANNEL
Prabir Pradhan51e7db02022-02-07 06:02:57 -08005045 const bool noInputWindow = info.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005046 if (noInputWindow && window->getToken() != nullptr) {
5047 ALOGE("%s has feature NO_INPUT_WINDOW, but a non-null token. Clearing",
5048 window->getName().c_str());
5049 window->releaseChannel();
5050 }
Prabir Pradhand65552b2021-10-07 11:23:50 -07005051
Prabir Pradhan5c85e052021-12-22 02:27:12 -08005052 // Ensure all spy windows are trusted overlays
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005053 LOG_ALWAYS_FATAL_IF(info.isSpy() &&
5054 !info.inputConfig.test(
5055 WindowInfo::InputConfig::TRUSTED_OVERLAY),
Prabir Pradhan5c85e052021-12-22 02:27:12 -08005056 "%s has feature SPY, but is not a trusted overlay.",
5057 window->getName().c_str());
5058
Prabir Pradhand65552b2021-10-07 11:23:50 -07005059 // Ensure all stylus interceptors are trusted overlays
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005060 LOG_ALWAYS_FATAL_IF(info.interceptsStylus() &&
5061 !info.inputConfig.test(
5062 WindowInfo::InputConfig::TRUSTED_OVERLAY),
Prabir Pradhand65552b2021-10-07 11:23:50 -07005063 "%s has feature INTERCEPTS_STYLUS, but is not a trusted overlay.",
5064 window->getName().c_str());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005065 }
5066
Arthur Hung72d8dc32020-03-28 00:48:39 +00005067 // Copy old handles for release if they are no longer present.
chaviw98318de2021-05-19 16:45:23 -05005068 const std::vector<sp<WindowInfoHandle>> oldWindowHandles = getWindowHandlesLocked(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005069
chaviw98318de2021-05-19 16:45:23 -05005070 updateWindowHandlesForDisplayLocked(windowInfoHandles, displayId);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005071
chaviw98318de2021-05-19 16:45:23 -05005072 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Arthur Hung72d8dc32020-03-28 00:48:39 +00005073
Vishnu Nairc519ff72021-01-21 08:23:08 -08005074 std::optional<FocusResolver::FocusChanges> changes =
5075 mFocusResolver.setInputWindows(displayId, windowHandles);
5076 if (changes) {
5077 onFocusChangedLocked(*changes);
Arthur Hung72d8dc32020-03-28 00:48:39 +00005078 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005079
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005080 std::unordered_map<int32_t, TouchState>::iterator stateIt =
5081 mTouchStatesByDisplay.find(displayId);
5082 if (stateIt != mTouchStatesByDisplay.end()) {
5083 TouchState& state = stateIt->second;
Arthur Hung72d8dc32020-03-28 00:48:39 +00005084 for (size_t i = 0; i < state.windows.size();) {
5085 TouchedWindow& touchedWindow = state.windows[i];
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07005086 if (getWindowHandleLocked(touchedWindow.windowHandle) == nullptr) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005087 if (DEBUG_FOCUS) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00005088 ALOGD("Touched window was removed: %s in display %" PRId32,
5089 touchedWindow.windowHandle->getName().c_str(), displayId);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005090 }
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005091 std::shared_ptr<InputChannel> touchedInputChannel =
Arthur Hung72d8dc32020-03-28 00:48:39 +00005092 getInputChannelLocked(touchedWindow.windowHandle->getToken());
5093 if (touchedInputChannel != nullptr) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00005094 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
Arthur Hung72d8dc32020-03-28 00:48:39 +00005095 "touched window was removed");
5096 synthesizeCancelationEventsForInputChannelLocked(touchedInputChannel, options);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00005097 // Since we are about to drop the touch, cancel the events for the wallpaper as
5098 // well.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005099 if (touchedWindow.targetFlags.test(InputTarget::Flags::FOREGROUND) &&
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005100 touchedWindow.windowHandle->getInfo()->inputConfig.test(
5101 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER)) {
Siarhei Vishniakouca205502021-07-16 21:31:58 +00005102 sp<WindowInfoHandle> wallpaper = state.getWallpaperWindow();
Arthur Hungc539dbb2022-12-08 07:45:36 +00005103 synthesizeCancelationEventsForWindowLocked(wallpaper, options);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00005104 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005105 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00005106 state.windows.erase(state.windows.begin() + i);
5107 } else {
5108 ++i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005109 }
5110 }
arthurhungb89ccb02020-12-30 16:19:01 +08005111
arthurhung6d4bed92021-03-17 11:59:33 +08005112 // If drag window is gone, it would receive a cancel event and broadcast the DRAG_END. We
arthurhungb89ccb02020-12-30 16:19:01 +08005113 // could just clear the state here.
Arthur Hung3915c1f2022-05-31 07:17:17 +00005114 if (mDragState && mDragState->dragWindow->getInfo()->displayId == displayId &&
arthurhung6d4bed92021-03-17 11:59:33 +08005115 std::find(windowHandles.begin(), windowHandles.end(), mDragState->dragWindow) ==
arthurhungb89ccb02020-12-30 16:19:01 +08005116 windowHandles.end()) {
Arthur Hung3915c1f2022-05-31 07:17:17 +00005117 ALOGI("Drag window went away: %s", mDragState->dragWindow->getName().c_str());
5118 sendDropWindowCommandLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08005119 mDragState.reset();
arthurhungb89ccb02020-12-30 16:19:01 +08005120 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00005121 }
Arthur Hung25e2af12020-03-26 12:58:37 +00005122
Arthur Hung72d8dc32020-03-28 00:48:39 +00005123 // Release information for windows that are no longer present.
5124 // This ensures that unused input channels are released promptly.
5125 // Otherwise, they might stick around until the window handle is destroyed
5126 // which might not happen until the next GC.
chaviw98318de2021-05-19 16:45:23 -05005127 for (const sp<WindowInfoHandle>& oldWindowHandle : oldWindowHandles) {
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07005128 if (getWindowHandleLocked(oldWindowHandle) == nullptr) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00005129 if (DEBUG_FOCUS) {
5130 ALOGD("Window went away: %s", oldWindowHandle->getName().c_str());
Arthur Hung25e2af12020-03-26 12:58:37 +00005131 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00005132 oldWindowHandle->releaseChannel();
Arthur Hung25e2af12020-03-26 12:58:37 +00005133 }
chaviw291d88a2019-02-14 10:33:58 -08005134 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005135}
5136
5137void InputDispatcher::setFocusedApplication(
Chris Yea209fde2020-07-22 13:54:51 -07005138 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005139 if (DEBUG_FOCUS) {
5140 ALOGD("setFocusedApplication displayId=%" PRId32 " %s", displayId,
5141 inputApplicationHandle ? inputApplicationHandle->getName().c_str() : "<nullptr>");
5142 }
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05005143 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005144 std::scoped_lock _l(mLock);
Vishnu Nair599f1412021-06-21 10:39:58 -07005145 setFocusedApplicationLocked(displayId, inputApplicationHandle);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005146 } // release lock
5147
5148 // Wake up poll loop since it may need to make new input dispatching choices.
5149 mLooper->wake();
5150}
5151
Vishnu Nair599f1412021-06-21 10:39:58 -07005152void InputDispatcher::setFocusedApplicationLocked(
5153 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
5154 std::shared_ptr<InputApplicationHandle> oldFocusedApplicationHandle =
5155 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
5156
5157 if (sharedPointersEqual(oldFocusedApplicationHandle, inputApplicationHandle)) {
5158 return; // This application is already focused. No need to wake up or change anything.
5159 }
5160
5161 // Set the new application handle.
5162 if (inputApplicationHandle != nullptr) {
5163 mFocusedApplicationHandlesByDisplay[displayId] = inputApplicationHandle;
5164 } else {
5165 mFocusedApplicationHandlesByDisplay.erase(displayId);
5166 }
5167
5168 // No matter what the old focused application was, stop waiting on it because it is
5169 // no longer focused.
5170 resetNoFocusedWindowTimeoutLocked();
5171}
5172
Tiger Huang721e26f2018-07-24 22:26:19 +08005173/**
5174 * Sets the focused display, which is responsible for receiving focus-dispatched input events where
5175 * the display not specified.
5176 *
5177 * We track any unreleased events for each window. If a window loses the ability to receive the
5178 * released event, we will send a cancel event to it. So when the focused display is changed, we
5179 * cancel all the unreleased display-unspecified events for the focused window on the old focused
5180 * display. The display-specified events won't be affected.
5181 */
5182void InputDispatcher::setFocusedDisplay(int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005183 if (DEBUG_FOCUS) {
5184 ALOGD("setFocusedDisplay displayId=%" PRId32, displayId);
5185 }
Tiger Huang721e26f2018-07-24 22:26:19 +08005186 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005187 std::scoped_lock _l(mLock);
Tiger Huang721e26f2018-07-24 22:26:19 +08005188
5189 if (mFocusedDisplayId != displayId) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07005190 sp<IBinder> oldFocusedWindowToken =
Vishnu Nairc519ff72021-01-21 08:23:08 -08005191 mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07005192 if (oldFocusedWindowToken != nullptr) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005193 std::shared_ptr<InputChannel> inputChannel =
Vishnu Nairad321cd2020-08-20 16:40:21 -07005194 getInputChannelLocked(oldFocusedWindowToken);
Tiger Huang721e26f2018-07-24 22:26:19 +08005195 if (inputChannel != nullptr) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005196 CancelationOptions
Michael Wrightfb04fd52022-11-24 22:31:11 +00005197 options(CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005198 "The display which contains this window no longer has focus.");
Michael Wright3dd60e22019-03-27 22:06:44 +00005199 options.displayId = ADISPLAY_ID_NONE;
Tiger Huang721e26f2018-07-24 22:26:19 +08005200 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
5201 }
5202 }
5203 mFocusedDisplayId = displayId;
5204
Chris Ye3c2d6f52020-08-09 10:39:48 -07005205 // Find new focused window and validate
Vishnu Nairc519ff72021-01-21 08:23:08 -08005206 sp<IBinder> newFocusedWindowToken = mFocusResolver.getFocusedWindowToken(displayId);
Prabir Pradhancef936d2021-07-21 16:17:52 +00005207 sendFocusChangedCommandLocked(oldFocusedWindowToken, newFocusedWindowToken);
Robert Carrf759f162018-11-13 12:57:11 -08005208
Vishnu Nairad321cd2020-08-20 16:40:21 -07005209 if (newFocusedWindowToken == nullptr) {
Tiger Huang721e26f2018-07-24 22:26:19 +08005210 ALOGW("Focused display #%" PRId32 " does not have a focused window.", displayId);
Vishnu Nairc519ff72021-01-21 08:23:08 -08005211 if (mFocusResolver.hasFocusedWindowTokens()) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07005212 ALOGE("But another display has a focused window\n%s",
Vishnu Nairc519ff72021-01-21 08:23:08 -08005213 mFocusResolver.dumpFocusedWindows().c_str());
Tiger Huang721e26f2018-07-24 22:26:19 +08005214 }
5215 }
5216 }
Tiger Huang721e26f2018-07-24 22:26:19 +08005217 } // release lock
5218
5219 // Wake up poll loop since it may need to make new input dispatching choices.
5220 mLooper->wake();
5221}
5222
Michael Wrightd02c5b62014-02-10 15:10:22 -08005223void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005224 if (DEBUG_FOCUS) {
5225 ALOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
5226 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005227
5228 bool changed;
5229 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005230 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005231
5232 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
5233 if (mDispatchFrozen && !frozen) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005234 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005235 }
5236
5237 if (mDispatchEnabled && !enabled) {
5238 resetAndDropEverythingLocked("dispatcher is being disabled");
5239 }
5240
5241 mDispatchEnabled = enabled;
5242 mDispatchFrozen = frozen;
5243 changed = true;
5244 } else {
5245 changed = false;
5246 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005247 } // release lock
5248
5249 if (changed) {
5250 // Wake up poll loop since it may need to make new input dispatching choices.
5251 mLooper->wake();
5252 }
5253}
5254
5255void InputDispatcher::setInputFilterEnabled(bool enabled) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005256 if (DEBUG_FOCUS) {
5257 ALOGD("setInputFilterEnabled: enabled=%d", enabled);
5258 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005259
5260 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005261 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005262
5263 if (mInputFilterEnabled == enabled) {
5264 return;
5265 }
5266
5267 mInputFilterEnabled = enabled;
5268 resetAndDropEverythingLocked("input filter is being enabled or disabled");
5269 } // release lock
5270
5271 // Wake up poll loop since there might be work to do to drop everything.
5272 mLooper->wake();
5273}
5274
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005275bool InputDispatcher::setInTouchMode(bool inTouchMode, gui::Pid pid, gui::Uid uid,
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00005276 bool hasPermission, int32_t displayId) {
Antonio Kantekf16f2832021-09-28 04:39:20 +00005277 bool needWake = false;
5278 {
5279 std::scoped_lock lock(mLock);
Antonio Kantek15beb512022-06-13 22:35:41 +00005280 ALOGD_IF(DEBUG_TOUCH_MODE,
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005281 "Request to change touch mode to %s (calling pid=%s, uid=%s, "
Antonio Kantek15beb512022-06-13 22:35:41 +00005282 "hasPermission=%s, target displayId=%d, mTouchModePerDisplay[displayId]=%s)",
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005283 toString(inTouchMode), pid.toString().c_str(), uid.toString().c_str(),
5284 toString(hasPermission), displayId,
Antonio Kantek15beb512022-06-13 22:35:41 +00005285 mTouchModePerDisplay.count(displayId) == 0
5286 ? "not set"
5287 : std::to_string(mTouchModePerDisplay[displayId]).c_str());
5288
Antonio Kantek15beb512022-06-13 22:35:41 +00005289 auto touchModeIt = mTouchModePerDisplay.find(displayId);
5290 if (touchModeIt != mTouchModePerDisplay.end() && touchModeIt->second == inTouchMode) {
Antonio Kantekea47acb2021-12-23 12:41:25 -08005291 return false;
Antonio Kantekf16f2832021-09-28 04:39:20 +00005292 }
Antonio Kantekea47acb2021-12-23 12:41:25 -08005293 if (!hasPermission) {
Antonio Kantek48710e42022-03-24 14:19:30 -07005294 if (!focusedWindowIsOwnedByLocked(pid, uid) &&
5295 !recentWindowsAreOwnedByLocked(pid, uid)) {
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005296 ALOGD("Touch mode switch rejected, caller (pid=%s, uid=%s) doesn't own the focused "
Antonio Kantek48710e42022-03-24 14:19:30 -07005297 "window nor none of the previously interacted window",
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005298 pid.toString().c_str(), uid.toString().c_str());
Antonio Kantekea47acb2021-12-23 12:41:25 -08005299 return false;
5300 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00005301 }
Antonio Kantek15beb512022-06-13 22:35:41 +00005302 mTouchModePerDisplay[displayId] = inTouchMode;
5303 auto entry = std::make_unique<TouchModeEntry>(mIdGenerator.nextId(), now(), inTouchMode,
5304 displayId);
Antonio Kantekf16f2832021-09-28 04:39:20 +00005305 needWake = enqueueInboundEventLocked(std::move(entry));
5306 } // release lock
5307
5308 if (needWake) {
5309 mLooper->wake();
5310 }
Antonio Kantekea47acb2021-12-23 12:41:25 -08005311 return true;
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -08005312}
5313
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005314bool InputDispatcher::focusedWindowIsOwnedByLocked(gui::Pid pid, gui::Uid uid) {
Antonio Kantek48710e42022-03-24 14:19:30 -07005315 const sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
5316 if (focusedToken == nullptr) {
5317 return false;
5318 }
5319 sp<WindowInfoHandle> windowHandle = getWindowHandleLocked(focusedToken);
5320 return isWindowOwnedBy(windowHandle, pid, uid);
5321}
5322
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005323bool InputDispatcher::recentWindowsAreOwnedByLocked(gui::Pid pid, gui::Uid uid) {
Antonio Kantek48710e42022-03-24 14:19:30 -07005324 return std::find_if(mInteractionConnectionTokens.begin(), mInteractionConnectionTokens.end(),
5325 [&](const sp<IBinder>& connectionToken) REQUIRES(mLock) {
5326 const sp<WindowInfoHandle> windowHandle =
5327 getWindowHandleLocked(connectionToken);
5328 return isWindowOwnedBy(windowHandle, pid, uid);
5329 }) != mInteractionConnectionTokens.end();
5330}
5331
Bernardo Rufinoea97d182020-08-19 14:43:14 +01005332void InputDispatcher::setMaximumObscuringOpacityForTouch(float opacity) {
5333 if (opacity < 0 || opacity > 1) {
5334 LOG_ALWAYS_FATAL("Maximum obscuring opacity for touch should be >= 0 and <= 1");
5335 return;
5336 }
5337
5338 std::scoped_lock lock(mLock);
5339 mMaximumObscuringOpacityForTouch = opacity;
5340}
5341
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005342std::tuple<TouchState*, TouchedWindow*, int32_t /*displayId*/>
5343InputDispatcher::findTouchStateWindowAndDisplayLocked(const sp<IBinder>& token) {
Arthur Hungabbb9d82021-09-01 14:52:30 +00005344 for (auto& [displayId, state] : mTouchStatesByDisplay) {
5345 for (TouchedWindow& w : state.windows) {
5346 if (w.windowHandle->getToken() == token) {
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005347 return std::make_tuple(&state, &w, displayId);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005348 }
5349 }
5350 }
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005351 return std::make_tuple(nullptr, nullptr, ADISPLAY_ID_DEFAULT);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005352}
5353
arthurhungb89ccb02020-12-30 16:19:01 +08005354bool InputDispatcher::transferTouchFocus(const sp<IBinder>& fromToken, const sp<IBinder>& toToken,
5355 bool isDragDrop) {
chaviwfbe5d9c2018-12-26 12:23:37 -08005356 if (fromToken == toToken) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005357 if (DEBUG_FOCUS) {
5358 ALOGD("Trivial transfer to same window.");
5359 }
chaviwfbe5d9c2018-12-26 12:23:37 -08005360 return true;
5361 }
5362
Michael Wrightd02c5b62014-02-10 15:10:22 -08005363 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005364 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005365
Arthur Hungabbb9d82021-09-01 14:52:30 +00005366 // Find the target touch state and touched window by fromToken.
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005367 auto [state, touchedWindow, displayId] = findTouchStateWindowAndDisplayLocked(fromToken);
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005368
Arthur Hungabbb9d82021-09-01 14:52:30 +00005369 if (state == nullptr || touchedWindow == nullptr) {
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005370 ALOGD("Touch transfer failed because from window is not being touched.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005371 return false;
5372 }
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005373 std::set<int32_t> deviceIds = touchedWindow->getTouchingDeviceIds();
5374 if (deviceIds.size() != 1) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07005375 LOG(INFO) << "Can't transfer touch. Currently touching devices: " << dumpSet(deviceIds)
5376 << " for window: " << touchedWindow->dump();
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005377 return false;
5378 }
5379 const int32_t deviceId = *deviceIds.begin();
Arthur Hungabbb9d82021-09-01 14:52:30 +00005380
Arthur Hungabbb9d82021-09-01 14:52:30 +00005381 sp<WindowInfoHandle> toWindowHandle = getWindowHandleLocked(toToken, displayId);
5382 if (toWindowHandle == nullptr) {
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005383 ALOGW("Cannot transfer touch because to window not found.");
Arthur Hungabbb9d82021-09-01 14:52:30 +00005384 return false;
5385 }
5386
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005387 if (DEBUG_FOCUS) {
5388 ALOGD("transferTouchFocus: fromWindowHandle=%s, toWindowHandle=%s",
Arthur Hungabbb9d82021-09-01 14:52:30 +00005389 touchedWindow->windowHandle->getName().c_str(),
5390 toWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005391 }
5392
Arthur Hungabbb9d82021-09-01 14:52:30 +00005393 // Erase old window.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005394 ftl::Flags<InputTarget::Flags> oldTargetFlags = touchedWindow->targetFlags;
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005395 std::bitset<MAX_POINTER_ID + 1> pointerIds = touchedWindow->getTouchingPointers(deviceId);
Arthur Hungc539dbb2022-12-08 07:45:36 +00005396 sp<WindowInfoHandle> fromWindowHandle = touchedWindow->windowHandle;
Arthur Hungabbb9d82021-09-01 14:52:30 +00005397 state->removeWindowByToken(fromToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005398
Arthur Hungabbb9d82021-09-01 14:52:30 +00005399 // Add new window.
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00005400 nsecs_t downTimeInTarget = now();
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005401 ftl::Flags<InputTarget::Flags> newTargetFlags =
5402 oldTargetFlags & (InputTarget::Flags::SPLIT | InputTarget::Flags::DISPATCH_AS_IS);
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00005403 if (canReceiveForegroundTouches(*toWindowHandle->getInfo())) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005404 newTargetFlags |= InputTarget::Flags::FOREGROUND;
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00005405 }
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005406 state->addOrUpdateWindow(toWindowHandle, newTargetFlags, deviceId, pointerIds,
5407 downTimeInTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005408
Arthur Hungabbb9d82021-09-01 14:52:30 +00005409 // Store the dragging window.
5410 if (isDragDrop) {
Arthur Hungb75c2aa2022-07-15 09:35:36 +00005411 if (pointerIds.count() != 1) {
5412 ALOGW("The drag and drop cannot be started when there is no pointer or more than 1"
5413 " pointer on the window.");
Arthur Hung54745652022-04-20 07:17:41 +00005414 return false;
5415 }
Arthur Hungb75c2aa2022-07-15 09:35:36 +00005416 // Track the pointer id for drag window and generate the drag state.
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08005417 const size_t id = firstMarkedBit(pointerIds);
Arthur Hung54745652022-04-20 07:17:41 +00005418 mDragState = std::make_unique<DragState>(toWindowHandle, id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005419 }
5420
Arthur Hungabbb9d82021-09-01 14:52:30 +00005421 // Synthesize cancel for old window and down for new window.
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07005422 std::shared_ptr<Connection> fromConnection = getConnectionLocked(fromToken);
5423 std::shared_ptr<Connection> toConnection = getConnectionLocked(toToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005424 if (fromConnection != nullptr && toConnection != nullptr) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08005425 fromConnection->inputState.mergePointerStateTo(toConnection->inputState);
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005426 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
5427 "transferring touch from this window to another window");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005428 synthesizeCancelationEventsForConnectionLocked(fromConnection, options);
Arthur Hungc539dbb2022-12-08 07:45:36 +00005429 synthesizePointerDownEventsForConnectionLocked(downTimeInTarget, toConnection,
5430 newTargetFlags);
5431
5432 // Check if the wallpaper window should deliver the corresponding event.
5433 transferWallpaperTouch(oldTargetFlags, newTargetFlags, fromWindowHandle, toWindowHandle,
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005434 *state, deviceId, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005435 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005436 } // release lock
5437
5438 // Wake up poll loop since it may need to make new input dispatching choices.
5439 mLooper->wake();
5440 return true;
5441}
5442
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005443/**
5444 * Get the touched foreground window on the given display.
5445 * Return null if there are no windows touched on that display, or if more than one foreground
5446 * window is being touched.
5447 */
5448sp<WindowInfoHandle> InputDispatcher::findTouchedForegroundWindowLocked(int32_t displayId) const {
5449 auto stateIt = mTouchStatesByDisplay.find(displayId);
5450 if (stateIt == mTouchStatesByDisplay.end()) {
5451 ALOGI("No touch state on display %" PRId32, displayId);
5452 return nullptr;
5453 }
5454
5455 const TouchState& state = stateIt->second;
5456 sp<WindowInfoHandle> touchedForegroundWindow;
5457 // If multiple foreground windows are touched, return nullptr
5458 for (const TouchedWindow& window : state.windows) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005459 if (window.targetFlags.test(InputTarget::Flags::FOREGROUND)) {
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005460 if (touchedForegroundWindow != nullptr) {
5461 ALOGI("Two or more foreground windows: %s and %s",
5462 touchedForegroundWindow->getName().c_str(),
5463 window.windowHandle->getName().c_str());
5464 return nullptr;
5465 }
5466 touchedForegroundWindow = window.windowHandle;
5467 }
5468 }
5469 return touchedForegroundWindow;
5470}
5471
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005472// Binder call
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005473bool InputDispatcher::transferTouch(const sp<IBinder>& destChannelToken, int32_t displayId) {
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005474 sp<IBinder> fromToken;
5475 { // acquire lock
5476 std::scoped_lock _l(mLock);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005477 sp<WindowInfoHandle> toWindowHandle = getWindowHandleLocked(destChannelToken, displayId);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005478 if (toWindowHandle == nullptr) {
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005479 ALOGW("Could not find window associated with token=%p on display %" PRId32,
5480 destChannelToken.get(), displayId);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005481 return false;
5482 }
5483
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005484 sp<WindowInfoHandle> from = findTouchedForegroundWindowLocked(displayId);
5485 if (from == nullptr) {
5486 ALOGE("Could not find a source window in %s for %p", __func__, destChannelToken.get());
5487 return false;
5488 }
5489
5490 fromToken = from->getToken();
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005491 } // release lock
5492
5493 return transferTouchFocus(fromToken, destChannelToken);
5494}
5495
Michael Wrightd02c5b62014-02-10 15:10:22 -08005496void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005497 if (DEBUG_FOCUS) {
5498 ALOGD("Resetting and dropping all events (%s).", reason);
5499 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005500
Michael Wrightfb04fd52022-11-24 22:31:11 +00005501 CancelationOptions options(CancelationOptions::Mode::CANCEL_ALL_EVENTS, reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005502 synthesizeCancelationEventsForAllConnectionsLocked(options);
5503
5504 resetKeyRepeatLocked();
5505 releasePendingEventLocked();
5506 drainInboundQueueLocked();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005507 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005508
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005509 mAnrTracker.clear();
Jeff Brownf086ddb2014-02-11 14:28:48 -08005510 mTouchStatesByDisplay.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005511}
5512
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005513void InputDispatcher::logDispatchStateLocked() const {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005514 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005515 dumpDispatchStateLocked(dump);
5516
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005517 std::istringstream stream(dump);
5518 std::string line;
5519
5520 while (std::getline(stream, line, '\n')) {
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07005521 ALOGI("%s", line.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005522 }
5523}
5524
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005525std::string InputDispatcher::dumpPointerCaptureStateLocked() const {
Prabir Pradhan99987712020-11-10 18:43:05 -08005526 std::string dump;
5527
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005528 dump += StringPrintf(INDENT "Pointer Capture Requested: %s\n",
5529 toString(mCurrentPointerCaptureRequest.enable));
Prabir Pradhan99987712020-11-10 18:43:05 -08005530
5531 std::string windowName = "None";
5532 if (mWindowTokenWithPointerCapture) {
chaviw98318de2021-05-19 16:45:23 -05005533 const sp<WindowInfoHandle> captureWindowHandle =
Prabir Pradhan99987712020-11-10 18:43:05 -08005534 getWindowHandleLocked(mWindowTokenWithPointerCapture);
5535 windowName = captureWindowHandle ? captureWindowHandle->getName().c_str()
5536 : "token has capture without window";
5537 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005538 dump += StringPrintf(INDENT "Current Window with Pointer Capture: %s\n", windowName.c_str());
Prabir Pradhan99987712020-11-10 18:43:05 -08005539
5540 return dump;
5541}
5542
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005543void InputDispatcher::dumpDispatchStateLocked(std::string& dump) const {
Siarhei Vishniakou043a3ec2019-05-01 11:30:46 -07005544 dump += StringPrintf(INDENT "DispatchEnabled: %s\n", toString(mDispatchEnabled));
5545 dump += StringPrintf(INDENT "DispatchFrozen: %s\n", toString(mDispatchFrozen));
5546 dump += StringPrintf(INDENT "InputFilterEnabled: %s\n", toString(mInputFilterEnabled));
Tiger Huang721e26f2018-07-24 22:26:19 +08005547 dump += StringPrintf(INDENT "FocusedDisplayId: %" PRId32 "\n", mFocusedDisplayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005548
Tiger Huang721e26f2018-07-24 22:26:19 +08005549 if (!mFocusedApplicationHandlesByDisplay.empty()) {
5550 dump += StringPrintf(INDENT "FocusedApplications:\n");
5551 for (auto& it : mFocusedApplicationHandlesByDisplay) {
5552 const int32_t displayId = it.first;
Chris Yea209fde2020-07-22 13:54:51 -07005553 const std::shared_ptr<InputApplicationHandle>& applicationHandle = it.second;
Siarhei Vishniakou70622952020-07-30 11:17:23 -05005554 const std::chrono::duration timeout =
5555 applicationHandle->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005556 dump += StringPrintf(INDENT2 "displayId=%" PRId32
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005557 ", name='%s', dispatchingTimeout=%" PRId64 "ms\n",
Siarhei Vishniakou70622952020-07-30 11:17:23 -05005558 displayId, applicationHandle->getName().c_str(), millis(timeout));
Tiger Huang721e26f2018-07-24 22:26:19 +08005559 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005560 } else {
Tiger Huang721e26f2018-07-24 22:26:19 +08005561 dump += StringPrintf(INDENT "FocusedApplications: <none>\n");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005562 }
Tiger Huang721e26f2018-07-24 22:26:19 +08005563
Vishnu Nairc519ff72021-01-21 08:23:08 -08005564 dump += mFocusResolver.dump();
Prabir Pradhan99987712020-11-10 18:43:05 -08005565 dump += dumpPointerCaptureStateLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005566
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005567 if (!mTouchStatesByDisplay.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005568 dump += StringPrintf(INDENT "TouchStatesByDisplay:\n");
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005569 for (const auto& [displayId, state] : mTouchStatesByDisplay) {
Siarhei Vishniakou6e1e9872022-11-08 17:51:35 -08005570 std::string touchStateDump = addLinePrefix(state.dump(), INDENT2);
5571 dump += INDENT2 + std::to_string(displayId) + " : " + touchStateDump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005572 }
5573 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005574 dump += INDENT "TouchStates: <no displays touched>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005575 }
5576
arthurhung6d4bed92021-03-17 11:59:33 +08005577 if (mDragState) {
5578 dump += StringPrintf(INDENT "DragState:\n");
5579 mDragState->dump(dump, INDENT2);
5580 }
5581
Arthur Hungb92218b2018-08-14 12:00:21 +08005582 if (!mWindowHandlesByDisplay.empty()) {
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005583 for (const auto& [displayId, windowHandles] : mWindowHandlesByDisplay) {
5584 dump += StringPrintf(INDENT "Display: %" PRId32 "\n", displayId);
5585 if (const auto& it = mDisplayInfos.find(displayId); it != mDisplayInfos.end()) {
5586 const auto& displayInfo = it->second;
5587 dump += StringPrintf(INDENT2 "logicalSize=%dx%d\n", displayInfo.logicalWidth,
5588 displayInfo.logicalHeight);
5589 displayInfo.transform.dump(dump, "transform", INDENT4);
5590 } else {
5591 dump += INDENT2 "No DisplayInfo found!\n";
5592 }
5593
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08005594 if (!windowHandles.empty()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08005595 dump += INDENT2 "Windows:\n";
5596 for (size_t i = 0; i < windowHandles.size(); i++) {
chaviw98318de2021-05-19 16:45:23 -05005597 const sp<WindowInfoHandle>& windowHandle = windowHandles[i];
5598 const WindowInfo* windowInfo = windowHandle->getInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005599
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00005600 dump += StringPrintf(INDENT3 "%zu: name='%s', id=%" PRId32 ", displayId=%d, "
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005601 "inputConfig=%s, alpha=%.2f, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005602 "frame=[%d,%d][%d,%d], globalScale=%f, "
Bernardo Rufino49d99e42021-01-18 15:16:59 +00005603 "applicationInfo.name=%s, "
5604 "applicationInfo.token=%s, "
chaviw1ff3d1e2020-07-01 15:53:47 -07005605 "touchableRegion=",
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00005606 i, windowInfo->name.c_str(), windowInfo->id,
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005607 windowInfo->displayId,
5608 windowInfo->inputConfig.string().c_str(),
Chavi Weingarten7f019192023-08-08 20:39:01 +00005609 windowInfo->alpha, windowInfo->frame.left,
5610 windowInfo->frame.top, windowInfo->frame.right,
5611 windowInfo->frame.bottom, windowInfo->globalScaleFactor,
Bernardo Rufino49d99e42021-01-18 15:16:59 +00005612 windowInfo->applicationInfo.name.c_str(),
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07005613 binderToString(windowInfo->applicationInfo.token).c_str());
Bernardo Rufino53fc31e2020-11-03 11:01:07 +00005614 dump += dumpRegion(windowInfo->touchableRegion);
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005615 dump += StringPrintf(", ownerPid=%s, ownerUid=%s, dispatchingTimeout=%" PRId64
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005616 "ms, hasToken=%s, "
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005617 "touchOcclusionMode=%s\n",
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005618 windowInfo->ownerPid.toString().c_str(),
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00005619 windowInfo->ownerUid.toString().c_str(),
Bernardo Rufinoc2f1fad2020-11-04 17:30:57 +00005620 millis(windowInfo->dispatchingTimeout),
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07005621 binderToString(windowInfo->token).c_str(),
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005622 toString(windowInfo->touchOcclusionMode).c_str());
chaviw85b44202020-07-24 11:46:21 -07005623 windowInfo->transform.dump(dump, "transform", INDENT4);
Arthur Hungb92218b2018-08-14 12:00:21 +08005624 }
5625 } else {
5626 dump += INDENT2 "Windows: <none>\n";
5627 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005628 }
5629 } else {
Arthur Hungb92218b2018-08-14 12:00:21 +08005630 dump += INDENT "Displays: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005631 }
5632
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005633 if (!mGlobalMonitorsByDisplay.empty()) {
5634 for (const auto& [displayId, monitors] : mGlobalMonitorsByDisplay) {
5635 dump += StringPrintf(INDENT "Global monitors on display %d:\n", displayId);
Michael Wright3dd60e22019-03-27 22:06:44 +00005636 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005637 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005638 } else {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005639 dump += INDENT "Global Monitors: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005640 }
5641
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005642 const nsecs_t currentTime = now();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005643
5644 // Dump recently dispatched or dropped events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005645 if (!mRecentQueue.empty()) {
5646 dump += StringPrintf(INDENT "RecentQueue: length=%zu\n", mRecentQueue.size());
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005647 for (const std::shared_ptr<EventEntry>& entry : mRecentQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005648 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005649 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005650 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005651 }
5652 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005653 dump += INDENT "RecentQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005654 }
5655
5656 // Dump event currently being dispatched.
5657 if (mPendingEvent) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005658 dump += INDENT "PendingEvent:\n";
5659 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005660 dump += mPendingEvent->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005661 dump += StringPrintf(", age=%" PRId64 "ms\n",
5662 ns2ms(currentTime - mPendingEvent->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005663 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005664 dump += INDENT "PendingEvent: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005665 }
5666
5667 // Dump inbound events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005668 if (!mInboundQueue.empty()) {
5669 dump += StringPrintf(INDENT "InboundQueue: length=%zu\n", mInboundQueue.size());
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005670 for (const std::shared_ptr<EventEntry>& entry : mInboundQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005671 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005672 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005673 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005674 }
5675 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005676 dump += INDENT "InboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005677 }
5678
Prabir Pradhancef936d2021-07-21 16:17:52 +00005679 if (!mCommandQueue.empty()) {
5680 dump += StringPrintf(INDENT "CommandQueue: size=%zu\n", mCommandQueue.size());
5681 } else {
5682 dump += INDENT "CommandQueue: <empty>\n";
5683 }
5684
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005685 if (!mConnectionsByToken.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005686 dump += INDENT "Connections:\n";
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005687 for (const auto& [token, connection] : mConnectionsByToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005688 dump += StringPrintf(INDENT2 "%i: channelName='%s', windowName='%s', "
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005689 "status=%s, monitor=%s, responsive=%s\n",
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005690 connection->inputChannel->getFd().get(),
5691 connection->getInputChannelName().c_str(),
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08005692 connection->getWindowName().c_str(),
5693 ftl::enum_string(connection->status).c_str(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005694 toString(connection->monitor), toString(connection->responsive));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005695
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005696 if (!connection->outboundQueue.empty()) {
5697 dump += StringPrintf(INDENT3 "OutboundQueue: length=%zu\n",
5698 connection->outboundQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005699 dump += dumpQueue(connection->outboundQueue, currentTime);
5700
Michael Wrightd02c5b62014-02-10 15:10:22 -08005701 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005702 dump += INDENT3 "OutboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005703 }
5704
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005705 if (!connection->waitQueue.empty()) {
5706 dump += StringPrintf(INDENT3 "WaitQueue: length=%zu\n",
5707 connection->waitQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005708 dump += dumpQueue(connection->waitQueue, currentTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005709 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005710 dump += INDENT3 "WaitQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005711 }
Siarhei Vishniakoud38a1e02023-07-18 11:55:17 -07005712 std::stringstream inputStateDump;
5713 inputStateDump << connection->inputState;
5714 if (!isEmpty(inputStateDump)) {
5715 dump += INDENT3 "InputState: ";
5716 dump += inputStateDump.str() + "\n";
5717 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005718 }
5719 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005720 dump += INDENT "Connections: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005721 }
5722
5723 if (isAppSwitchPendingLocked()) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005724 dump += StringPrintf(INDENT "AppSwitch: pending, due in %" PRId64 "ms\n",
5725 ns2ms(mAppSwitchDueTime - now()));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005726 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005727 dump += INDENT "AppSwitch: not pending\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005728 }
5729
Antonio Kantek15beb512022-06-13 22:35:41 +00005730 if (!mTouchModePerDisplay.empty()) {
5731 dump += INDENT "TouchModePerDisplay:\n";
5732 for (const auto& [displayId, touchMode] : mTouchModePerDisplay) {
5733 dump += StringPrintf(INDENT2 "Display: %" PRId32 " TouchMode: %s\n", displayId,
5734 std::to_string(touchMode).c_str());
5735 }
5736 } else {
5737 dump += INDENT "TouchModePerDisplay: <none>\n";
5738 }
5739
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005740 dump += INDENT "Configuration:\n";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005741 dump += StringPrintf(INDENT2 "KeyRepeatDelay: %" PRId64 "ms\n", ns2ms(mConfig.keyRepeatDelay));
5742 dump += StringPrintf(INDENT2 "KeyRepeatTimeout: %" PRId64 "ms\n",
5743 ns2ms(mConfig.keyRepeatTimeout));
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00005744 dump += mLatencyTracker.dump(INDENT2);
Siarhei Vishniakoua04181f2021-03-26 05:56:49 +00005745 dump += mLatencyAggregator.dump(INDENT2);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005746}
5747
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005748void InputDispatcher::dumpMonitors(std::string& dump, const std::vector<Monitor>& monitors) const {
Michael Wright3dd60e22019-03-27 22:06:44 +00005749 const size_t numMonitors = monitors.size();
5750 for (size_t i = 0; i < numMonitors; i++) {
5751 const Monitor& monitor = monitors[i];
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005752 const std::shared_ptr<InputChannel>& channel = monitor.inputChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005753 dump += StringPrintf(INDENT2 "%zu: '%s', ", i, channel->getName().c_str());
5754 dump += "\n";
5755 }
5756}
5757
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005758class LooperEventCallback : public LooperCallback {
5759public:
5760 LooperEventCallback(std::function<int(int events)> callback) : mCallback(callback) {}
5761 int handleEvent(int /*fd*/, int events, void* /*data*/) override { return mCallback(events); }
5762
5763private:
5764 std::function<int(int events)> mCallback;
5765};
5766
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005767Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputChannel(const std::string& name) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00005768 if (DEBUG_CHANNEL_CREATION) {
5769 ALOGD("channel '%s' ~ createInputChannel", name.c_str());
5770 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005771
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005772 std::unique_ptr<InputChannel> serverChannel;
Garfield Tan15601662020-09-22 15:32:38 -07005773 std::unique_ptr<InputChannel> clientChannel;
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005774 status_t result = InputChannel::openInputChannelPair(name, serverChannel, clientChannel);
Garfield Tan15601662020-09-22 15:32:38 -07005775
5776 if (result) {
5777 return base::Error(result) << "Failed to open input channel pair with name " << name;
5778 }
5779
Michael Wrightd02c5b62014-02-10 15:10:22 -08005780 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005781 std::scoped_lock _l(mLock);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005782 const sp<IBinder>& token = serverChannel->getConnectionToken();
Garfield Tan15601662020-09-22 15:32:38 -07005783 int fd = serverChannel->getFd();
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07005784 std::shared_ptr<Connection> connection =
5785 std::make_shared<Connection>(std::move(serverChannel), /*monitor=*/false,
5786 mIdGenerator);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005787
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005788 if (mConnectionsByToken.find(token) != mConnectionsByToken.end()) {
5789 ALOGE("Created a new connection, but the token %p is already known", token.get());
5790 }
5791 mConnectionsByToken.emplace(token, connection);
5792
5793 std::function<int(int events)> callback = std::bind(&InputDispatcher::handleReceiveCallback,
5794 this, std::placeholders::_1, token);
5795
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005796 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, sp<LooperEventCallback>::make(callback),
5797 nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005798 } // release lock
5799
5800 // Wake the looper because some connections have changed.
5801 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07005802 return clientChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005803}
5804
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005805Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputMonitor(int32_t displayId,
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005806 const std::string& name,
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005807 gui::Pid pid) {
Garfield Tan15601662020-09-22 15:32:38 -07005808 std::shared_ptr<InputChannel> serverChannel;
5809 std::unique_ptr<InputChannel> clientChannel;
5810 status_t result = openInputChannelPair(name, serverChannel, clientChannel);
5811 if (result) {
5812 return base::Error(result) << "Failed to open input channel pair with name " << name;
5813 }
5814
Michael Wright3dd60e22019-03-27 22:06:44 +00005815 { // acquire lock
5816 std::scoped_lock _l(mLock);
5817
5818 if (displayId < 0) {
Garfield Tan15601662020-09-22 15:32:38 -07005819 return base::Error(BAD_VALUE) << "Attempted to create input monitor with name " << name
5820 << " without a specified display.";
Michael Wright3dd60e22019-03-27 22:06:44 +00005821 }
5822
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07005823 std::shared_ptr<Connection> connection =
5824 std::make_shared<Connection>(serverChannel, /*monitor=*/true, mIdGenerator);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005825 const sp<IBinder>& token = serverChannel->getConnectionToken();
Garfield Tan15601662020-09-22 15:32:38 -07005826 const int fd = serverChannel->getFd();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005827
5828 if (mConnectionsByToken.find(token) != mConnectionsByToken.end()) {
5829 ALOGE("Created a new connection, but the token %p is already known", token.get());
5830 }
5831 mConnectionsByToken.emplace(token, connection);
5832 std::function<int(int events)> callback = std::bind(&InputDispatcher::handleReceiveCallback,
5833 this, std::placeholders::_1, token);
Michael Wright3dd60e22019-03-27 22:06:44 +00005834
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005835 mGlobalMonitorsByDisplay[displayId].emplace_back(serverChannel, pid);
Michael Wright3dd60e22019-03-27 22:06:44 +00005836
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005837 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, sp<LooperEventCallback>::make(callback),
5838 nullptr);
Michael Wright3dd60e22019-03-27 22:06:44 +00005839 }
Garfield Tan15601662020-09-22 15:32:38 -07005840
Michael Wright3dd60e22019-03-27 22:06:44 +00005841 // Wake the looper because some connections have changed.
5842 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07005843 return clientChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005844}
5845
Garfield Tan15601662020-09-22 15:32:38 -07005846status_t InputDispatcher::removeInputChannel(const sp<IBinder>& connectionToken) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005847 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005848 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005849
Harry Cutts33476232023-01-30 19:57:29 +00005850 status_t status = removeInputChannelLocked(connectionToken, /*notify=*/false);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005851 if (status) {
5852 return status;
5853 }
5854 } // release lock
5855
5856 // Wake the poll loop because removing the connection may have changed the current
5857 // synchronization state.
5858 mLooper->wake();
5859 return OK;
5860}
5861
Garfield Tan15601662020-09-22 15:32:38 -07005862status_t InputDispatcher::removeInputChannelLocked(const sp<IBinder>& connectionToken,
5863 bool notify) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07005864 std::shared_ptr<Connection> connection = getConnectionLocked(connectionToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005865 if (connection == nullptr) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005866 // Connection can be removed via socket hang up or an explicit call to 'removeInputChannel'
Michael Wrightd02c5b62014-02-10 15:10:22 -08005867 return BAD_VALUE;
5868 }
5869
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005870 removeConnectionLocked(connection);
Robert Carr5c8a0262018-10-03 16:30:44 -07005871
Michael Wrightd02c5b62014-02-10 15:10:22 -08005872 if (connection->monitor) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005873 removeMonitorChannelLocked(connectionToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005874 }
5875
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005876 mLooper->removeFd(connection->inputChannel->getFd());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005877
5878 nsecs_t currentTime = now();
5879 abortBrokenDispatchCycleLocked(currentTime, connection, notify);
5880
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08005881 connection->status = Connection::Status::ZOMBIE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005882 return OK;
5883}
5884
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005885void InputDispatcher::removeMonitorChannelLocked(const sp<IBinder>& connectionToken) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005886 for (auto it = mGlobalMonitorsByDisplay.begin(); it != mGlobalMonitorsByDisplay.end();) {
5887 auto& [displayId, monitors] = *it;
5888 std::erase_if(monitors, [connectionToken](const Monitor& monitor) {
5889 return monitor.inputChannel->getConnectionToken() == connectionToken;
5890 });
Michael Wright3dd60e22019-03-27 22:06:44 +00005891
Michael Wright3dd60e22019-03-27 22:06:44 +00005892 if (monitors.empty()) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005893 it = mGlobalMonitorsByDisplay.erase(it);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005894 } else {
5895 ++it;
5896 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005897 }
5898}
5899
Michael Wright3dd60e22019-03-27 22:06:44 +00005900status_t InputDispatcher::pilferPointers(const sp<IBinder>& token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005901 std::scoped_lock _l(mLock);
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00005902 return pilferPointersLocked(token);
5903}
Michael Wright3dd60e22019-03-27 22:06:44 +00005904
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00005905status_t InputDispatcher::pilferPointersLocked(const sp<IBinder>& token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005906 const std::shared_ptr<InputChannel> requestingChannel = getInputChannelLocked(token);
5907 if (!requestingChannel) {
5908 ALOGW("Attempted to pilfer pointers from an un-registered channel or invalid token");
5909 return BAD_VALUE;
Michael Wright3dd60e22019-03-27 22:06:44 +00005910 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005911
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005912 auto [statePtr, windowPtr, displayId] = findTouchStateWindowAndDisplayLocked(token);
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005913 if (statePtr == nullptr || windowPtr == nullptr) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005914 ALOGW("Attempted to pilfer points from a channel without any on-going pointer streams."
5915 " Ignoring.");
5916 return BAD_VALUE;
5917 }
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005918 std::set<int32_t> deviceIds = windowPtr->getTouchingDeviceIds();
5919 if (deviceIds.size() != 1) {
5920 LOG(WARNING) << "Can't pilfer. Currently touching devices: " << dumpSet(deviceIds)
5921 << " in window: " << windowPtr->dump();
5922 return BAD_VALUE;
5923 }
5924 const int32_t deviceId = *deviceIds.begin();
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005925
5926 TouchState& state = *statePtr;
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00005927 TouchedWindow& window = *windowPtr;
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005928 // Send cancel events to all the input channels we're stealing from.
Michael Wrightfb04fd52022-11-24 22:31:11 +00005929 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005930 "input channel stole pointer stream");
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005931 options.deviceId = deviceId;
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005932 options.displayId = displayId;
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005933 std::bitset<MAX_POINTER_ID + 1> pointerIds = window.getTouchingPointers(deviceId);
5934 options.pointerIds = pointerIds;
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005935 std::string canceledWindows;
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00005936 for (const TouchedWindow& w : state.windows) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005937 const std::shared_ptr<InputChannel> channel =
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00005938 getInputChannelLocked(w.windowHandle->getToken());
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005939 if (channel != nullptr && channel->getConnectionToken() != token) {
5940 synthesizeCancelationEventsForInputChannelLocked(channel, options);
5941 canceledWindows += canceledWindows.empty() ? "[" : ", ";
5942 canceledWindows += channel->getName();
5943 }
5944 }
5945 canceledWindows += canceledWindows.empty() ? "[]" : "]";
5946 ALOGI("Channel %s is stealing touch from %s", requestingChannel->getName().c_str(),
5947 canceledWindows.c_str());
5948
Prabir Pradhane680f9b2022-02-04 04:24:00 -08005949 // Prevent the gesture from being sent to any other windows.
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00005950 // This only blocks relevant pointers to be sent to other windows
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005951 window.addPilferingPointers(deviceId, pointerIds);
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00005952
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005953 state.cancelPointersForWindowsExcept(deviceId, pointerIds, token);
Michael Wright3dd60e22019-03-27 22:06:44 +00005954 return OK;
5955}
5956
Prabir Pradhan99987712020-11-10 18:43:05 -08005957void InputDispatcher::requestPointerCapture(const sp<IBinder>& windowToken, bool enabled) {
5958 { // acquire lock
5959 std::scoped_lock _l(mLock);
5960 if (DEBUG_FOCUS) {
chaviw98318de2021-05-19 16:45:23 -05005961 const sp<WindowInfoHandle> windowHandle = getWindowHandleLocked(windowToken);
Prabir Pradhan99987712020-11-10 18:43:05 -08005962 ALOGI("Request to %s Pointer Capture from: %s.", enabled ? "enable" : "disable",
5963 windowHandle != nullptr ? windowHandle->getName().c_str()
5964 : "token without window");
5965 }
5966
Vishnu Nairc519ff72021-01-21 08:23:08 -08005967 const sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Prabir Pradhan99987712020-11-10 18:43:05 -08005968 if (focusedToken != windowToken) {
5969 ALOGW("Ignoring request to %s Pointer Capture: window does not have focus.",
5970 enabled ? "enable" : "disable");
5971 return;
5972 }
5973
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005974 if (enabled == mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08005975 ALOGW("Ignoring request to %s Pointer Capture: "
5976 "window has %s requested pointer capture.",
5977 enabled ? "enable" : "disable", enabled ? "already" : "not");
5978 return;
5979 }
5980
Christine Franksb768bb42021-11-29 12:11:31 -08005981 if (enabled) {
5982 if (std::find(mIneligibleDisplaysForPointerCapture.begin(),
5983 mIneligibleDisplaysForPointerCapture.end(),
5984 mFocusedDisplayId) != mIneligibleDisplaysForPointerCapture.end()) {
5985 ALOGW("Ignoring request to enable Pointer Capture: display is not eligible");
5986 return;
5987 }
5988 }
5989
Prabir Pradhan99987712020-11-10 18:43:05 -08005990 setPointerCaptureLocked(enabled);
5991 } // release lock
5992
5993 // Wake the thread to process command entries.
5994 mLooper->wake();
5995}
5996
Christine Franksb768bb42021-11-29 12:11:31 -08005997void InputDispatcher::setDisplayEligibilityForPointerCapture(int32_t displayId, bool isEligible) {
5998 { // acquire lock
5999 std::scoped_lock _l(mLock);
6000 std::erase(mIneligibleDisplaysForPointerCapture, displayId);
6001 if (!isEligible) {
6002 mIneligibleDisplaysForPointerCapture.push_back(displayId);
6003 }
6004 } // release lock
6005}
6006
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00006007std::optional<gui::Pid> InputDispatcher::findMonitorPidByTokenLocked(const sp<IBinder>& token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006008 for (const auto& [_, monitors] : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00006009 for (const Monitor& monitor : monitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07006010 if (monitor.inputChannel->getConnectionToken() == token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006011 return monitor.pid;
Michael Wright3dd60e22019-03-27 22:06:44 +00006012 }
6013 }
6014 }
6015 return std::nullopt;
6016}
6017
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006018std::shared_ptr<Connection> InputDispatcher::getConnectionLocked(
6019 const sp<IBinder>& inputConnectionToken) const {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07006020 if (inputConnectionToken == nullptr) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07006021 return nullptr;
Arthur Hung3b413f22018-10-26 18:05:34 +08006022 }
6023
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00006024 for (const auto& [token, connection] : mConnectionsByToken) {
6025 if (token == inputConnectionToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07006026 return connection;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006027 }
6028 }
Robert Carr4e670e52018-08-15 13:26:12 -07006029
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07006030 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006031}
6032
Siarhei Vishniakouad991402020-10-28 11:40:09 -05006033std::string InputDispatcher::getConnectionNameLocked(const sp<IBinder>& connectionToken) const {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006034 std::shared_ptr<Connection> connection = getConnectionLocked(connectionToken);
Siarhei Vishniakouad991402020-10-28 11:40:09 -05006035 if (connection == nullptr) {
6036 return "<nullptr>";
6037 }
6038 return connection->getInputChannelName();
6039}
6040
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006041void InputDispatcher::removeConnectionLocked(const std::shared_ptr<Connection>& connection) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006042 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00006043 mConnectionsByToken.erase(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07006044}
6045
Prabir Pradhancef936d2021-07-21 16:17:52 +00006046void InputDispatcher::doDispatchCycleFinishedCommand(nsecs_t finishTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006047 const std::shared_ptr<Connection>& connection,
6048 uint32_t seq, bool handled,
6049 nsecs_t consumeTime) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006050 // Handle post-event policy actions.
6051 std::deque<DispatchEntry*>::iterator dispatchEntryIt = connection->findWaitQueueEntry(seq);
6052 if (dispatchEntryIt == connection->waitQueue.end()) {
6053 return;
6054 }
6055 DispatchEntry* dispatchEntry = *dispatchEntryIt;
6056 const nsecs_t eventDuration = finishTime - dispatchEntry->deliveryTime;
6057 if (eventDuration > SLOW_EVENT_PROCESSING_WARNING_TIMEOUT) {
6058 ALOGI("%s spent %" PRId64 "ms processing %s", connection->getWindowName().c_str(),
6059 ns2ms(eventDuration), dispatchEntry->eventEntry->getDescription().c_str());
6060 }
6061 if (shouldReportFinishedEvent(*dispatchEntry, *connection)) {
6062 mLatencyTracker.trackFinishedEvent(dispatchEntry->eventEntry->id,
6063 connection->inputChannel->getConnectionToken(),
6064 dispatchEntry->deliveryTime, consumeTime, finishTime);
6065 }
6066
6067 bool restartEvent;
6068 if (dispatchEntry->eventEntry->type == EventEntry::Type::KEY) {
6069 KeyEntry& keyEntry = static_cast<KeyEntry&>(*(dispatchEntry->eventEntry));
6070 restartEvent =
6071 afterKeyEventLockedInterruptable(connection, dispatchEntry, keyEntry, handled);
6072 } else if (dispatchEntry->eventEntry->type == EventEntry::Type::MOTION) {
6073 MotionEntry& motionEntry = static_cast<MotionEntry&>(*(dispatchEntry->eventEntry));
6074 restartEvent = afterMotionEventLockedInterruptable(connection, dispatchEntry, motionEntry,
6075 handled);
6076 } else {
6077 restartEvent = false;
6078 }
6079
6080 // Dequeue the event and start the next cycle.
6081 // Because the lock might have been released, it is possible that the
6082 // contents of the wait queue to have been drained, so we need to double-check
6083 // a few things.
6084 dispatchEntryIt = connection->findWaitQueueEntry(seq);
6085 if (dispatchEntryIt != connection->waitQueue.end()) {
6086 dispatchEntry = *dispatchEntryIt;
6087 connection->waitQueue.erase(dispatchEntryIt);
6088 const sp<IBinder>& connectionToken = connection->inputChannel->getConnectionToken();
6089 mAnrTracker.erase(dispatchEntry->timeoutTime, connectionToken);
6090 if (!connection->responsive) {
6091 connection->responsive = isConnectionResponsive(*connection);
6092 if (connection->responsive) {
6093 // The connection was unresponsive, and now it's responsive.
6094 processConnectionResponsiveLocked(*connection);
6095 }
6096 }
6097 traceWaitQueueLength(*connection);
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08006098 if (restartEvent && connection->status == Connection::Status::NORMAL) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006099 connection->outboundQueue.push_front(dispatchEntry);
6100 traceOutboundQueueLength(*connection);
6101 } else {
6102 releaseDispatchEntry(dispatchEntry);
6103 }
6104 }
6105
6106 // Start the next dispatch cycle for this connection.
6107 startDispatchCycleLocked(now(), connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006108}
6109
Prabir Pradhancef936d2021-07-21 16:17:52 +00006110void InputDispatcher::sendFocusChangedCommandLocked(const sp<IBinder>& oldToken,
6111 const sp<IBinder>& newToken) {
6112 auto command = [this, oldToken, newToken]() REQUIRES(mLock) {
6113 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00006114 mPolicy.notifyFocusChanged(oldToken, newToken);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006115 };
6116 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08006117}
6118
Prabir Pradhancef936d2021-07-21 16:17:52 +00006119void InputDispatcher::sendDropWindowCommandLocked(const sp<IBinder>& token, float x, float y) {
6120 auto command = [this, token, x, y]() REQUIRES(mLock) {
6121 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00006122 mPolicy.notifyDropWindow(token, x, y);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006123 };
6124 postCommandLocked(std::move(command));
Robert Carrf759f162018-11-13 12:57:11 -08006125}
6126
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006127void InputDispatcher::onAnrLocked(const std::shared_ptr<Connection>& connection) {
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006128 if (connection == nullptr) {
6129 LOG_ALWAYS_FATAL("Caller must check for nullness");
6130 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006131 // Since we are allowing the policy to extend the timeout, maybe the waitQueue
6132 // is already healthy again. Don't raise ANR in this situation
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006133 if (connection->waitQueue.empty()) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006134 ALOGI("Not raising ANR because the connection %s has recovered",
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006135 connection->inputChannel->getName().c_str());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006136 return;
6137 }
6138 /**
6139 * The "oldestEntry" is the entry that was first sent to the application. That entry, however,
6140 * may not be the one that caused the timeout to occur. One possibility is that window timeout
6141 * has changed. This could cause newer entries to time out before the already dispatched
6142 * entries. In that situation, the newest entries caused ANR. But in all likelihood, the app
6143 * processes the events linearly. So providing information about the oldest entry seems to be
6144 * most useful.
6145 */
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006146 DispatchEntry* oldestEntry = *connection->waitQueue.begin();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006147 const nsecs_t currentWait = now() - oldestEntry->deliveryTime;
6148 std::string reason =
6149 android::base::StringPrintf("%s is not responding. Waited %" PRId64 "ms for %s",
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006150 connection->inputChannel->getName().c_str(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006151 ns2ms(currentWait),
6152 oldestEntry->eventEntry->getDescription().c_str());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006153 sp<IBinder> connectionToken = connection->inputChannel->getConnectionToken();
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -06006154 updateLastAnrStateLocked(getWindowHandleLocked(connectionToken), reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006155
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006156 processConnectionUnresponsiveLocked(*connection, std::move(reason));
6157
6158 // Stop waking up for events on this connection, it is already unresponsive
6159 cancelEventsForAnrLocked(connection);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006160}
6161
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05006162void InputDispatcher::onAnrLocked(std::shared_ptr<InputApplicationHandle> application) {
6163 std::string reason =
6164 StringPrintf("%s does not have a focused window", application->getName().c_str());
6165 updateLastAnrStateLocked(*application, reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006166
Yabin Cui8eb9c552023-06-08 18:05:07 +00006167 auto command = [this, app = std::move(application)]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006168 scoped_unlock unlock(mLock);
Yabin Cuiced952f2023-06-09 21:12:51 +00006169 mPolicy.notifyNoFocusedWindowAnr(app);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006170 };
6171 postCommandLocked(std::move(command));
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00006172}
6173
chaviw98318de2021-05-19 16:45:23 -05006174void InputDispatcher::updateLastAnrStateLocked(const sp<WindowInfoHandle>& window,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006175 const std::string& reason) {
6176 const std::string windowLabel = getApplicationWindowLabel(nullptr, window);
6177 updateLastAnrStateLocked(windowLabel, reason);
6178}
6179
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05006180void InputDispatcher::updateLastAnrStateLocked(const InputApplicationHandle& application,
6181 const std::string& reason) {
6182 const std::string windowLabel = getApplicationWindowLabel(&application, nullptr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006183 updateLastAnrStateLocked(windowLabel, reason);
6184}
6185
6186void InputDispatcher::updateLastAnrStateLocked(const std::string& windowLabel,
6187 const std::string& reason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006188 // Capture a record of the InputDispatcher state at the time of the ANR.
Yi Kong9b14ac62018-07-17 13:48:38 -07006189 time_t t = time(nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006190 struct tm tm;
6191 localtime_r(&t, &tm);
6192 char timestr[64];
6193 strftime(timestr, sizeof(timestr), "%F %T", &tm);
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006194 mLastAnrState.clear();
6195 mLastAnrState += INDENT "ANR:\n";
6196 mLastAnrState += StringPrintf(INDENT2 "Time: %s\n", timestr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006197 mLastAnrState += StringPrintf(INDENT2 "Reason: %s\n", reason.c_str());
6198 mLastAnrState += StringPrintf(INDENT2 "Window: %s\n", windowLabel.c_str());
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006199 dumpDispatchStateLocked(mLastAnrState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006200}
6201
Prabir Pradhancef936d2021-07-21 16:17:52 +00006202void InputDispatcher::doInterceptKeyBeforeDispatchingCommand(const sp<IBinder>& focusedWindowToken,
6203 KeyEntry& entry) {
6204 const KeyEvent event = createKeyEvent(entry);
6205 nsecs_t delay = 0;
6206 { // release lock
6207 scoped_unlock unlock(mLock);
6208 android::base::Timer t;
Prabir Pradhana41d2442023-04-20 21:30:40 +00006209 delay = mPolicy.interceptKeyBeforeDispatching(focusedWindowToken, event, entry.policyFlags);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006210 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
6211 ALOGW("Excessive delay in interceptKeyBeforeDispatching; took %s ms",
6212 std::to_string(t.duration().count()).c_str());
6213 }
6214 } // acquire lock
Michael Wrightd02c5b62014-02-10 15:10:22 -08006215
6216 if (delay < 0) {
Michael Wright5caf55a2022-11-24 22:31:42 +00006217 entry.interceptKeyResult = KeyEntry::InterceptKeyResult::SKIP;
Prabir Pradhancef936d2021-07-21 16:17:52 +00006218 } else if (delay == 0) {
Michael Wright5caf55a2022-11-24 22:31:42 +00006219 entry.interceptKeyResult = KeyEntry::InterceptKeyResult::CONTINUE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006220 } else {
Michael Wright5caf55a2022-11-24 22:31:42 +00006221 entry.interceptKeyResult = KeyEntry::InterceptKeyResult::TRY_AGAIN_LATER;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006222 entry.interceptKeyWakeupTime = now() + delay;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006223 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006224}
6225
Prabir Pradhancef936d2021-07-21 16:17:52 +00006226void InputDispatcher::sendWindowUnresponsiveCommandLocked(const sp<IBinder>& token,
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00006227 std::optional<gui::Pid> pid,
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006228 std::string reason) {
Yabin Cui8eb9c552023-06-08 18:05:07 +00006229 auto command = [this, token, pid, r = std::move(reason)]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006230 scoped_unlock unlock(mLock);
Yabin Cuiced952f2023-06-09 21:12:51 +00006231 mPolicy.notifyWindowUnresponsive(token, pid, r);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006232 };
6233 postCommandLocked(std::move(command));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006234}
6235
Prabir Pradhanedd96402022-02-15 01:46:16 -08006236void InputDispatcher::sendWindowResponsiveCommandLocked(const sp<IBinder>& token,
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00006237 std::optional<gui::Pid> pid) {
Prabir Pradhanedd96402022-02-15 01:46:16 -08006238 auto command = [this, token, pid]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006239 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00006240 mPolicy.notifyWindowResponsive(token, pid);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006241 };
6242 postCommandLocked(std::move(command));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006243}
6244
6245/**
6246 * Tell the policy that a connection has become unresponsive so that it can start ANR.
6247 * Check whether the connection of interest is a monitor or a window, and add the corresponding
6248 * command entry to the command queue.
6249 */
6250void InputDispatcher::processConnectionUnresponsiveLocked(const Connection& connection,
6251 std::string reason) {
6252 const sp<IBinder>& connectionToken = connection.inputChannel->getConnectionToken();
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00006253 std::optional<gui::Pid> pid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006254 if (connection.monitor) {
6255 ALOGW("Monitor %s is unresponsive: %s", connection.inputChannel->getName().c_str(),
6256 reason.c_str());
Prabir Pradhanedd96402022-02-15 01:46:16 -08006257 pid = findMonitorPidByTokenLocked(connectionToken);
6258 } else {
6259 // The connection is a window
6260 ALOGW("Window %s is unresponsive: %s", connection.inputChannel->getName().c_str(),
6261 reason.c_str());
6262 const sp<WindowInfoHandle> handle = getWindowHandleLocked(connectionToken);
6263 if (handle != nullptr) {
6264 pid = handle->getInfo()->ownerPid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006265 }
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006266 }
Prabir Pradhanedd96402022-02-15 01:46:16 -08006267 sendWindowUnresponsiveCommandLocked(connectionToken, pid, std::move(reason));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006268}
6269
6270/**
6271 * Tell the policy that a connection has become responsive so that it can stop ANR.
6272 */
6273void InputDispatcher::processConnectionResponsiveLocked(const Connection& connection) {
6274 const sp<IBinder>& connectionToken = connection.inputChannel->getConnectionToken();
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00006275 std::optional<gui::Pid> pid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006276 if (connection.monitor) {
Prabir Pradhanedd96402022-02-15 01:46:16 -08006277 pid = findMonitorPidByTokenLocked(connectionToken);
6278 } else {
6279 // The connection is a window
6280 const sp<WindowInfoHandle> handle = getWindowHandleLocked(connectionToken);
6281 if (handle != nullptr) {
6282 pid = handle->getInfo()->ownerPid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006283 }
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006284 }
Prabir Pradhanedd96402022-02-15 01:46:16 -08006285 sendWindowResponsiveCommandLocked(connectionToken, pid);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006286}
6287
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006288bool InputDispatcher::afterKeyEventLockedInterruptable(
6289 const std::shared_ptr<Connection>& connection, DispatchEntry* dispatchEntry,
6290 KeyEntry& keyEntry, bool handled) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006291 if (keyEntry.flags & AKEY_EVENT_FLAG_FALLBACK) {
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006292 if (!handled) {
6293 // Report the key as unhandled, since the fallback was not handled.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006294 mReporter->reportUnhandledKey(keyEntry.id);
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006295 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006296 return false;
6297 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006298
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006299 // Get the fallback key state.
6300 // Clear it out after dispatching the UP.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006301 int32_t originalKeyCode = keyEntry.keyCode;
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006302 std::optional<int32_t> fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006303 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006304 connection->inputState.removeFallbackKey(originalKeyCode);
6305 }
6306
6307 if (handled || !dispatchEntry->hasForegroundTarget()) {
6308 // If the application handles the original key for which we previously
6309 // generated a fallback or if the window is not a foreground window,
6310 // then cancel the associated fallback key, if any.
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006311 if (fallbackKeyCode) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006312 // Dispatch the unhandled key to the policy with the cancel flag.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006313 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6314 ALOGD("Unhandled key event: Asking policy to cancel fallback action. "
6315 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6316 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount,
6317 keyEntry.policyFlags);
6318 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006319 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006320 event.setFlags(event.getFlags() | AKEY_EVENT_FLAG_CANCELED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006321
6322 mLock.unlock();
6323
Prabir Pradhana41d2442023-04-20 21:30:40 +00006324 if (const auto unhandledKeyFallback =
6325 mPolicy.dispatchUnhandledKey(connection->inputChannel->getConnectionToken(),
6326 event, keyEntry.policyFlags);
6327 unhandledKeyFallback) {
6328 event = *unhandledKeyFallback;
6329 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006330
6331 mLock.lock();
6332
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006333 // Cancel the fallback key.
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006334 if (*fallbackKeyCode != AKEYCODE_UNKNOWN) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00006335 CancelationOptions options(CancelationOptions::Mode::CANCEL_FALLBACK_EVENTS,
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006336 "application handled the original non-fallback key "
6337 "or is no longer a foreground target, "
6338 "canceling previously dispatched fallback key");
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006339 options.keyCode = *fallbackKeyCode;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006340 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006341 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006342 connection->inputState.removeFallbackKey(originalKeyCode);
6343 }
6344 } else {
6345 // If the application did not handle a non-fallback key, first check
6346 // that we are in a good state to perform unhandled key event processing
6347 // Then ask the policy what to do with it.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006348 bool initialDown = keyEntry.action == AKEY_EVENT_ACTION_DOWN && keyEntry.repeatCount == 0;
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006349 if (!fallbackKeyCode && !initialDown) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006350 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6351 ALOGD("Unhandled key event: Skipping unhandled key event processing "
6352 "since this is not an initial down. "
6353 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6354 originalKeyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
6355 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006356 return false;
6357 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006358
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006359 // Dispatch the unhandled key to the policy.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006360 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6361 ALOGD("Unhandled key event: Asking policy to perform fallback action. "
6362 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6363 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
6364 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006365 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006366
6367 mLock.unlock();
6368
Prabir Pradhana41d2442023-04-20 21:30:40 +00006369 bool fallback = false;
6370 if (auto fb = mPolicy.dispatchUnhandledKey(connection->inputChannel->getConnectionToken(),
6371 event, keyEntry.policyFlags);
6372 fb) {
6373 fallback = true;
6374 event = *fb;
6375 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006376
6377 mLock.lock();
6378
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08006379 if (connection->status != Connection::Status::NORMAL) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006380 connection->inputState.removeFallbackKey(originalKeyCode);
6381 return false;
6382 }
6383
6384 // Latch the fallback keycode for this key on an initial down.
6385 // The fallback keycode cannot change at any other point in the lifecycle.
6386 if (initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006387 if (fallback) {
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006388 *fallbackKeyCode = event.getKeyCode();
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006389 } else {
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006390 *fallbackKeyCode = AKEYCODE_UNKNOWN;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006391 }
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006392 connection->inputState.setFallbackKey(originalKeyCode, *fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006393 }
6394
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006395 ALOG_ASSERT(fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006396
6397 // Cancel the fallback key if the policy decides not to send it anymore.
6398 // We will continue to dispatch the key to the policy but we will no
6399 // longer dispatch a fallback key to the application.
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006400 if (*fallbackKeyCode != AKEYCODE_UNKNOWN &&
6401 (!fallback || *fallbackKeyCode != event.getKeyCode())) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006402 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6403 if (fallback) {
6404 ALOGD("Unhandled key event: Policy requested to send key %d"
6405 "as a fallback for %d, but on the DOWN it had requested "
6406 "to send %d instead. Fallback canceled.",
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006407 event.getKeyCode(), originalKeyCode, *fallbackKeyCode);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006408 } else {
6409 ALOGD("Unhandled key event: Policy did not request fallback for %d, "
6410 "but on the DOWN it had requested to send %d. "
6411 "Fallback canceled.",
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006412 originalKeyCode, *fallbackKeyCode);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006413 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006414 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006415
Michael Wrightfb04fd52022-11-24 22:31:11 +00006416 CancelationOptions options(CancelationOptions::Mode::CANCEL_FALLBACK_EVENTS,
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006417 "canceling fallback, policy no longer desires it");
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006418 options.keyCode = *fallbackKeyCode;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006419 synthesizeCancelationEventsForConnectionLocked(connection, options);
6420
6421 fallback = false;
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006422 *fallbackKeyCode = AKEYCODE_UNKNOWN;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006423 if (keyEntry.action != AKEY_EVENT_ACTION_UP) {
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006424 connection->inputState.setFallbackKey(originalKeyCode, *fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006425 }
6426 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006427
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006428 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6429 {
6430 std::string msg;
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006431 const std::map<int32_t, int32_t>& fallbackKeys =
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006432 connection->inputState.getFallbackKeys();
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006433 for (const auto& [key, value] : fallbackKeys) {
6434 msg += StringPrintf(", %d->%d", key, value);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006435 }
6436 ALOGD("Unhandled key event: %zu currently tracked fallback keys%s.",
6437 fallbackKeys.size(), msg.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006438 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006439 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006440
6441 if (fallback) {
6442 // Restart the dispatch cycle using the fallback key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006443 keyEntry.eventTime = event.getEventTime();
6444 keyEntry.deviceId = event.getDeviceId();
6445 keyEntry.source = event.getSource();
6446 keyEntry.displayId = event.getDisplayId();
6447 keyEntry.flags = event.getFlags() | AKEY_EVENT_FLAG_FALLBACK;
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006448 keyEntry.keyCode = *fallbackKeyCode;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006449 keyEntry.scanCode = event.getScanCode();
6450 keyEntry.metaState = event.getMetaState();
6451 keyEntry.repeatCount = event.getRepeatCount();
6452 keyEntry.downTime = event.getDownTime();
6453 keyEntry.syntheticRepeat = false;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006454
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006455 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6456 ALOGD("Unhandled key event: Dispatching fallback key. "
6457 "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006458 originalKeyCode, *fallbackKeyCode, keyEntry.metaState);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006459 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006460 return true; // restart the event
6461 } else {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006462 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6463 ALOGD("Unhandled key event: No fallback key.");
6464 }
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006465
6466 // Report the key as unhandled, since there is no fallback key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006467 mReporter->reportUnhandledKey(keyEntry.id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006468 }
6469 }
6470 return false;
6471}
6472
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006473bool InputDispatcher::afterMotionEventLockedInterruptable(
6474 const std::shared_ptr<Connection>& connection, DispatchEntry* dispatchEntry,
6475 MotionEntry& motionEntry, bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006476 return false;
6477}
6478
Michael Wrightd02c5b62014-02-10 15:10:22 -08006479void InputDispatcher::traceInboundQueueLengthLocked() {
6480 if (ATRACE_ENABLED()) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07006481 ATRACE_INT("iq", mInboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006482 }
6483}
6484
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006485void InputDispatcher::traceOutboundQueueLength(const Connection& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006486 if (ATRACE_ENABLED()) {
6487 char counterName[40];
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006488 snprintf(counterName, sizeof(counterName), "oq:%s", connection.getWindowName().c_str());
6489 ATRACE_INT(counterName, connection.outboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006490 }
6491}
6492
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006493void InputDispatcher::traceWaitQueueLength(const Connection& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006494 if (ATRACE_ENABLED()) {
6495 char counterName[40];
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006496 snprintf(counterName, sizeof(counterName), "wq:%s", connection.getWindowName().c_str());
6497 ATRACE_INT(counterName, connection.waitQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006498 }
6499}
6500
Siarhei Vishniakou5e20f272023-06-08 17:24:44 -07006501void InputDispatcher::dump(std::string& dump) const {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006502 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006503
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006504 dump += "Input Dispatcher State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08006505 dumpDispatchStateLocked(dump);
6506
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006507 if (!mLastAnrState.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006508 dump += "\nInput Dispatcher State at time of last ANR:\n";
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006509 dump += mLastAnrState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006510 }
6511}
6512
6513void InputDispatcher::monitor() {
6514 // Acquire and release the lock to ensure that the dispatcher has not deadlocked.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006515 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006516 mLooper->wake();
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006517 mDispatcherIsAlive.wait(_l);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006518}
6519
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08006520/**
6521 * Wake up the dispatcher and wait until it processes all events and commands.
6522 * The notification of mDispatcherEnteredIdle is guaranteed to happen after wake(), so
6523 * this method can be safely called from any thread, as long as you've ensured that
6524 * the work you are interested in completing has already been queued.
6525 */
Siarhei Vishniakoua66d65e2023-06-16 10:32:51 -07006526bool InputDispatcher::waitForIdle() const {
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08006527 /**
6528 * Timeout should represent the longest possible time that a device might spend processing
6529 * events and commands.
6530 */
6531 constexpr std::chrono::duration TIMEOUT = 100ms;
6532 std::unique_lock lock(mLock);
6533 mLooper->wake();
6534 std::cv_status result = mDispatcherEnteredIdle.wait_for(lock, TIMEOUT);
6535 return result == std::cv_status::no_timeout;
6536}
6537
Vishnu Naire798b472020-07-23 13:52:21 -07006538/**
6539 * Sets focus to the window identified by the token. This must be called
6540 * after updating any input window handles.
6541 *
6542 * Params:
6543 * request.token - input channel token used to identify the window that should gain focus.
6544 * request.focusedToken - the token that the caller expects currently to be focused. If the
6545 * specified token does not match the currently focused window, this request will be dropped.
6546 * If the specified focused token matches the currently focused window, the call will succeed.
6547 * Set this to "null" if this call should succeed no matter what the currently focused token is.
6548 * request.timestamp - SYSTEM_TIME_MONOTONIC timestamp in nanos set by the client (wm)
6549 * when requesting the focus change. This determines which request gets
6550 * precedence if there is a focus change request from another source such as pointer down.
6551 */
Vishnu Nair958da932020-08-21 17:12:37 -07006552void InputDispatcher::setFocusedWindow(const FocusRequest& request) {
6553 { // acquire lock
6554 std::scoped_lock _l(mLock);
Vishnu Nairc519ff72021-01-21 08:23:08 -08006555 std::optional<FocusResolver::FocusChanges> changes =
6556 mFocusResolver.setFocusedWindow(request, getWindowHandlesLocked(request.displayId));
6557 if (changes) {
6558 onFocusChangedLocked(*changes);
Vishnu Nair958da932020-08-21 17:12:37 -07006559 }
6560 } // release lock
6561 // Wake up poll loop since it may need to make new input dispatching choices.
6562 mLooper->wake();
6563}
6564
Vishnu Nairc519ff72021-01-21 08:23:08 -08006565void InputDispatcher::onFocusChangedLocked(const FocusResolver::FocusChanges& changes) {
6566 if (changes.oldFocus) {
6567 std::shared_ptr<InputChannel> focusedInputChannel = getInputChannelLocked(changes.oldFocus);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006568 if (focusedInputChannel) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00006569 CancelationOptions options(CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS,
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006570 "focus left window");
6571 synthesizeCancelationEventsForInputChannelLocked(focusedInputChannel, options);
Harry Cutts33476232023-01-30 19:57:29 +00006572 enqueueFocusEventLocked(changes.oldFocus, /*hasFocus=*/false, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006573 }
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006574 }
Vishnu Nairc519ff72021-01-21 08:23:08 -08006575 if (changes.newFocus) {
Harry Cutts33476232023-01-30 19:57:29 +00006576 enqueueFocusEventLocked(changes.newFocus, /*hasFocus=*/true, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006577 }
6578
Prabir Pradhan99987712020-11-10 18:43:05 -08006579 // If a window has pointer capture, then it must have focus. We need to ensure that this
6580 // contract is upheld when pointer capture is being disabled due to a loss of window focus.
6581 // If the window loses focus before it loses pointer capture, then the window can be in a state
6582 // where it has pointer capture but not focus, violating the contract. Therefore we must
6583 // dispatch the pointer capture event before the focus event. Since focus events are added to
6584 // the front of the queue (above), we add the pointer capture event to the front of the queue
6585 // after the focus events are added. This ensures the pointer capture event ends up at the
6586 // front.
6587 disablePointerCaptureForcedLocked();
6588
Vishnu Nairc519ff72021-01-21 08:23:08 -08006589 if (mFocusedDisplayId == changes.displayId) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006590 sendFocusChangedCommandLocked(changes.oldFocus, changes.newFocus);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006591 }
6592}
Vishnu Nair958da932020-08-21 17:12:37 -07006593
Prabir Pradhan99987712020-11-10 18:43:05 -08006594void InputDispatcher::disablePointerCaptureForcedLocked() {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006595 if (!mCurrentPointerCaptureRequest.enable && !mWindowTokenWithPointerCapture) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006596 return;
6597 }
6598
6599 ALOGD_IF(DEBUG_FOCUS, "Disabling Pointer Capture because the window lost focus.");
6600
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006601 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006602 setPointerCaptureLocked(false);
6603 }
6604
6605 if (!mWindowTokenWithPointerCapture) {
6606 // No need to send capture changes because no window has capture.
6607 return;
6608 }
6609
6610 if (mPendingEvent != nullptr) {
6611 // Move the pending event to the front of the queue. This will give the chance
6612 // for the pending event to be dropped if it is a captured event.
6613 mInboundQueue.push_front(mPendingEvent);
6614 mPendingEvent = nullptr;
6615 }
6616
6617 auto entry = std::make_unique<PointerCaptureChangedEntry>(mIdGenerator.nextId(), now(),
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006618 mCurrentPointerCaptureRequest);
Prabir Pradhan99987712020-11-10 18:43:05 -08006619 mInboundQueue.push_front(std::move(entry));
6620}
6621
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006622void InputDispatcher::setPointerCaptureLocked(bool enable) {
6623 mCurrentPointerCaptureRequest.enable = enable;
6624 mCurrentPointerCaptureRequest.seq++;
6625 auto command = [this, request = mCurrentPointerCaptureRequest]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006626 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00006627 mPolicy.setPointerCapture(request);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006628 };
6629 postCommandLocked(std::move(command));
Prabir Pradhan99987712020-11-10 18:43:05 -08006630}
6631
Vishnu Nair599f1412021-06-21 10:39:58 -07006632void InputDispatcher::displayRemoved(int32_t displayId) {
6633 { // acquire lock
6634 std::scoped_lock _l(mLock);
6635 // Set an empty list to remove all handles from the specific display.
Harry Cutts101ee9b2023-07-06 18:04:14 +00006636 setInputWindowsLocked(/*windowInfoHandles=*/{}, displayId);
Vishnu Nair599f1412021-06-21 10:39:58 -07006637 setFocusedApplicationLocked(displayId, nullptr);
6638 // Call focus resolver to clean up stale requests. This must be called after input windows
6639 // have been removed for the removed display.
6640 mFocusResolver.displayRemoved(displayId);
Christine Franksb768bb42021-11-29 12:11:31 -08006641 // Reset pointer capture eligibility, regardless of previous state.
6642 std::erase(mIneligibleDisplaysForPointerCapture, displayId);
Antonio Kantek15beb512022-06-13 22:35:41 +00006643 // Remove the associated touch mode state.
6644 mTouchModePerDisplay.erase(displayId);
Siarhei Vishniakou5c02a712023-05-15 15:45:02 -07006645 mVerifiersByDisplay.erase(displayId);
Vishnu Nair599f1412021-06-21 10:39:58 -07006646 } // release lock
6647
6648 // Wake up poll loop since it may need to make new input dispatching choices.
6649 mLooper->wake();
6650}
6651
Patrick Williamsd828f302023-04-28 17:52:08 -05006652void InputDispatcher::onWindowInfosChanged(const gui::WindowInfosUpdate& update) {
chaviw15fab6f2021-06-07 14:15:52 -05006653 // The listener sends the windows as a flattened array. Separate the windows by display for
6654 // more convenient parsing.
6655 std::unordered_map<int32_t, std::vector<sp<WindowInfoHandle>>> handlesPerDisplay;
Patrick Williamsd828f302023-04-28 17:52:08 -05006656 for (const auto& info : update.windowInfos) {
chaviw15fab6f2021-06-07 14:15:52 -05006657 handlesPerDisplay.emplace(info.displayId, std::vector<sp<WindowInfoHandle>>());
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07006658 handlesPerDisplay[info.displayId].push_back(sp<WindowInfoHandle>::make(info));
chaviw15fab6f2021-06-07 14:15:52 -05006659 }
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006660
6661 { // acquire lock
6662 std::scoped_lock _l(mLock);
Prabir Pradhan814fe082022-07-22 20:22:18 +00006663
6664 // Ensure that we have an entry created for all existing displays so that if a displayId has
6665 // no windows, we can tell that the windows were removed from the display.
6666 for (const auto& [displayId, _] : mWindowHandlesByDisplay) {
6667 handlesPerDisplay[displayId];
6668 }
6669
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006670 mDisplayInfos.clear();
Patrick Williamsd828f302023-04-28 17:52:08 -05006671 for (const auto& displayInfo : update.displayInfos) {
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006672 mDisplayInfos.emplace(displayInfo.displayId, displayInfo);
6673 }
6674
6675 for (const auto& [displayId, handles] : handlesPerDisplay) {
6676 setInputWindowsLocked(handles, displayId);
6677 }
Patrick Williams9464b2c2023-05-23 11:22:04 -05006678
6679 if (update.vsyncId < mWindowInfosVsyncId) {
6680 ALOGE("Received out of order window infos update. Last update vsync id: %" PRId64
6681 ", current update vsync id: %" PRId64,
6682 mWindowInfosVsyncId, update.vsyncId);
6683 }
6684 mWindowInfosVsyncId = update.vsyncId;
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006685 }
6686 // Wake up poll loop since it may need to make new input dispatching choices.
6687 mLooper->wake();
chaviw15fab6f2021-06-07 14:15:52 -05006688}
6689
Vishnu Nair062a8672021-09-03 16:07:44 -07006690bool InputDispatcher::shouldDropInput(
6691 const EventEntry& entry, const sp<android::gui::WindowInfoHandle>& windowHandle) const {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006692 if (windowHandle->getInfo()->inputConfig.test(WindowInfo::InputConfig::DROP_INPUT) ||
6693 (windowHandle->getInfo()->inputConfig.test(
6694 WindowInfo::InputConfig::DROP_INPUT_IF_OBSCURED) &&
Vishnu Nair062a8672021-09-03 16:07:44 -07006695 isWindowObscuredLocked(windowHandle))) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006696 ALOGW("Dropping %s event targeting %s as requested by the input configuration {%s} on "
6697 "display %" PRId32 ".",
Vishnu Nair062a8672021-09-03 16:07:44 -07006698 ftl::enum_string(entry.type).c_str(), windowHandle->getName().c_str(),
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006699 windowHandle->getInfo()->inputConfig.string().c_str(),
Vishnu Nair062a8672021-09-03 16:07:44 -07006700 windowHandle->getInfo()->displayId);
6701 return true;
6702 }
6703 return false;
6704}
6705
Siarhei Vishniakou18050092021-09-01 13:32:49 -07006706void InputDispatcher::DispatcherWindowListener::onWindowInfosChanged(
Patrick Williamsd828f302023-04-28 17:52:08 -05006707 const gui::WindowInfosUpdate& update) {
6708 mDispatcher.onWindowInfosChanged(update);
Siarhei Vishniakou18050092021-09-01 13:32:49 -07006709}
6710
Arthur Hungdfd528e2021-12-08 13:23:04 +00006711void InputDispatcher::cancelCurrentTouch() {
6712 {
6713 std::scoped_lock _l(mLock);
6714 ALOGD("Canceling all ongoing pointer gestures on all displays.");
Michael Wrightfb04fd52022-11-24 22:31:11 +00006715 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
Arthur Hungdfd528e2021-12-08 13:23:04 +00006716 "cancel current touch");
6717 synthesizeCancelationEventsForAllConnectionsLocked(options);
6718
6719 mTouchStatesByDisplay.clear();
Arthur Hungdfd528e2021-12-08 13:23:04 +00006720 }
6721 // Wake up poll loop since there might be work to do.
6722 mLooper->wake();
6723}
6724
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006725void InputDispatcher::setMonitorDispatchingTimeoutForTest(std::chrono::nanoseconds timeout) {
6726 std::scoped_lock _l(mLock);
6727 mMonitorDispatchingTimeout = timeout;
6728}
6729
Arthur Hungc539dbb2022-12-08 07:45:36 +00006730void InputDispatcher::slipWallpaperTouch(ftl::Flags<InputTarget::Flags> targetFlags,
6731 const sp<WindowInfoHandle>& oldWindowHandle,
6732 const sp<WindowInfoHandle>& newWindowHandle,
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07006733 TouchState& state, int32_t deviceId, int32_t pointerId,
Siarhei Vishniakoubf880522023-05-01 11:03:22 -07006734 std::vector<InputTarget>& targets) const {
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08006735 std::bitset<MAX_POINTER_ID + 1> pointerIds;
6736 pointerIds.set(pointerId);
Arthur Hungc539dbb2022-12-08 07:45:36 +00006737 const bool oldHasWallpaper = oldWindowHandle->getInfo()->inputConfig.test(
6738 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
6739 const bool newHasWallpaper = targetFlags.test(InputTarget::Flags::FOREGROUND) &&
6740 newWindowHandle->getInfo()->inputConfig.test(
6741 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
6742 const sp<WindowInfoHandle> oldWallpaper =
6743 oldHasWallpaper ? state.getWallpaperWindow() : nullptr;
6744 const sp<WindowInfoHandle> newWallpaper =
6745 newHasWallpaper ? findWallpaperWindowBelow(newWindowHandle) : nullptr;
6746 if (oldWallpaper == newWallpaper) {
6747 return;
6748 }
6749
6750 if (oldWallpaper != nullptr) {
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08006751 const TouchedWindow& oldTouchedWindow = state.getTouchedWindow(oldWallpaper);
6752 addWindowTargetLocked(oldWallpaper,
6753 oldTouchedWindow.targetFlags |
6754 InputTarget::Flags::DISPATCH_AS_SLIPPERY_EXIT,
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07006755 pointerIds, oldTouchedWindow.getDownTimeInTarget(deviceId), targets);
6756 state.removeTouchingPointerFromWindow(deviceId, pointerId, oldWallpaper);
Arthur Hungc539dbb2022-12-08 07:45:36 +00006757 }
6758
6759 if (newWallpaper != nullptr) {
6760 state.addOrUpdateWindow(newWallpaper,
6761 InputTarget::Flags::DISPATCH_AS_SLIPPERY_ENTER |
6762 InputTarget::Flags::WINDOW_IS_OBSCURED |
6763 InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED,
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07006764 deviceId, pointerIds);
Arthur Hungc539dbb2022-12-08 07:45:36 +00006765 }
6766}
6767
6768void InputDispatcher::transferWallpaperTouch(ftl::Flags<InputTarget::Flags> oldTargetFlags,
6769 ftl::Flags<InputTarget::Flags> newTargetFlags,
6770 const sp<WindowInfoHandle> fromWindowHandle,
6771 const sp<WindowInfoHandle> toWindowHandle,
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07006772 TouchState& state, int32_t deviceId,
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08006773 std::bitset<MAX_POINTER_ID + 1> pointerIds) {
Arthur Hungc539dbb2022-12-08 07:45:36 +00006774 const bool oldHasWallpaper = oldTargetFlags.test(InputTarget::Flags::FOREGROUND) &&
6775 fromWindowHandle->getInfo()->inputConfig.test(
6776 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
6777 const bool newHasWallpaper = newTargetFlags.test(InputTarget::Flags::FOREGROUND) &&
6778 toWindowHandle->getInfo()->inputConfig.test(
6779 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
6780
6781 const sp<WindowInfoHandle> oldWallpaper =
6782 oldHasWallpaper ? state.getWallpaperWindow() : nullptr;
6783 const sp<WindowInfoHandle> newWallpaper =
6784 newHasWallpaper ? findWallpaperWindowBelow(toWindowHandle) : nullptr;
6785 if (oldWallpaper == newWallpaper) {
6786 return;
6787 }
6788
6789 if (oldWallpaper != nullptr) {
6790 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
6791 "transferring touch focus to another window");
6792 state.removeWindowByToken(oldWallpaper->getToken());
6793 synthesizeCancelationEventsForWindowLocked(oldWallpaper, options);
6794 }
6795
6796 if (newWallpaper != nullptr) {
6797 nsecs_t downTimeInTarget = now();
6798 ftl::Flags<InputTarget::Flags> wallpaperFlags =
6799 oldTargetFlags & (InputTarget::Flags::SPLIT | InputTarget::Flags::DISPATCH_AS_IS);
6800 wallpaperFlags |= InputTarget::Flags::WINDOW_IS_OBSCURED |
6801 InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED;
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07006802 state.addOrUpdateWindow(newWallpaper, wallpaperFlags, deviceId, pointerIds,
6803 downTimeInTarget);
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006804 std::shared_ptr<Connection> wallpaperConnection =
6805 getConnectionLocked(newWallpaper->getToken());
Arthur Hungc539dbb2022-12-08 07:45:36 +00006806 if (wallpaperConnection != nullptr) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006807 std::shared_ptr<Connection> toConnection =
6808 getConnectionLocked(toWindowHandle->getToken());
Arthur Hungc539dbb2022-12-08 07:45:36 +00006809 toConnection->inputState.mergePointerStateTo(wallpaperConnection->inputState);
6810 synthesizePointerDownEventsForConnectionLocked(downTimeInTarget, wallpaperConnection,
6811 wallpaperFlags);
6812 }
6813 }
6814}
6815
6816sp<WindowInfoHandle> InputDispatcher::findWallpaperWindowBelow(
6817 const sp<WindowInfoHandle>& windowHandle) const {
6818 const std::vector<sp<WindowInfoHandle>>& windowHandles =
6819 getWindowHandlesLocked(windowHandle->getInfo()->displayId);
6820 bool foundWindow = false;
6821 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
6822 if (!foundWindow && otherHandle != windowHandle) {
6823 continue;
6824 }
6825 if (windowHandle == otherHandle) {
6826 foundWindow = true;
6827 continue;
6828 }
6829
6830 if (otherHandle->getInfo()->inputConfig.test(WindowInfo::InputConfig::IS_WALLPAPER)) {
6831 return otherHandle;
6832 }
6833 }
6834 return nullptr;
6835}
6836
Nergi Rahardi730cf3c2023-04-13 12:41:17 +09006837void InputDispatcher::setKeyRepeatConfiguration(nsecs_t timeout, nsecs_t delay) {
6838 std::scoped_lock _l(mLock);
6839
6840 mConfig.keyRepeatTimeout = timeout;
6841 mConfig.keyRepeatDelay = delay;
6842}
6843
Garfield Tane84e6f92019-08-29 17:28:41 -07006844} // namespace android::inputdispatcher