blob: 4657c011f61cf502c474fab23dfc026e3d3272ea [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)) {
Daniel Norman7487dfa2023-08-02 16:39:45 -0700671 android::base::LogSeverity severity = android::base::LogSeverity::FATAL;
672 if (entry.flags & AMOTION_EVENT_FLAG_IS_ACCESSIBILITY_EVENT) {
673 // The Accessibility injected touch exploration event stream
674 // has known inconsistencies, so log ERROR instead of
675 // crashing the device with FATAL.
676 // TODO(b/299977100): Move a11y severity back to FATAL.
677 severity = android::base::LogSeverity::ERROR;
678 }
679 LOG(severity) << "Expected ACTION_HOVER_MOVE instead of " << entry.getDescription();
Siarhei Vishniakouc2eb8502023-04-11 18:33:36 -0700680 }
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000681 touchedWindow.targetFlags = InputTarget::Flags::DISPATCH_AS_IS;
682 }
Siarhei Vishniakou0836a302023-05-03 13:54:30 -0700683 touchedWindow.addHoveringPointer(entry.deviceId, pointerId);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000684 if (canReceiveForegroundTouches(*newWindow->getInfo())) {
685 touchedWindow.targetFlags |= InputTarget::Flags::FOREGROUND;
686 }
687 out.push_back(touchedWindow);
688 }
689 return out;
690}
691
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -0800692template <typename T>
693std::vector<T>& operator+=(std::vector<T>& left, const std::vector<T>& right) {
694 left.insert(left.end(), right.begin(), right.end());
695 return left;
696}
697
Harry Cuttsb166c002023-05-09 13:06:05 +0000698// Filter windows in a TouchState and targets in a vector to remove untrusted windows/targets from
699// both.
700void filterUntrustedTargets(TouchState& touchState, std::vector<InputTarget>& targets) {
701 std::erase_if(touchState.windows, [&](const TouchedWindow& window) {
702 if (!window.windowHandle->getInfo()->inputConfig.test(
703 WindowInfo::InputConfig::TRUSTED_OVERLAY)) {
704 // In addition to TouchState, erase this window from the input targets! We don't have a
705 // good way to do this today except by adding a nested loop.
706 // TODO(b/282025641): simplify this code once InputTargets are being identified
707 // separately from TouchedWindows.
708 std::erase_if(targets, [&](const InputTarget& target) {
709 return target.inputChannel->getConnectionToken() == window.windowHandle->getToken();
710 });
711 return true;
712 }
713 return false;
714 });
715}
716
Siarhei Vishniakouce1fd472023-09-18 18:38:07 -0700717/**
718 * In general, touch should be always split between windows. Some exceptions:
719 * 1. Don't split touch if all of the below is true:
720 * (a) we have an active pointer down *and*
721 * (b) a new pointer is going down that's from the same device *and*
722 * (c) the window that's receiving the current pointer does not support split touch.
723 * 2. Don't split mouse events
724 */
725bool shouldSplitTouch(const TouchState& touchState, const MotionEntry& entry) {
726 if (isFromSource(entry.source, AINPUT_SOURCE_MOUSE)) {
727 // We should never split mouse events
728 return false;
729 }
730 for (const TouchedWindow& touchedWindow : touchState.windows) {
731 if (touchedWindow.windowHandle->getInfo()->isSpy()) {
732 // Spy windows should not affect whether or not touch is split.
733 continue;
734 }
735 if (touchedWindow.windowHandle->getInfo()->supportsSplitTouch()) {
736 continue;
737 }
738 if (touchedWindow.windowHandle->getInfo()->inputConfig.test(
739 gui::WindowInfo::InputConfig::IS_WALLPAPER)) {
740 // Wallpaper window should not affect whether or not touch is split
741 continue;
742 }
743
744 if (touchedWindow.hasTouchingPointers(entry.deviceId)) {
745 return false;
746 }
747 }
748 return true;
749}
750
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000751} // namespace
752
Michael Wrightd02c5b62014-02-10 15:10:22 -0800753// --- InputDispatcher ---
754
Prabir Pradhana41d2442023-04-20 21:30:40 +0000755InputDispatcher::InputDispatcher(InputDispatcherPolicyInterface& policy)
Siarhei Vishniakou289e9242022-02-15 14:50:16 -0800756 : InputDispatcher(policy, STALE_EVENT_TIMEOUT) {}
757
Prabir Pradhana41d2442023-04-20 21:30:40 +0000758InputDispatcher::InputDispatcher(InputDispatcherPolicyInterface& policy,
Siarhei Vishniakou289e9242022-02-15 14:50:16 -0800759 std::chrono::nanoseconds staleEventTimeout)
Garfield Tan00f511d2019-06-12 16:55:40 -0700760 : mPolicy(policy),
761 mPendingEvent(nullptr),
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700762 mLastDropReason(DropReason::NOT_DROPPED),
Garfield Tanff1f1bb2020-01-28 13:24:04 -0800763 mIdGenerator(IdGenerator::Source::INPUT_DISPATCHER),
Garfield Tan00f511d2019-06-12 16:55:40 -0700764 mAppSwitchSawKeyDown(false),
Colin Cross5b799302022-10-18 21:52:41 -0700765 mAppSwitchDueTime(LLONG_MAX),
Garfield Tan00f511d2019-06-12 16:55:40 -0700766 mNextUnblockedEvent(nullptr),
Prabir Pradhan1376fcd2022-01-21 09:56:35 -0800767 mMonitorDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT),
Garfield Tan00f511d2019-06-12 16:55:40 -0700768 mDispatchEnabled(false),
769 mDispatchFrozen(false),
770 mInputFilterEnabled(false),
Bernardo Rufinoea97d182020-08-19 14:43:14 +0100771 mMaximumObscuringOpacityForTouch(1.0f),
Siarhei Vishniakou2508b872020-12-03 16:33:53 -1000772 mFocusedDisplayId(ADISPLAY_ID_DEFAULT),
Prabir Pradhan99987712020-11-10 18:43:05 -0800773 mWindowTokenWithPointerCapture(nullptr),
Siarhei Vishniakou289e9242022-02-15 14:50:16 -0800774 mStaleEventTimeout(staleEventTimeout),
Siarhei Vishniakoua04181f2021-03-26 05:56:49 +0000775 mLatencyAggregator(),
Antonio Kantek15beb512022-06-13 22:35:41 +0000776 mLatencyTracker(&mLatencyAggregator) {
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -0700777 mLooper = sp<Looper>::make(false);
Prabir Pradhanf93562f2018-11-29 12:13:37 -0800778 mReporter = createInputReporter();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800779
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -0700780 mWindowInfoListener = sp<DispatcherWindowListener>::make(*this);
Siarhei Vishniakou31977182022-09-30 08:51:23 -0700781#if defined(__ANDROID__)
Siarhei Vishniakou18050092021-09-01 13:32:49 -0700782 SurfaceComposerClient::getDefault()->addWindowInfosListener(mWindowInfoListener);
Siarhei Vishniakou31977182022-09-30 08:51:23 -0700783#endif
Yi Kong9b14ac62018-07-17 13:48:38 -0700784 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800785}
786
787InputDispatcher::~InputDispatcher() {
Prabir Pradhancef936d2021-07-21 16:17:52 +0000788 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800789
Prabir Pradhancef936d2021-07-21 16:17:52 +0000790 resetKeyRepeatLocked();
791 releasePendingEventLocked();
792 drainInboundQueueLocked();
793 mCommandQueue.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800794
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +0000795 while (!mConnectionsByToken.empty()) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -0700796 std::shared_ptr<Connection> connection = mConnectionsByToken.begin()->second;
Harry Cutts33476232023-01-30 19:57:29 +0000797 removeInputChannelLocked(connection->inputChannel->getConnectionToken(), /*notify=*/false);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800798 }
799}
800
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700801status_t InputDispatcher::start() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700802 if (mThread) {
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700803 return ALREADY_EXISTS;
804 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700805 mThread = std::make_unique<InputThread>(
806 "InputDispatcher", [this]() { dispatchOnce(); }, [this]() { mLooper->wake(); });
807 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700808}
809
810status_t InputDispatcher::stop() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700811 if (mThread && mThread->isCallingThread()) {
812 ALOGE("InputDispatcher cannot be stopped from its own thread!");
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700813 return INVALID_OPERATION;
814 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700815 mThread.reset();
816 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700817}
818
Michael Wrightd02c5b62014-02-10 15:10:22 -0800819void InputDispatcher::dispatchOnce() {
Colin Cross5b799302022-10-18 21:52:41 -0700820 nsecs_t nextWakeupTime = LLONG_MAX;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800821 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -0800822 std::scoped_lock _l(mLock);
823 mDispatcherIsAlive.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800824
825 // Run a dispatch loop if there are no pending commands.
826 // The dispatch loop might enqueue commands to run afterwards.
827 if (!haveCommandsLocked()) {
828 dispatchOnceInnerLocked(&nextWakeupTime);
829 }
830
831 // Run all pending commands if there are any.
832 // If any commands were run then force the next poll to wake up immediately.
Prabir Pradhancef936d2021-07-21 16:17:52 +0000833 if (runCommandsLockedInterruptable()) {
Colin Cross5b799302022-10-18 21:52:41 -0700834 nextWakeupTime = LLONG_MIN;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800835 }
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800836
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700837 // If we are still waiting for ack on some events,
838 // we might have to wake up earlier to check if an app is anr'ing.
839 const nsecs_t nextAnrCheck = processAnrsLocked();
840 nextWakeupTime = std::min(nextWakeupTime, nextAnrCheck);
841
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800842 // We are about to enter an infinitely long sleep, because we have no commands or
843 // pending or queued events
Colin Cross5b799302022-10-18 21:52:41 -0700844 if (nextWakeupTime == LLONG_MAX) {
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800845 mDispatcherEnteredIdle.notify_all();
846 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800847 } // release lock
848
849 // Wait for callback or timeout or wake. (make sure we round up, not down)
850 nsecs_t currentTime = now();
851 int timeoutMillis = toMillisecondTimeoutDelay(currentTime, nextWakeupTime);
852 mLooper->pollOnce(timeoutMillis);
853}
854
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700855/**
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500856 * Raise ANR if there is no focused window.
857 * Before the ANR is raised, do a final state check:
858 * 1. The currently focused application must be the same one we are waiting for.
859 * 2. Ensure we still don't have a focused window.
860 */
861void InputDispatcher::processNoFocusedWindowAnrLocked() {
862 // Check if the application that we are waiting for is still focused.
863 std::shared_ptr<InputApplicationHandle> focusedApplication =
864 getValueByKey(mFocusedApplicationHandlesByDisplay, mAwaitedApplicationDisplayId);
865 if (focusedApplication == nullptr ||
866 focusedApplication->getApplicationToken() !=
867 mAwaitedFocusedApplication->getApplicationToken()) {
868 // Unexpected because we should have reset the ANR timer when focused application changed
869 ALOGE("Waited for a focused window, but focused application has already changed to %s",
870 focusedApplication->getName().c_str());
871 return; // The focused application has changed.
872 }
873
chaviw98318de2021-05-19 16:45:23 -0500874 const sp<WindowInfoHandle>& focusedWindowHandle =
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500875 getFocusedWindowHandleLocked(mAwaitedApplicationDisplayId);
876 if (focusedWindowHandle != nullptr) {
877 return; // We now have a focused window. No need for ANR.
878 }
879 onAnrLocked(mAwaitedFocusedApplication);
880}
881
882/**
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700883 * Check if any of the connections' wait queues have events that are too old.
884 * If we waited for events to be ack'ed for more than the window timeout, raise an ANR.
885 * Return the time at which we should wake up next.
886 */
887nsecs_t InputDispatcher::processAnrsLocked() {
888 const nsecs_t currentTime = now();
Colin Cross5b799302022-10-18 21:52:41 -0700889 nsecs_t nextAnrCheck = LLONG_MAX;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700890 // Check if we are waiting for a focused window to appear. Raise ANR if waited too long
891 if (mNoFocusedWindowTimeoutTime.has_value() && mAwaitedFocusedApplication != nullptr) {
892 if (currentTime >= *mNoFocusedWindowTimeoutTime) {
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500893 processNoFocusedWindowAnrLocked();
Chris Yea209fde2020-07-22 13:54:51 -0700894 mAwaitedFocusedApplication.reset();
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500895 mNoFocusedWindowTimeoutTime = std::nullopt;
Colin Cross5b799302022-10-18 21:52:41 -0700896 return LLONG_MIN;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700897 } else {
Siarhei Vishniakou38a6d272020-10-20 20:29:33 -0500898 // Keep waiting. We will drop the event when mNoFocusedWindowTimeoutTime comes.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700899 nextAnrCheck = *mNoFocusedWindowTimeoutTime;
900 }
901 }
902
903 // Check if any connection ANRs are due
904 nextAnrCheck = std::min(nextAnrCheck, mAnrTracker.firstTimeout());
905 if (currentTime < nextAnrCheck) { // most likely scenario
906 return nextAnrCheck; // everything is normal. Let's check again at nextAnrCheck
907 }
908
909 // If we reached here, we have an unresponsive connection.
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -0700910 std::shared_ptr<Connection> connection = getConnectionLocked(mAnrTracker.firstToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700911 if (connection == nullptr) {
912 ALOGE("Could not find connection for entry %" PRId64, mAnrTracker.firstTimeout());
913 return nextAnrCheck;
914 }
915 connection->responsive = false;
916 // Stop waking up for this unresponsive connection
917 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000918 onAnrLocked(connection);
Colin Cross5b799302022-10-18 21:52:41 -0700919 return LLONG_MIN;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700920}
921
Prabir Pradhan1376fcd2022-01-21 09:56:35 -0800922std::chrono::nanoseconds InputDispatcher::getDispatchingTimeoutLocked(
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -0700923 const std::shared_ptr<Connection>& connection) {
Prabir Pradhan1376fcd2022-01-21 09:56:35 -0800924 if (connection->monitor) {
925 return mMonitorDispatchingTimeout;
926 }
927 const sp<WindowInfoHandle> window =
928 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700929 if (window != nullptr) {
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500930 return window->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700931 }
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500932 return DEFAULT_INPUT_DISPATCHING_TIMEOUT;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700933}
934
Michael Wrightd02c5b62014-02-10 15:10:22 -0800935void InputDispatcher::dispatchOnceInnerLocked(nsecs_t* nextWakeupTime) {
936 nsecs_t currentTime = now();
937
Jeff Browndc5992e2014-04-11 01:27:26 -0700938 // Reset the key repeat timer whenever normal dispatch is suspended while the
939 // device is in a non-interactive state. This is to ensure that we abort a key
940 // repeat if the device is just coming out of sleep.
941 if (!mDispatchEnabled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800942 resetKeyRepeatLocked();
943 }
944
945 // If dispatching is frozen, do not process timeouts or try to deliver any new events.
946 if (mDispatchFrozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +0100947 if (DEBUG_FOCUS) {
948 ALOGD("Dispatch frozen. Waiting some more.");
949 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800950 return;
951 }
952
953 // Optimize latency of app switches.
954 // Essentially we start a short timeout when an app switch key (HOME / ENDCALL) has
955 // been pressed. When it expires, we preempt dispatch and drop all other pending events.
956 bool isAppSwitchDue = mAppSwitchDueTime <= currentTime;
957 if (mAppSwitchDueTime < *nextWakeupTime) {
958 *nextWakeupTime = mAppSwitchDueTime;
959 }
960
961 // Ready to start a new event.
962 // If we don't already have a pending event, go grab one.
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700963 if (!mPendingEvent) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700964 if (mInboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800965 if (isAppSwitchDue) {
966 // The inbound queue is empty so the app switch key we were waiting
967 // for will never arrive. Stop waiting for it.
968 resetPendingAppSwitchLocked(false);
969 isAppSwitchDue = false;
970 }
971
972 // Synthesize a key repeat if appropriate.
973 if (mKeyRepeatState.lastKeyEntry) {
974 if (currentTime >= mKeyRepeatState.nextRepeatTime) {
975 mPendingEvent = synthesizeKeyRepeatLocked(currentTime);
976 } else {
977 if (mKeyRepeatState.nextRepeatTime < *nextWakeupTime) {
978 *nextWakeupTime = mKeyRepeatState.nextRepeatTime;
979 }
980 }
981 }
982
983 // Nothing to do if there is no pending event.
984 if (!mPendingEvent) {
985 return;
986 }
987 } else {
988 // Inbound queue has at least one entry.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700989 mPendingEvent = mInboundQueue.front();
990 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800991 traceInboundQueueLengthLocked();
992 }
993
994 // Poke user activity for this event.
995 if (mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700996 pokeUserActivityLocked(*mPendingEvent);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800997 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800998 }
999
1000 // Now we have an event to dispatch.
1001 // All events are eventually dequeued and processed this way, even if we intend to drop them.
Yi Kong9b14ac62018-07-17 13:48:38 -07001002 ALOG_ASSERT(mPendingEvent != nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001003 bool done = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001004 DropReason dropReason = DropReason::NOT_DROPPED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001005 if (!(mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001006 dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001007 } else if (!mDispatchEnabled) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001008 dropReason = DropReason::DISABLED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001009 }
1010
1011 if (mNextUnblockedEvent == mPendingEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001012 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001013 }
1014
1015 switch (mPendingEvent->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001016 case EventEntry::Type::CONFIGURATION_CHANGED: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001017 const ConfigurationChangedEntry& typedEntry =
1018 static_cast<const ConfigurationChangedEntry&>(*mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001019 done = dispatchConfigurationChangedLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001020 dropReason = DropReason::NOT_DROPPED; // configuration changes are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001021 break;
1022 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001023
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001024 case EventEntry::Type::DEVICE_RESET: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001025 const DeviceResetEntry& typedEntry =
1026 static_cast<const DeviceResetEntry&>(*mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001027 done = dispatchDeviceResetLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001028 dropReason = DropReason::NOT_DROPPED; // device resets are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001029 break;
1030 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001031
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001032 case EventEntry::Type::FOCUS: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001033 std::shared_ptr<FocusEntry> typedEntry =
1034 std::static_pointer_cast<FocusEntry>(mPendingEvent);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001035 dispatchFocusLocked(currentTime, typedEntry);
1036 done = true;
1037 dropReason = DropReason::NOT_DROPPED; // focus events are never dropped
1038 break;
1039 }
1040
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001041 case EventEntry::Type::TOUCH_MODE_CHANGED: {
1042 const auto typedEntry = std::static_pointer_cast<TouchModeEntry>(mPendingEvent);
1043 dispatchTouchModeChangeLocked(currentTime, typedEntry);
1044 done = true;
1045 dropReason = DropReason::NOT_DROPPED; // touch mode events are never dropped
1046 break;
1047 }
1048
Prabir Pradhan99987712020-11-10 18:43:05 -08001049 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
1050 const auto typedEntry =
1051 std::static_pointer_cast<PointerCaptureChangedEntry>(mPendingEvent);
1052 dispatchPointerCaptureChangedLocked(currentTime, typedEntry, dropReason);
1053 done = true;
1054 break;
1055 }
1056
arthurhungb89ccb02020-12-30 16:19:01 +08001057 case EventEntry::Type::DRAG: {
1058 std::shared_ptr<DragEntry> typedEntry =
1059 std::static_pointer_cast<DragEntry>(mPendingEvent);
1060 dispatchDragLocked(currentTime, typedEntry);
1061 done = true;
1062 break;
1063 }
1064
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001065 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001066 std::shared_ptr<KeyEntry> keyEntry = std::static_pointer_cast<KeyEntry>(mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001067 if (isAppSwitchDue) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001068 if (isAppSwitchKeyEvent(*keyEntry)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001069 resetPendingAppSwitchLocked(true);
1070 isAppSwitchDue = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001071 } else if (dropReason == DropReason::NOT_DROPPED) {
1072 dropReason = DropReason::APP_SWITCH;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001073 }
1074 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001075 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *keyEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001076 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001077 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001078 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
1079 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001080 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001081 done = dispatchKeyLocked(currentTime, keyEntry, &dropReason, nextWakeupTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001082 break;
1083 }
1084
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001085 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001086 std::shared_ptr<MotionEntry> motionEntry =
1087 std::static_pointer_cast<MotionEntry>(mPendingEvent);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001088 if (dropReason == DropReason::NOT_DROPPED && isAppSwitchDue) {
1089 dropReason = DropReason::APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001090 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001091 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *motionEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001092 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001093 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001094 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
1095 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001096 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001097 done = dispatchMotionLocked(currentTime, motionEntry, &dropReason, nextWakeupTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001098 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001099 }
Chris Yef59a2f42020-10-16 12:55:26 -07001100
1101 case EventEntry::Type::SENSOR: {
1102 std::shared_ptr<SensorEntry> sensorEntry =
1103 std::static_pointer_cast<SensorEntry>(mPendingEvent);
1104 if (dropReason == DropReason::NOT_DROPPED && isAppSwitchDue) {
1105 dropReason = DropReason::APP_SWITCH;
1106 }
1107 // Sensor timestamps use SYSTEM_TIME_BOOTTIME time base, so we can't use
1108 // 'currentTime' here, get SYSTEM_TIME_BOOTTIME instead.
1109 nsecs_t bootTime = systemTime(SYSTEM_TIME_BOOTTIME);
1110 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(bootTime, *sensorEntry)) {
1111 dropReason = DropReason::STALE;
1112 }
1113 dispatchSensorLocked(currentTime, sensorEntry, &dropReason, nextWakeupTime);
1114 done = true;
1115 break;
1116 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001117 }
1118
1119 if (done) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001120 if (dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001121 dropInboundEventLocked(*mPendingEvent, dropReason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001122 }
Michael Wright3a981722015-06-10 15:26:13 +01001123 mLastDropReason = dropReason;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001124
1125 releasePendingEventLocked();
Colin Cross5b799302022-10-18 21:52:41 -07001126 *nextWakeupTime = LLONG_MIN; // force next poll to wake up immediately
Michael Wrightd02c5b62014-02-10 15:10:22 -08001127 }
1128}
1129
Siarhei Vishniakou289e9242022-02-15 14:50:16 -08001130bool InputDispatcher::isStaleEvent(nsecs_t currentTime, const EventEntry& entry) {
1131 return std::chrono::nanoseconds(currentTime - entry.eventTime) >= mStaleEventTimeout;
1132}
1133
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001134/**
1135 * Return true if the events preceding this incoming motion event should be dropped
1136 * Return false otherwise (the default behaviour)
1137 */
1138bool InputDispatcher::shouldPruneInboundQueueLocked(const MotionEntry& motionEntry) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001139 const bool isPointerDownEvent = motionEntry.action == AMOTION_EVENT_ACTION_DOWN &&
Prabir Pradhanaa561d12021-09-24 06:57:33 -07001140 isFromSource(motionEntry.source, AINPUT_SOURCE_CLASS_POINTER);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001141
1142 // Optimize case where the current application is unresponsive and the user
1143 // decides to touch a window in a different application.
1144 // If the application takes too long to catch up then we drop all events preceding
1145 // the touch into the other window.
1146 if (isPointerDownEvent && mAwaitedFocusedApplication != nullptr) {
Siarhei Vishniakou9306c382022-09-30 15:30:31 -07001147 const int32_t displayId = motionEntry.displayId;
1148 const auto [x, y] = resolveTouchedPosition(motionEntry);
Harry Cutts33476232023-01-30 19:57:29 +00001149 const bool isStylus = isPointerFromStylus(motionEntry, /*pointerIndex=*/0);
Siarhei Vishniakou9306c382022-09-30 15:30:31 -07001150
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07001151 sp<WindowInfoHandle> touchedWindowHandle =
1152 findTouchedWindowAtLocked(displayId, x, y, isStylus);
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001153 if (touchedWindowHandle != nullptr &&
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001154 touchedWindowHandle->getApplicationToken() !=
1155 mAwaitedFocusedApplication->getApplicationToken()) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001156 // User touched a different application than the one we are waiting on.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001157 ALOGI("Pruning input queue because user touched a different application while waiting "
1158 "for %s",
1159 mAwaitedFocusedApplication->getName().c_str());
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001160 return true;
1161 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001162
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08001163 // Alternatively, maybe there's a spy window that could handle this event.
1164 const std::vector<sp<WindowInfoHandle>> touchedSpies =
1165 findTouchedSpyWindowsAtLocked(displayId, x, y, isStylus);
1166 for (const auto& windowHandle : touchedSpies) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07001167 const std::shared_ptr<Connection> connection =
1168 getConnectionLocked(windowHandle->getToken());
Siarhei Vishniakou34ed4d42020-06-18 00:43:02 +00001169 if (connection != nullptr && connection->responsive) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08001170 // This spy window could take more input. Drop all events preceding this
1171 // event, so that the spy window can get a chance to receive the stream.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001172 ALOGW("Pruning the input queue because %s is unresponsive, but we have a "
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08001173 "responsive spy window that may handle the event.",
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001174 mAwaitedFocusedApplication->getName().c_str());
1175 return true;
1176 }
1177 }
1178 }
1179
1180 // Prevent getting stuck: if we have a pending key event, and some motion events that have not
1181 // yet been processed by some connections, the dispatcher will wait for these motion
1182 // events to be processed before dispatching the key event. This is because these motion events
1183 // may cause a new window to be launched, which the user might expect to receive focus.
1184 // To prevent waiting forever for such events, just send the key to the currently focused window
1185 if (isPointerDownEvent && mKeyIsWaitingForEventsTimeout) {
1186 ALOGD("Received a new pointer down event, stop waiting for events to process and "
1187 "just send the pending key event to the focused window.");
1188 mKeyIsWaitingForEventsTimeout = now();
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001189 }
1190 return false;
1191}
1192
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001193bool InputDispatcher::enqueueInboundEventLocked(std::unique_ptr<EventEntry> newEntry) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001194 bool needWake = mInboundQueue.empty();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001195 mInboundQueue.push_back(std::move(newEntry));
1196 EventEntry& entry = *(mInboundQueue.back());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001197 traceInboundQueueLengthLocked();
1198
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001199 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001200 case EventEntry::Type::KEY: {
Prabir Pradhan5735a322022-04-11 17:23:34 +00001201 LOG_ALWAYS_FATAL_IF((entry.policyFlags & POLICY_FLAG_TRUSTED) == 0,
1202 "Unexpected untrusted event.");
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001203 // Optimize app switch latency.
1204 // If the application takes too long to catch up then we drop all events preceding
1205 // the app switch key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001206 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001207 if (isAppSwitchKeyEvent(keyEntry)) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001208 if (keyEntry.action == AKEY_EVENT_ACTION_DOWN) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001209 mAppSwitchSawKeyDown = true;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001210 } else if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001211 if (mAppSwitchSawKeyDown) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001212 if (DEBUG_APP_SWITCH) {
1213 ALOGD("App switch is pending!");
1214 }
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001215 mAppSwitchDueTime = keyEntry.eventTime + APP_SWITCH_TIMEOUT;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001216 mAppSwitchSawKeyDown = false;
1217 needWake = true;
1218 }
1219 }
1220 }
Arthur Hung2ee6d0b2022-03-03 20:19:38 +08001221
1222 // If a new up event comes in, and the pending event with same key code has been asked
1223 // to try again later because of the policy. We have to reset the intercept key wake up
1224 // time for it may have been handled in the policy and could be dropped.
1225 if (keyEntry.action == AKEY_EVENT_ACTION_UP && mPendingEvent &&
1226 mPendingEvent->type == EventEntry::Type::KEY) {
1227 KeyEntry& pendingKey = static_cast<KeyEntry&>(*mPendingEvent);
1228 if (pendingKey.keyCode == keyEntry.keyCode &&
1229 pendingKey.interceptKeyResult ==
Michael Wright5caf55a2022-11-24 22:31:42 +00001230 KeyEntry::InterceptKeyResult::TRY_AGAIN_LATER) {
1231 pendingKey.interceptKeyResult = KeyEntry::InterceptKeyResult::UNKNOWN;
Arthur Hung2ee6d0b2022-03-03 20:19:38 +08001232 pendingKey.interceptKeyWakeupTime = 0;
1233 needWake = true;
1234 }
1235 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001236 break;
1237 }
1238
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001239 case EventEntry::Type::MOTION: {
Prabir Pradhan5735a322022-04-11 17:23:34 +00001240 LOG_ALWAYS_FATAL_IF((entry.policyFlags & POLICY_FLAG_TRUSTED) == 0,
1241 "Unexpected untrusted event.");
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001242 if (shouldPruneInboundQueueLocked(static_cast<MotionEntry&>(entry))) {
1243 mNextUnblockedEvent = mInboundQueue.back();
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001244 needWake = true;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001245 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001246 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001247 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001248 case EventEntry::Type::FOCUS: {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001249 LOG_ALWAYS_FATAL("Focus events should be inserted using enqueueFocusEventLocked");
1250 break;
1251 }
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001252 case EventEntry::Type::TOUCH_MODE_CHANGED:
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001253 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08001254 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07001255 case EventEntry::Type::SENSOR:
arthurhungb89ccb02020-12-30 16:19:01 +08001256 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
1257 case EventEntry::Type::DRAG: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001258 // nothing to do
1259 break;
1260 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001261 }
1262
1263 return needWake;
1264}
1265
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001266void InputDispatcher::addRecentEventLocked(std::shared_ptr<EventEntry> entry) {
Chris Yef59a2f42020-10-16 12:55:26 -07001267 // Do not store sensor event in recent queue to avoid flooding the queue.
1268 if (entry->type != EventEntry::Type::SENSOR) {
1269 mRecentQueue.push_back(entry);
1270 }
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001271 if (mRecentQueue.size() > RECENT_QUEUE_MAX_SIZE) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001272 mRecentQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001273 }
1274}
1275
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07001276sp<WindowInfoHandle> InputDispatcher::findTouchedWindowAtLocked(int32_t displayId, float x, float y,
1277 bool isStylus,
1278 bool ignoreDragWindow) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001279 // Traverse windows from front to back to find touched window.
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001280 const auto& windowHandles = getWindowHandlesLocked(displayId);
chaviw98318de2021-05-19 16:45:23 -05001281 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
arthurhung6d4bed92021-03-17 11:59:33 +08001282 if (ignoreDragWindow && haveSameToken(windowHandle, mDragState->dragWindow)) {
arthurhungb89ccb02020-12-30 16:19:01 +08001283 continue;
1284 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001285
Prabir Pradhan3f90d312021-11-19 03:57:24 -08001286 const WindowInfo& info = *windowHandle->getInfo();
Prabir Pradhan33e3baa2022-12-06 20:30:22 +00001287 if (!info.isSpy() &&
1288 windowAcceptsTouchAt(info, displayId, x, y, isStylus, getTransformLocked(displayId))) {
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07001289 return windowHandle;
1290 }
1291 }
1292 return nullptr;
1293}
1294
1295std::vector<InputTarget> InputDispatcher::findOutsideTargetsLocked(
1296 int32_t displayId, const sp<WindowInfoHandle>& touchedWindow) const {
1297 if (touchedWindow == nullptr) {
1298 return {};
1299 }
1300 // Traverse windows from front to back until we encounter the touched window.
1301 std::vector<InputTarget> outsideTargets;
1302 const auto& windowHandles = getWindowHandlesLocked(displayId);
1303 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
1304 if (windowHandle == touchedWindow) {
1305 // Stop iterating once we found a touched window. Any WATCH_OUTSIDE_TOUCH window
1306 // below the touched window will not get ACTION_OUTSIDE event.
1307 return outsideTargets;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08001308 }
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001309
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07001310 const WindowInfo& info = *windowHandle->getInfo();
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08001311 if (info.inputConfig.test(WindowInfo::InputConfig::WATCH_OUTSIDE_TOUCH)) {
1312 addWindowTargetLocked(windowHandle, InputTarget::Flags::DISPATCH_AS_OUTSIDE,
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08001313 /*pointerIds=*/{}, /*firstDownTimeInTarget=*/std::nullopt,
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08001314 outsideTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001315 }
1316 }
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07001317 return outsideTargets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001318}
1319
Prabir Pradhand65552b2021-10-07 11:23:50 -07001320std::vector<sp<WindowInfoHandle>> InputDispatcher::findTouchedSpyWindowsAtLocked(
Prabir Pradhan82e081e2022-12-06 09:50:09 +00001321 int32_t displayId, float x, float y, bool isStylus) const {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001322 // Traverse windows from front to back and gather the touched spy windows.
1323 std::vector<sp<WindowInfoHandle>> spyWindows;
1324 const auto& windowHandles = getWindowHandlesLocked(displayId);
1325 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
1326 const WindowInfo& info = *windowHandle->getInfo();
1327
Prabir Pradhan33e3baa2022-12-06 20:30:22 +00001328 if (!windowAcceptsTouchAt(info, displayId, x, y, isStylus, getTransformLocked(displayId))) {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001329 continue;
1330 }
1331 if (!info.isSpy()) {
1332 // The first touched non-spy window was found, so return the spy windows touched so far.
1333 return spyWindows;
1334 }
1335 spyWindows.push_back(windowHandle);
1336 }
1337 return spyWindows;
1338}
1339
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001340void InputDispatcher::dropInboundEventLocked(const EventEntry& entry, DropReason dropReason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001341 const char* reason;
1342 switch (dropReason) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001343 case DropReason::POLICY:
Prabir Pradhan65613802023-02-22 23:36:58 +00001344 if (debugInboundEventDetails()) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001345 ALOGD("Dropped event because policy consumed it.");
1346 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001347 reason = "inbound event was dropped because the policy consumed it";
1348 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001349 case DropReason::DISABLED:
1350 if (mLastDropReason != DropReason::DISABLED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001351 ALOGI("Dropped event because input dispatch is disabled.");
1352 }
1353 reason = "inbound event was dropped because input dispatch is disabled";
1354 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001355 case DropReason::APP_SWITCH:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001356 ALOGI("Dropped event because of pending overdue app switch.");
1357 reason = "inbound event was dropped because of pending overdue app switch";
1358 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001359 case DropReason::BLOCKED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001360 ALOGI("Dropped event because the current application is not responding and the user "
1361 "has started interacting with a different application.");
1362 reason = "inbound event was dropped because the current application is not responding "
1363 "and the user has started interacting with a different application";
1364 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001365 case DropReason::STALE:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001366 ALOGI("Dropped event because it is stale.");
1367 reason = "inbound event was dropped because it is stale";
1368 break;
Prabir Pradhan99987712020-11-10 18:43:05 -08001369 case DropReason::NO_POINTER_CAPTURE:
1370 ALOGI("Dropped event because there is no window with Pointer Capture.");
1371 reason = "inbound event was dropped because there is no window with Pointer Capture";
1372 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001373 case DropReason::NOT_DROPPED: {
1374 LOG_ALWAYS_FATAL("Should not be dropping a NOT_DROPPED event");
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001375 return;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001376 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001377 }
1378
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001379 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001380 case EventEntry::Type::KEY: {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001381 CancelationOptions options(CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS, reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001382 synthesizeCancelationEventsForAllConnectionsLocked(options);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001383 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001384 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001385 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001386 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
1387 if (motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001388 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS, reason);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001389 synthesizeCancelationEventsForAllConnectionsLocked(options);
1390 } else {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001391 CancelationOptions options(CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS,
1392 reason);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001393 synthesizeCancelationEventsForAllConnectionsLocked(options);
1394 }
1395 break;
1396 }
Chris Yef59a2f42020-10-16 12:55:26 -07001397 case EventEntry::Type::SENSOR: {
1398 break;
1399 }
arthurhungb89ccb02020-12-30 16:19:01 +08001400 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
1401 case EventEntry::Type::DRAG: {
Prabir Pradhan99987712020-11-10 18:43:05 -08001402 break;
1403 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001404 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001405 case EventEntry::Type::TOUCH_MODE_CHANGED:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001406 case EventEntry::Type::CONFIGURATION_CHANGED:
1407 case EventEntry::Type::DEVICE_RESET: {
Dominik Laskowski75788452021-02-09 18:51:25 -08001408 LOG_ALWAYS_FATAL("Should not drop %s events", ftl::enum_string(entry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001409 break;
1410 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001411 }
1412}
1413
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08001414static bool isAppSwitchKeyCode(int32_t keyCode) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001415 return keyCode == AKEYCODE_HOME || keyCode == AKEYCODE_ENDCALL ||
1416 keyCode == AKEYCODE_APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001417}
1418
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001419bool InputDispatcher::isAppSwitchKeyEvent(const KeyEntry& keyEntry) {
1420 return !(keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) && isAppSwitchKeyCode(keyEntry.keyCode) &&
1421 (keyEntry.policyFlags & POLICY_FLAG_TRUSTED) &&
1422 (keyEntry.policyFlags & POLICY_FLAG_PASS_TO_USER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001423}
1424
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07001425bool InputDispatcher::isAppSwitchPendingLocked() const {
Colin Cross5b799302022-10-18 21:52:41 -07001426 return mAppSwitchDueTime != LLONG_MAX;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001427}
1428
1429void InputDispatcher::resetPendingAppSwitchLocked(bool handled) {
Colin Cross5b799302022-10-18 21:52:41 -07001430 mAppSwitchDueTime = LLONG_MAX;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001431
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001432 if (DEBUG_APP_SWITCH) {
1433 if (handled) {
1434 ALOGD("App switch has arrived.");
1435 } else {
1436 ALOGD("App switch was abandoned.");
1437 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001438 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001439}
1440
Michael Wrightd02c5b62014-02-10 15:10:22 -08001441bool InputDispatcher::haveCommandsLocked() const {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001442 return !mCommandQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001443}
1444
Prabir Pradhancef936d2021-07-21 16:17:52 +00001445bool InputDispatcher::runCommandsLockedInterruptable() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001446 if (mCommandQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001447 return false;
1448 }
1449
1450 do {
Prabir Pradhancef936d2021-07-21 16:17:52 +00001451 auto command = std::move(mCommandQueue.front());
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001452 mCommandQueue.pop_front();
Prabir Pradhancef936d2021-07-21 16:17:52 +00001453 // Commands are run with the lock held, but may release and re-acquire the lock from within.
1454 command();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001455 } while (!mCommandQueue.empty());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001456 return true;
1457}
1458
Prabir Pradhancef936d2021-07-21 16:17:52 +00001459void InputDispatcher::postCommandLocked(Command&& command) {
1460 mCommandQueue.push_back(command);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001461}
1462
1463void InputDispatcher::drainInboundQueueLocked() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001464 while (!mInboundQueue.empty()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001465 std::shared_ptr<EventEntry> entry = mInboundQueue.front();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001466 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001467 releaseInboundEventLocked(entry);
1468 }
1469 traceInboundQueueLengthLocked();
1470}
1471
1472void InputDispatcher::releasePendingEventLocked() {
1473 if (mPendingEvent) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001474 releaseInboundEventLocked(mPendingEvent);
Yi Kong9b14ac62018-07-17 13:48:38 -07001475 mPendingEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001476 }
1477}
1478
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001479void InputDispatcher::releaseInboundEventLocked(std::shared_ptr<EventEntry> entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001480 InjectionState* injectionState = entry->injectionState;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001481 if (injectionState && injectionState->injectionResult == InputEventInjectionResult::PENDING) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001482 if (DEBUG_DISPATCH_CYCLE) {
1483 ALOGD("Injected inbound event was dropped.");
1484 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001485 setInjectionResult(*entry, InputEventInjectionResult::FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001486 }
1487 if (entry == mNextUnblockedEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001488 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001489 }
1490 addRecentEventLocked(entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001491}
1492
1493void InputDispatcher::resetKeyRepeatLocked() {
1494 if (mKeyRepeatState.lastKeyEntry) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001495 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001496 }
1497}
1498
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001499std::shared_ptr<KeyEntry> InputDispatcher::synthesizeKeyRepeatLocked(nsecs_t currentTime) {
1500 std::shared_ptr<KeyEntry> entry = mKeyRepeatState.lastKeyEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001501
Michael Wright2e732952014-09-24 13:26:59 -07001502 uint32_t policyFlags = entry->policyFlags &
1503 (POLICY_FLAG_RAW_MASK | POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_TRUSTED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001504
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001505 std::shared_ptr<KeyEntry> newEntry =
1506 std::make_unique<KeyEntry>(mIdGenerator.nextId(), currentTime, entry->deviceId,
1507 entry->source, entry->displayId, policyFlags, entry->action,
1508 entry->flags, entry->keyCode, entry->scanCode,
1509 entry->metaState, entry->repeatCount + 1, entry->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001510
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001511 newEntry->syntheticRepeat = true;
1512 mKeyRepeatState.lastKeyEntry = newEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001513 mKeyRepeatState.nextRepeatTime = currentTime + mConfig.keyRepeatDelay;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001514 return newEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001515}
1516
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001517bool InputDispatcher::dispatchConfigurationChangedLocked(nsecs_t currentTime,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001518 const ConfigurationChangedEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001519 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1520 ALOGD("dispatchConfigurationChanged - eventTime=%" PRId64, entry.eventTime);
1521 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001522
1523 // Reset key repeating in case a keyboard device was added or removed or something.
1524 resetKeyRepeatLocked();
1525
1526 // Enqueue a command to run outside the lock to tell the policy that the configuration changed.
Prabir Pradhancef936d2021-07-21 16:17:52 +00001527 auto command = [this, eventTime = entry.eventTime]() REQUIRES(mLock) {
1528 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00001529 mPolicy.notifyConfigurationChanged(eventTime);
Prabir Pradhancef936d2021-07-21 16:17:52 +00001530 };
1531 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001532 return true;
1533}
1534
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001535bool InputDispatcher::dispatchDeviceResetLocked(nsecs_t currentTime,
1536 const DeviceResetEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001537 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1538 ALOGD("dispatchDeviceReset - eventTime=%" PRId64 ", deviceId=%d", entry.eventTime,
1539 entry.deviceId);
1540 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001541
liushenxiang42232912021-05-21 20:24:09 +08001542 // Reset key repeating in case a keyboard device was disabled or enabled.
1543 if (mKeyRepeatState.lastKeyEntry && mKeyRepeatState.lastKeyEntry->deviceId == entry.deviceId) {
1544 resetKeyRepeatLocked();
1545 }
1546
Michael Wrightfb04fd52022-11-24 22:31:11 +00001547 CancelationOptions options(CancelationOptions::Mode::CANCEL_ALL_EVENTS, "device was reset");
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001548 options.deviceId = entry.deviceId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001549 synthesizeCancelationEventsForAllConnectionsLocked(options);
Siarhei Vishniakou0686f0c2023-05-02 11:56:15 -07001550
1551 // Remove all active pointers from this device
1552 for (auto& [_, touchState] : mTouchStatesByDisplay) {
1553 touchState.removeAllPointersForDevice(entry.deviceId);
1554 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001555 return true;
1556}
1557
Vishnu Nairad321cd2020-08-20 16:40:21 -07001558void InputDispatcher::enqueueFocusEventLocked(const sp<IBinder>& windowToken, bool hasFocus,
Vishnu Nairc519ff72021-01-21 08:23:08 -08001559 const std::string& reason) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001560 if (mPendingEvent != nullptr) {
1561 // Move the pending event to the front of the queue. This will give the chance
1562 // for the pending event to get dispatched to the newly focused window
1563 mInboundQueue.push_front(mPendingEvent);
1564 mPendingEvent = nullptr;
1565 }
1566
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001567 std::unique_ptr<FocusEntry> focusEntry =
1568 std::make_unique<FocusEntry>(mIdGenerator.nextId(), now(), windowToken, hasFocus,
1569 reason);
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001570
1571 // This event should go to the front of the queue, but behind all other focus events
1572 // Find the last focus event, and insert right after it
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001573 std::deque<std::shared_ptr<EventEntry>>::reverse_iterator it =
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001574 std::find_if(mInboundQueue.rbegin(), mInboundQueue.rend(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001575 [](const std::shared_ptr<EventEntry>& event) {
1576 return event->type == EventEntry::Type::FOCUS;
1577 });
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001578
1579 // Maintain the order of focus events. Insert the entry after all other focus events.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001580 mInboundQueue.insert(it.base(), std::move(focusEntry));
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001581}
1582
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001583void InputDispatcher::dispatchFocusLocked(nsecs_t currentTime, std::shared_ptr<FocusEntry> entry) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05001584 std::shared_ptr<InputChannel> channel = getInputChannelLocked(entry->connectionToken);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001585 if (channel == nullptr) {
1586 return; // Window has gone away
1587 }
1588 InputTarget target;
1589 target.inputChannel = channel;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08001590 target.flags = InputTarget::Flags::DISPATCH_AS_IS;
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001591 entry->dispatchInProgress = true;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00001592 std::string message = std::string("Focus ") + (entry->hasFocus ? "entering " : "leaving ") +
1593 channel->getName();
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07001594 std::string reason = std::string("reason=").append(entry->reason);
1595 android_log_event_list(LOGTAG_INPUT_FOCUS) << message << reason << LOG_ID_EVENTS;
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001596 dispatchEventLocked(currentTime, entry, {target});
1597}
1598
Prabir Pradhan99987712020-11-10 18:43:05 -08001599void InputDispatcher::dispatchPointerCaptureChangedLocked(
1600 nsecs_t currentTime, const std::shared_ptr<PointerCaptureChangedEntry>& entry,
1601 DropReason& dropReason) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001602 dropReason = DropReason::NOT_DROPPED;
1603
Prabir Pradhan99987712020-11-10 18:43:05 -08001604 const bool haveWindowWithPointerCapture = mWindowTokenWithPointerCapture != nullptr;
Prabir Pradhan99987712020-11-10 18:43:05 -08001605 sp<IBinder> token;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001606
1607 if (entry->pointerCaptureRequest.enable) {
1608 // Enable Pointer Capture.
1609 if (haveWindowWithPointerCapture &&
1610 (entry->pointerCaptureRequest == mCurrentPointerCaptureRequest)) {
Prabir Pradhan7092e262022-05-03 16:51:09 +00001611 // This can happen if pointer capture is disabled and re-enabled before we notify the
1612 // app of the state change, so there is no need to notify the app.
1613 ALOGI("Skipping dispatch of Pointer Capture being enabled: no state change.");
1614 return;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001615 }
1616 if (!mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08001617 // This can happen if a window requests capture and immediately releases capture.
1618 ALOGW("No window requested Pointer Capture.");
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001619 dropReason = DropReason::NO_POINTER_CAPTURE;
Prabir Pradhan99987712020-11-10 18:43:05 -08001620 return;
1621 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001622 if (entry->pointerCaptureRequest.seq != mCurrentPointerCaptureRequest.seq) {
1623 ALOGI("Skipping dispatch of Pointer Capture being enabled: sequence number mismatch.");
1624 return;
1625 }
1626
Vishnu Nairc519ff72021-01-21 08:23:08 -08001627 token = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Prabir Pradhan99987712020-11-10 18:43:05 -08001628 LOG_ALWAYS_FATAL_IF(!token, "Cannot find focused window for Pointer Capture.");
1629 mWindowTokenWithPointerCapture = token;
1630 } else {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001631 // Disable Pointer Capture.
1632 // We do not check if the sequence number matches for requests to disable Pointer Capture
1633 // for two reasons:
1634 // 1. Pointer Capture can be disabled by a focus change, which means we can get two entries
1635 // to disable capture with the same sequence number: one generated by
1636 // disablePointerCaptureForcedLocked() and another as an acknowledgement of Pointer
1637 // Capture being disabled in InputReader.
1638 // 2. We respect any request to disable Pointer Capture generated by InputReader, since the
1639 // actual Pointer Capture state that affects events being generated by input devices is
1640 // in InputReader.
1641 if (!haveWindowWithPointerCapture) {
1642 // Pointer capture was already forcefully disabled because of focus change.
1643 dropReason = DropReason::NOT_DROPPED;
1644 return;
1645 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001646 token = mWindowTokenWithPointerCapture;
1647 mWindowTokenWithPointerCapture = nullptr;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001648 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan7d030382020-12-21 07:58:35 -08001649 setPointerCaptureLocked(false);
1650 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001651 }
1652
1653 auto channel = getInputChannelLocked(token);
1654 if (channel == nullptr) {
1655 // Window has gone away, clean up Pointer Capture state.
1656 mWindowTokenWithPointerCapture = nullptr;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001657 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan7d030382020-12-21 07:58:35 -08001658 setPointerCaptureLocked(false);
1659 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001660 return;
1661 }
1662 InputTarget target;
1663 target.inputChannel = channel;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08001664 target.flags = InputTarget::Flags::DISPATCH_AS_IS;
Prabir Pradhan99987712020-11-10 18:43:05 -08001665 entry->dispatchInProgress = true;
1666 dispatchEventLocked(currentTime, entry, {target});
1667
1668 dropReason = DropReason::NOT_DROPPED;
1669}
1670
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001671void InputDispatcher::dispatchTouchModeChangeLocked(nsecs_t currentTime,
1672 const std::shared_ptr<TouchModeEntry>& entry) {
1673 const std::vector<sp<WindowInfoHandle>>& windowHandles =
Antonio Kantek15beb512022-06-13 22:35:41 +00001674 getWindowHandlesLocked(entry->displayId);
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001675 if (windowHandles.empty()) {
1676 return;
1677 }
1678 const std::vector<InputTarget> inputTargets =
1679 getInputTargetsFromWindowHandlesLocked(windowHandles);
1680 if (inputTargets.empty()) {
1681 return;
1682 }
1683 entry->dispatchInProgress = true;
1684 dispatchEventLocked(currentTime, entry, inputTargets);
1685}
1686
1687std::vector<InputTarget> InputDispatcher::getInputTargetsFromWindowHandlesLocked(
1688 const std::vector<sp<WindowInfoHandle>>& windowHandles) const {
1689 std::vector<InputTarget> inputTargets;
1690 for (const sp<WindowInfoHandle>& handle : windowHandles) {
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001691 const sp<IBinder>& token = handle->getToken();
1692 if (token == nullptr) {
1693 continue;
1694 }
1695 std::shared_ptr<InputChannel> channel = getInputChannelLocked(token);
1696 if (channel == nullptr) {
1697 continue; // Window has gone away
1698 }
1699 InputTarget target;
1700 target.inputChannel = channel;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08001701 target.flags = InputTarget::Flags::DISPATCH_AS_IS;
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001702 inputTargets.push_back(target);
1703 }
1704 return inputTargets;
1705}
1706
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001707bool InputDispatcher::dispatchKeyLocked(nsecs_t currentTime, std::shared_ptr<KeyEntry> entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001708 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001709 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001710 if (!entry->dispatchInProgress) {
1711 if (entry->repeatCount == 0 && entry->action == AKEY_EVENT_ACTION_DOWN &&
1712 (entry->policyFlags & POLICY_FLAG_TRUSTED) &&
1713 (!(entry->policyFlags & POLICY_FLAG_DISABLE_KEY_REPEAT))) {
1714 if (mKeyRepeatState.lastKeyEntry &&
Chris Ye2ad95392020-09-01 13:44:44 -07001715 mKeyRepeatState.lastKeyEntry->keyCode == entry->keyCode &&
Michael Wrightd02c5b62014-02-10 15:10:22 -08001716 // We have seen two identical key downs in a row which indicates that the device
1717 // driver is automatically generating key repeats itself. We take note of the
1718 // repeat here, but we disable our own next key repeat timer since it is clear that
1719 // we will not need to synthesize key repeats ourselves.
Chris Ye2ad95392020-09-01 13:44:44 -07001720 mKeyRepeatState.lastKeyEntry->deviceId == entry->deviceId) {
1721 // Make sure we don't get key down from a different device. If a different
1722 // device Id has same key pressed down, the new device Id will replace the
1723 // current one to hold the key repeat with repeat count reset.
1724 // In the future when got a KEY_UP on the device id, drop it and do not
1725 // stop the key repeat on current device.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001726 entry->repeatCount = mKeyRepeatState.lastKeyEntry->repeatCount + 1;
1727 resetKeyRepeatLocked();
Colin Cross5b799302022-10-18 21:52:41 -07001728 mKeyRepeatState.nextRepeatTime = LLONG_MAX; // don't generate repeats ourselves
Michael Wrightd02c5b62014-02-10 15:10:22 -08001729 } else {
1730 // Not a repeat. Save key down state in case we do see a repeat later.
1731 resetKeyRepeatLocked();
1732 mKeyRepeatState.nextRepeatTime = entry->eventTime + mConfig.keyRepeatTimeout;
1733 }
1734 mKeyRepeatState.lastKeyEntry = entry;
Chris Ye2ad95392020-09-01 13:44:44 -07001735 } else if (entry->action == AKEY_EVENT_ACTION_UP && mKeyRepeatState.lastKeyEntry &&
1736 mKeyRepeatState.lastKeyEntry->deviceId != entry->deviceId) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001737 // The key on device 'deviceId' is still down, do not stop key repeat
Prabir Pradhan65613802023-02-22 23:36:58 +00001738 if (debugInboundEventDetails()) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001739 ALOGD("deviceId=%d got KEY_UP as stale", entry->deviceId);
1740 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001741 } else if (!entry->syntheticRepeat) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001742 resetKeyRepeatLocked();
1743 }
1744
1745 if (entry->repeatCount == 1) {
1746 entry->flags |= AKEY_EVENT_FLAG_LONG_PRESS;
1747 } else {
1748 entry->flags &= ~AKEY_EVENT_FLAG_LONG_PRESS;
1749 }
1750
1751 entry->dispatchInProgress = true;
1752
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001753 logOutboundKeyDetails("dispatchKey - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001754 }
1755
1756 // Handle case where the policy asked us to try again later last time.
Michael Wright5caf55a2022-11-24 22:31:42 +00001757 if (entry->interceptKeyResult == KeyEntry::InterceptKeyResult::TRY_AGAIN_LATER) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001758 if (currentTime < entry->interceptKeyWakeupTime) {
1759 if (entry->interceptKeyWakeupTime < *nextWakeupTime) {
1760 *nextWakeupTime = entry->interceptKeyWakeupTime;
1761 }
1762 return false; // wait until next wakeup
1763 }
Michael Wright5caf55a2022-11-24 22:31:42 +00001764 entry->interceptKeyResult = KeyEntry::InterceptKeyResult::UNKNOWN;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001765 entry->interceptKeyWakeupTime = 0;
1766 }
1767
1768 // Give the policy a chance to intercept the key.
Michael Wright5caf55a2022-11-24 22:31:42 +00001769 if (entry->interceptKeyResult == KeyEntry::InterceptKeyResult::UNKNOWN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001770 if (entry->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07001771 sp<IBinder> focusedWindowToken =
Vishnu Nairc519ff72021-01-21 08:23:08 -08001772 mFocusResolver.getFocusedWindowToken(getTargetDisplayId(*entry));
Prabir Pradhancef936d2021-07-21 16:17:52 +00001773
1774 auto command = [this, focusedWindowToken, entry]() REQUIRES(mLock) {
1775 doInterceptKeyBeforeDispatchingCommand(focusedWindowToken, *entry);
1776 };
1777 postCommandLocked(std::move(command));
Josep del Riob3981622023-04-18 15:49:45 +00001778 // Poke user activity for keys not passed to user
1779 pokeUserActivityLocked(*entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001780 return false; // wait for the command to run
1781 } else {
Michael Wright5caf55a2022-11-24 22:31:42 +00001782 entry->interceptKeyResult = KeyEntry::InterceptKeyResult::CONTINUE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001783 }
Michael Wright5caf55a2022-11-24 22:31:42 +00001784 } else if (entry->interceptKeyResult == KeyEntry::InterceptKeyResult::SKIP) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001785 if (*dropReason == DropReason::NOT_DROPPED) {
1786 *dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001787 }
1788 }
1789
1790 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001791 if (*dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001792 setInjectionResult(*entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001793 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
1794 : InputEventInjectionResult::FAILED);
Garfield Tan6a5a14e2020-01-28 13:24:04 -08001795 mReporter->reportDroppedKey(entry->id);
Josep del Riob3981622023-04-18 15:49:45 +00001796 // Poke user activity for undispatched keys
1797 pokeUserActivityLocked(*entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001798 return true;
1799 }
1800
1801 // Identify targets.
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001802 InputEventInjectionResult injectionResult;
1803 sp<WindowInfoHandle> focusedWindow =
1804 findFocusedWindowTargetLocked(currentTime, *entry, nextWakeupTime,
1805 /*byref*/ injectionResult);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001806 if (injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001807 return false;
1808 }
1809
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001810 setInjectionResult(*entry, injectionResult);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001811 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001812 return true;
1813 }
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001814 LOG_ALWAYS_FATAL_IF(focusedWindow == nullptr);
1815
1816 std::vector<InputTarget> inputTargets;
1817 addWindowTargetLocked(focusedWindow,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08001818 InputTarget::Flags::FOREGROUND | InputTarget::Flags::DISPATCH_AS_IS,
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08001819 /*pointerIds=*/{}, getDownTime(*entry), inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001820
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001821 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001822 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001823
1824 // Dispatch the key.
1825 dispatchEventLocked(currentTime, entry, inputTargets);
1826 return true;
1827}
1828
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001829void InputDispatcher::logOutboundKeyDetails(const char* prefix, const KeyEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001830 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1831 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32 ", "
1832 "policyFlags=0x%x, action=0x%x, flags=0x%x, keyCode=0x%x, scanCode=0x%x, "
1833 "metaState=0x%x, repeatCount=%d, downTime=%" PRId64,
1834 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId,
1835 entry.policyFlags, entry.action, entry.flags, entry.keyCode, entry.scanCode,
1836 entry.metaState, entry.repeatCount, entry.downTime);
1837 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001838}
1839
Prabir Pradhancef936d2021-07-21 16:17:52 +00001840void InputDispatcher::dispatchSensorLocked(nsecs_t currentTime,
1841 const std::shared_ptr<SensorEntry>& entry,
Chris Yef59a2f42020-10-16 12:55:26 -07001842 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001843 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1844 ALOGD("notifySensorEvent eventTime=%" PRId64 ", hwTimestamp=%" PRId64 ", deviceId=%d, "
1845 "source=0x%x, sensorType=%s",
1846 entry->eventTime, entry->hwTimestamp, entry->deviceId, entry->source,
Dominik Laskowski75788452021-02-09 18:51:25 -08001847 ftl::enum_string(entry->sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001848 }
Prabir Pradhancef936d2021-07-21 16:17:52 +00001849 auto command = [this, entry]() REQUIRES(mLock) {
1850 scoped_unlock unlock(mLock);
1851
1852 if (entry->accuracyChanged) {
Prabir Pradhana41d2442023-04-20 21:30:40 +00001853 mPolicy.notifySensorAccuracy(entry->deviceId, entry->sensorType, entry->accuracy);
Prabir Pradhancef936d2021-07-21 16:17:52 +00001854 }
Prabir Pradhana41d2442023-04-20 21:30:40 +00001855 mPolicy.notifySensorEvent(entry->deviceId, entry->sensorType, entry->accuracy,
1856 entry->hwTimestamp, entry->values);
Prabir Pradhancef936d2021-07-21 16:17:52 +00001857 };
1858 postCommandLocked(std::move(command));
Chris Yef59a2f42020-10-16 12:55:26 -07001859}
1860
1861bool InputDispatcher::flushSensor(int deviceId, InputDeviceSensorType sensorType) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001862 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1863 ALOGD("flushSensor deviceId=%d, sensorType=%s", deviceId,
Dominik Laskowski75788452021-02-09 18:51:25 -08001864 ftl::enum_string(sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001865 }
Chris Yef59a2f42020-10-16 12:55:26 -07001866 { // acquire lock
1867 std::scoped_lock _l(mLock);
1868
1869 for (auto it = mInboundQueue.begin(); it != mInboundQueue.end(); it++) {
1870 std::shared_ptr<EventEntry> entry = *it;
1871 if (entry->type == EventEntry::Type::SENSOR) {
1872 it = mInboundQueue.erase(it);
1873 releaseInboundEventLocked(entry);
1874 }
1875 }
1876 }
1877 return true;
1878}
1879
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001880bool InputDispatcher::dispatchMotionLocked(nsecs_t currentTime, std::shared_ptr<MotionEntry> entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001881 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001882 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001883 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001884 if (!entry->dispatchInProgress) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001885 entry->dispatchInProgress = true;
1886
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001887 logOutboundMotionDetails("dispatchMotion - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001888 }
1889
1890 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001891 if (*dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001892 setInjectionResult(*entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001893 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
1894 : InputEventInjectionResult::FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001895 return true;
1896 }
1897
Prabir Pradhanaa561d12021-09-24 06:57:33 -07001898 const bool isPointerEvent = isFromSource(entry->source, AINPUT_SOURCE_CLASS_POINTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001899
1900 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001901 std::vector<InputTarget> inputTargets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001902
1903 bool conflictingPointerActions = false;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001904 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001905 if (isPointerEvent) {
1906 // Pointer event. (eg. touchscreen)
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00001907
1908 if (mDragState &&
1909 (entry->action & AMOTION_EVENT_ACTION_MASK) == AMOTION_EVENT_ACTION_POINTER_DOWN) {
1910 // If drag and drop ongoing and pointer down occur: pilfer drag window pointers
1911 pilferPointersLocked(mDragState->dragWindow->getToken());
1912 }
1913
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08001914 inputTargets =
Siarhei Vishniakou4fe57392022-10-25 13:44:30 -07001915 findTouchedWindowTargetsLocked(currentTime, *entry, &conflictingPointerActions,
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001916 /*byref*/ injectionResult);
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08001917 LOG_ALWAYS_FATAL_IF(injectionResult != InputEventInjectionResult::SUCCEEDED &&
1918 !inputTargets.empty());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001919 } else {
1920 // Non touch event. (eg. trackball)
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001921 sp<WindowInfoHandle> focusedWindow =
1922 findFocusedWindowTargetLocked(currentTime, *entry, nextWakeupTime, injectionResult);
1923 if (injectionResult == InputEventInjectionResult::SUCCEEDED) {
1924 LOG_ALWAYS_FATAL_IF(focusedWindow == nullptr);
1925 addWindowTargetLocked(focusedWindow,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08001926 InputTarget::Flags::FOREGROUND |
1927 InputTarget::Flags::DISPATCH_AS_IS,
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08001928 /*pointerIds=*/{}, getDownTime(*entry), inputTargets);
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001929 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001930 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001931 if (injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001932 return false;
1933 }
1934
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001935 setInjectionResult(*entry, injectionResult);
Prabir Pradhan5735a322022-04-11 17:23:34 +00001936 if (injectionResult == InputEventInjectionResult::TARGET_MISMATCH) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001937 return true;
1938 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001939 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001940 CancelationOptions::Mode mode(
1941 isPointerEvent ? CancelationOptions::Mode::CANCEL_POINTER_EVENTS
1942 : CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS);
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001943 CancelationOptions options(mode, "input event injection failed");
1944 synthesizeCancelationEventsForMonitorsLocked(options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001945 return true;
1946 }
1947
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001948 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001949 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001950
1951 // Dispatch the motion.
1952 if (conflictingPointerActions) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001953 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001954 "conflicting pointer actions");
Michael Wrightd02c5b62014-02-10 15:10:22 -08001955 synthesizeCancelationEventsForAllConnectionsLocked(options);
1956 }
1957 dispatchEventLocked(currentTime, entry, inputTargets);
1958 return true;
1959}
1960
chaviw98318de2021-05-19 16:45:23 -05001961void InputDispatcher::enqueueDragEventLocked(const sp<WindowInfoHandle>& windowHandle,
Arthur Hung54745652022-04-20 07:17:41 +00001962 bool isExiting, const int32_t rawX,
1963 const int32_t rawY) {
1964 const vec2 xy = windowHandle->getInfo()->transform.transform(vec2(rawX, rawY));
arthurhungb89ccb02020-12-30 16:19:01 +08001965 std::unique_ptr<DragEntry> dragEntry =
Arthur Hung54745652022-04-20 07:17:41 +00001966 std::make_unique<DragEntry>(mIdGenerator.nextId(), now(), windowHandle->getToken(),
1967 isExiting, xy.x, xy.y);
arthurhungb89ccb02020-12-30 16:19:01 +08001968
1969 enqueueInboundEventLocked(std::move(dragEntry));
1970}
1971
1972void InputDispatcher::dispatchDragLocked(nsecs_t currentTime, std::shared_ptr<DragEntry> entry) {
1973 std::shared_ptr<InputChannel> channel = getInputChannelLocked(entry->connectionToken);
1974 if (channel == nullptr) {
1975 return; // Window has gone away
1976 }
1977 InputTarget target;
1978 target.inputChannel = channel;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08001979 target.flags = InputTarget::Flags::DISPATCH_AS_IS;
arthurhungb89ccb02020-12-30 16:19:01 +08001980 entry->dispatchInProgress = true;
1981 dispatchEventLocked(currentTime, entry, {target});
1982}
1983
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001984void InputDispatcher::logOutboundMotionDetails(const char* prefix, const MotionEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001985 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -08001986 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=%s, displayId=%" PRId32
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001987 ", policyFlags=0x%x, "
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001988 "action=%s, actionButton=0x%x, flags=0x%x, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001989 "metaState=0x%x, buttonState=0x%x,"
1990 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%" PRId64,
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -08001991 prefix, entry.eventTime, entry.deviceId,
1992 inputEventSourceToString(entry.source).c_str(), entry.displayId, entry.policyFlags,
1993 MotionEvent::actionToString(entry.action).c_str(), entry.actionButton, entry.flags,
1994 entry.metaState, entry.buttonState, entry.edgeFlags, entry.xPrecision,
1995 entry.yPrecision, entry.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001996
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001997 for (uint32_t i = 0; i < entry.pointerCount; i++) {
Siarhei Vishniakou09a8fe42022-07-21 17:27:03 -07001998 ALOGD(" Pointer %d: id=%d, toolType=%s, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001999 "x=%f, y=%f, pressure=%f, size=%f, "
2000 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
2001 "orientation=%f",
Siarhei Vishniakou09a8fe42022-07-21 17:27:03 -07002002 i, entry.pointerProperties[i].id,
2003 ftl::enum_string(entry.pointerProperties[i].toolType).c_str(),
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002004 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
2005 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
2006 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
2007 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
2008 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
2009 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
2010 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
2011 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
2012 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
2013 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002014 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002015}
2016
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002017void InputDispatcher::dispatchEventLocked(nsecs_t currentTime,
2018 std::shared_ptr<EventEntry> eventEntry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002019 const std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002020 ATRACE_CALL();
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002021 if (DEBUG_DISPATCH_CYCLE) {
2022 ALOGD("dispatchEventToCurrentInputTargets");
2023 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002024
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00002025 processInteractionsLocked(*eventEntry, inputTargets);
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00002026
Michael Wrightd02c5b62014-02-10 15:10:22 -08002027 ALOG_ASSERT(eventEntry->dispatchInProgress); // should already have been set to true
2028
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002029 pokeUserActivityLocked(*eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002030
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002031 for (const InputTarget& inputTarget : inputTargets) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07002032 std::shared_ptr<Connection> connection =
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07002033 getConnectionLocked(inputTarget.inputChannel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07002034 if (connection != nullptr) {
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002035 prepareDispatchCycleLocked(currentTime, connection, eventEntry, inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002036 } else {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002037 if (DEBUG_FOCUS) {
2038 ALOGD("Dropping event delivery to target with channel '%s' because it "
2039 "is no longer registered with the input dispatcher.",
2040 inputTarget.inputChannel->getName().c_str());
2041 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002042 }
2043 }
2044}
2045
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07002046void InputDispatcher::cancelEventsForAnrLocked(const std::shared_ptr<Connection>& connection) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002047 // We will not be breaking any connections here, even if the policy wants us to abort dispatch.
2048 // If the policy decides to close the app, we will get a channel removal event via
2049 // unregisterInputChannel, and will clean up the connection that way. We are already not
2050 // sending new pointers to the connection when it blocked, but focused events will continue to
2051 // pile up.
2052 ALOGW("Canceling events for %s because it is unresponsive",
2053 connection->inputChannel->getName().c_str());
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08002054 if (connection->status == Connection::Status::NORMAL) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00002055 CancelationOptions options(CancelationOptions::Mode::CANCEL_ALL_EVENTS,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002056 "application not responding");
2057 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002058 }
2059}
2060
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002061void InputDispatcher::resetNoFocusedWindowTimeoutLocked() {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002062 if (DEBUG_FOCUS) {
2063 ALOGD("Resetting ANR timeouts.");
2064 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002065
2066 // Reset input target wait timeout.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002067 mNoFocusedWindowTimeoutTime = std::nullopt;
Chris Yea209fde2020-07-22 13:54:51 -07002068 mAwaitedFocusedApplication.reset();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002069}
2070
Tiger Huang721e26f2018-07-24 22:26:19 +08002071/**
2072 * Get the display id that the given event should go to. If this event specifies a valid display id,
2073 * then it should be dispatched to that display. Otherwise, the event goes to the focused display.
2074 * Focused display is the display that the user most recently interacted with.
2075 */
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002076int32_t InputDispatcher::getTargetDisplayId(const EventEntry& entry) {
Tiger Huang721e26f2018-07-24 22:26:19 +08002077 int32_t displayId;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002078 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002079 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002080 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
2081 displayId = keyEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002082 break;
2083 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002084 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002085 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
2086 displayId = motionEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002087 break;
2088 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00002089 case EventEntry::Type::TOUCH_MODE_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08002090 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002091 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002092 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07002093 case EventEntry::Type::DEVICE_RESET:
arthurhungb89ccb02020-12-30 16:19:01 +08002094 case EventEntry::Type::SENSOR:
2095 case EventEntry::Type::DRAG: {
Dominik Laskowski75788452021-02-09 18:51:25 -08002096 ALOGE("%s events do not have a target display", ftl::enum_string(entry.type).c_str());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002097 return ADISPLAY_ID_NONE;
2098 }
Tiger Huang721e26f2018-07-24 22:26:19 +08002099 }
2100 return displayId == ADISPLAY_ID_NONE ? mFocusedDisplayId : displayId;
2101}
2102
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002103bool InputDispatcher::shouldWaitToSendKeyLocked(nsecs_t currentTime,
2104 const char* focusedWindowName) {
2105 if (mAnrTracker.empty()) {
2106 // already processed all events that we waited for
2107 mKeyIsWaitingForEventsTimeout = std::nullopt;
2108 return false;
2109 }
2110
2111 if (!mKeyIsWaitingForEventsTimeout.has_value()) {
2112 // Start the timer
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00002113 // Wait to send key because there are unprocessed events that may cause focus to change
Siarhei Vishniakou70622952020-07-30 11:17:23 -05002114 mKeyIsWaitingForEventsTimeout = currentTime +
2115 std::chrono::duration_cast<std::chrono::nanoseconds>(KEY_WAITING_FOR_EVENTS_TIMEOUT)
2116 .count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002117 return true;
2118 }
2119
2120 // We still have pending events, and already started the timer
2121 if (currentTime < *mKeyIsWaitingForEventsTimeout) {
2122 return true; // Still waiting
2123 }
2124
2125 // Waited too long, and some connection still hasn't processed all motions
2126 // Just send the key to the focused window
2127 ALOGW("Dispatching key to %s even though there are other unprocessed events",
2128 focusedWindowName);
2129 mKeyIsWaitingForEventsTimeout = std::nullopt;
2130 return false;
2131}
2132
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002133sp<WindowInfoHandle> InputDispatcher::findFocusedWindowTargetLocked(
2134 nsecs_t currentTime, const EventEntry& entry, nsecs_t* nextWakeupTime,
2135 InputEventInjectionResult& outInjectionResult) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002136 std::string reason;
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002137 outInjectionResult = InputEventInjectionResult::FAILED; // Default result
Michael Wrightd02c5b62014-02-10 15:10:22 -08002138
Tiger Huang721e26f2018-07-24 22:26:19 +08002139 int32_t displayId = getTargetDisplayId(entry);
chaviw98318de2021-05-19 16:45:23 -05002140 sp<WindowInfoHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Chris Yea209fde2020-07-22 13:54:51 -07002141 std::shared_ptr<InputApplicationHandle> focusedApplicationHandle =
Tiger Huang721e26f2018-07-24 22:26:19 +08002142 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
2143
Michael Wrightd02c5b62014-02-10 15:10:22 -08002144 // If there is no currently focused window and no focused application
2145 // then drop the event.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002146 if (focusedWindowHandle == nullptr && focusedApplicationHandle == nullptr) {
2147 ALOGI("Dropping %s event because there is no focused window or focused application in "
2148 "display %" PRId32 ".",
Dominik Laskowski75788452021-02-09 18:51:25 -08002149 ftl::enum_string(entry.type).c_str(), displayId);
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002150 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002151 }
2152
Vishnu Nair062a8672021-09-03 16:07:44 -07002153 // Drop key events if requested by input feature
2154 if (focusedWindowHandle != nullptr && shouldDropInput(entry, focusedWindowHandle)) {
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002155 return nullptr;
Vishnu Nair062a8672021-09-03 16:07:44 -07002156 }
2157
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002158 // Compatibility behavior: raise ANR if there is a focused application, but no focused window.
2159 // Only start counting when we have a focused event to dispatch. The ANR is canceled if we
2160 // start interacting with another application via touch (app switch). This code can be removed
2161 // if the "no focused window ANR" is moved to the policy. Input doesn't know whether
2162 // an app is expected to have a focused window.
2163 if (focusedWindowHandle == nullptr && focusedApplicationHandle != nullptr) {
2164 if (!mNoFocusedWindowTimeoutTime.has_value()) {
2165 // We just discovered that there's no focused window. Start the ANR timer
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05002166 std::chrono::nanoseconds timeout = focusedApplicationHandle->getDispatchingTimeout(
2167 DEFAULT_INPUT_DISPATCHING_TIMEOUT);
2168 mNoFocusedWindowTimeoutTime = currentTime + timeout.count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002169 mAwaitedFocusedApplication = focusedApplicationHandle;
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05002170 mAwaitedApplicationDisplayId = displayId;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002171 ALOGW("Waiting because no window has focus but %s may eventually add a "
2172 "window when it finishes starting up. Will wait for %" PRId64 "ms",
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05002173 mAwaitedFocusedApplication->getName().c_str(), millis(timeout));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002174 *nextWakeupTime = *mNoFocusedWindowTimeoutTime;
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002175 outInjectionResult = InputEventInjectionResult::PENDING;
2176 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002177 } else if (currentTime > *mNoFocusedWindowTimeoutTime) {
2178 // Already raised ANR. Drop the event
2179 ALOGE("Dropping %s event because there is no focused window",
Dominik Laskowski75788452021-02-09 18:51:25 -08002180 ftl::enum_string(entry.type).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002181 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002182 } else {
2183 // Still waiting for the focused window
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002184 outInjectionResult = InputEventInjectionResult::PENDING;
2185 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002186 }
2187 }
2188
2189 // we have a valid, non-null focused window
2190 resetNoFocusedWindowTimeoutLocked();
2191
Prabir Pradhan5735a322022-04-11 17:23:34 +00002192 // Verify targeted injection.
2193 if (const auto err = verifyTargetedInjection(focusedWindowHandle, entry); err) {
2194 ALOGW("Dropping injected event: %s", (*err).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002195 outInjectionResult = InputEventInjectionResult::TARGET_MISMATCH;
2196 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002197 }
2198
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002199 if (focusedWindowHandle->getInfo()->inputConfig.test(
2200 WindowInfo::InputConfig::PAUSE_DISPATCHING)) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002201 ALOGI("Waiting because %s is paused", focusedWindowHandle->getName().c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002202 outInjectionResult = InputEventInjectionResult::PENDING;
2203 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002204 }
2205
2206 // If the event is a key event, then we must wait for all previous events to
2207 // complete before delivering it because previous events may have the
2208 // side-effect of transferring focus to a different window and we want to
2209 // ensure that the following keys are sent to the new window.
2210 //
2211 // Suppose the user touches a button in a window then immediately presses "A".
2212 // If the button causes a pop-up window to appear then we want to ensure that
2213 // the "A" key is delivered to the new pop-up window. This is because users
2214 // often anticipate pending UI changes when typing on a keyboard.
2215 // To obtain this behavior, we must serialize key events with respect to all
2216 // prior input events.
2217 if (entry.type == EventEntry::Type::KEY) {
2218 if (shouldWaitToSendKeyLocked(currentTime, focusedWindowHandle->getName().c_str())) {
2219 *nextWakeupTime = *mKeyIsWaitingForEventsTimeout;
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002220 outInjectionResult = InputEventInjectionResult::PENDING;
2221 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002222 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002223 }
2224
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002225 outInjectionResult = InputEventInjectionResult::SUCCEEDED;
2226 return focusedWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002227}
2228
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002229/**
2230 * Given a list of monitors, remove the ones we cannot find a connection for, and the ones
2231 * that are currently unresponsive.
2232 */
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002233std::vector<Monitor> InputDispatcher::selectResponsiveMonitorsLocked(
2234 const std::vector<Monitor>& monitors) const {
2235 std::vector<Monitor> responsiveMonitors;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002236 std::copy_if(monitors.begin(), monitors.end(), std::back_inserter(responsiveMonitors),
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002237 [this](const Monitor& monitor) REQUIRES(mLock) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07002238 std::shared_ptr<Connection> connection =
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002239 getConnectionLocked(monitor.inputChannel->getConnectionToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002240 if (connection == nullptr) {
2241 ALOGE("Could not find connection for monitor %s",
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002242 monitor.inputChannel->getName().c_str());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002243 return false;
2244 }
2245 if (!connection->responsive) {
2246 ALOGW("Unresponsive monitor %s will not get the new gesture",
2247 connection->inputChannel->getName().c_str());
2248 return false;
2249 }
2250 return true;
2251 });
2252 return responsiveMonitors;
2253}
2254
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002255std::vector<InputTarget> InputDispatcher::findTouchedWindowTargetsLocked(
Siarhei Vishniakou4fe57392022-10-25 13:44:30 -07002256 nsecs_t currentTime, const MotionEntry& entry, bool* outConflictingPointerActions,
2257 InputEventInjectionResult& outInjectionResult) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002258 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002259
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002260 std::vector<InputTarget> targets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002261 // For security reasons, we defer updating the touch state until we are sure that
2262 // event injection will be allowed.
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002263 const int32_t displayId = entry.displayId;
2264 const int32_t action = entry.action;
Siarhei Vishniakoubf880522023-05-01 11:03:22 -07002265 const int32_t maskedAction = MotionEvent::getActionMasked(action);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002266
2267 // Update the touch state as needed based on the properties of the touch event.
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002268 outInjectionResult = InputEventInjectionResult::PENDING;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002269
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002270 // Copy current touch state into tempTouchState.
2271 // This state will be used to update mTouchStatesByDisplay at the end of this function.
2272 // If no state for the specified display exists, then our initial state will be empty.
Yi Kong9b14ac62018-07-17 13:48:38 -07002273 const TouchState* oldState = nullptr;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002274 TouchState tempTouchState;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002275 if (const auto it = mTouchStatesByDisplay.find(displayId); it != mTouchStatesByDisplay.end()) {
2276 oldState = &(it->second);
Prabir Pradhane680f9b2022-02-04 04:24:00 -08002277 tempTouchState = *oldState;
Jeff Brownf086ddb2014-02-11 14:28:48 -08002278 }
2279
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07002280 bool isSplit = shouldSplitTouch(tempTouchState, entry);
Siarhei Vishniakou45504fe2023-05-05 16:05:10 -07002281 bool switchedDevice = false;
2282 if (oldState != nullptr) {
2283 std::set<int32_t> oldActiveDevices = oldState->getActiveDeviceIds();
2284 const bool anotherDeviceIsActive =
2285 oldActiveDevices.count(entry.deviceId) == 0 && !oldActiveDevices.empty();
2286 switchedDevice |= anotherDeviceIsActive;
Siarhei Vishniakou45504fe2023-05-05 16:05:10 -07002287 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002288
2289 const bool isHoverAction = (maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE ||
2290 maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2291 maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT);
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002292 // A DOWN could be generated from POINTER_DOWN if the initial pointers did not land into any
2293 // touchable windows.
2294 const bool wasDown = oldState != nullptr && oldState->isDown();
2295 const bool isDown = (maskedAction == AMOTION_EVENT_ACTION_DOWN) ||
2296 (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN && !wasDown);
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07002297 const bool newGesture = isDown || maskedAction == AMOTION_EVENT_ACTION_SCROLL ||
2298 maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2299 maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE;
Prabir Pradhanaa561d12021-09-24 06:57:33 -07002300 const bool isFromMouse = isFromSource(entry.source, AINPUT_SOURCE_MOUSE);
Siarhei Vishniakou5cee1e32022-11-29 12:35:39 -08002301
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002302 // If pointers are already down, let's finish the current gesture and ignore the new events
2303 // from another device. However, if the new event is a down event, let's cancel the current
2304 // touch and let the new one take over.
2305 if (switchedDevice && wasDown && !isDown) {
Siarhei Vishniakou45504fe2023-05-05 16:05:10 -07002306 LOG(INFO) << "Dropping event because a pointer for another device "
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002307 << " is already down in display " << displayId << ": " << entry.getDescription();
2308 // TODO(b/211379801): test multiple simultaneous input streams.
2309 outInjectionResult = InputEventInjectionResult::FAILED;
2310 return {}; // wrong device
2311 }
2312
Michael Wrightd02c5b62014-02-10 15:10:22 -08002313 if (newGesture) {
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002314 // If a new gesture is starting, clear the touch state completely.
2315 tempTouchState.reset();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002316 isSplit = false;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04002317 } else if (switchedDevice && maskedAction == AMOTION_EVENT_ACTION_MOVE) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07002318 ALOGI("Dropping move event because a pointer for a different device is already active "
2319 "in display %" PRId32,
2320 displayId);
Siarhei Vishniakou16e4fa02023-02-16 17:48:56 -08002321 // TODO(b/211379801): test multiple simultaneous input streams.
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002322 outInjectionResult = InputEventInjectionResult::FAILED;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002323 return {}; // wrong device
Michael Wrightd02c5b62014-02-10 15:10:22 -08002324 }
2325
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002326 if (isHoverAction) {
2327 // For hover actions, we will treat 'tempTouchState' as a new state, so let's erase
2328 // all of the existing hovering pointers and recompute.
2329 tempTouchState.clearHoveringPointers();
2330 }
2331
Michael Wrightd02c5b62014-02-10 15:10:22 -08002332 if (newGesture || (isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN)) {
2333 /* Case 1: New splittable pointer going down, or need target for hover or scroll. */
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07002334 const auto [x, y] = resolveTouchedPosition(entry);
Siarhei Vishniakou5b9766d2023-07-18 14:06:29 -07002335 const int32_t pointerIndex = MotionEvent::getActionIndex(action);
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002336 // Outside targets should be added upon first dispatched DOWN event. That means, this should
2337 // be a pointer that would generate ACTION_DOWN, *and* touch should not already be down.
Prabir Pradhand65552b2021-10-07 11:23:50 -07002338 const bool isStylus = isPointerFromStylus(entry, pointerIndex);
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07002339 sp<WindowInfoHandle> newTouchedWindowHandle =
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002340 findTouchedWindowAtLocked(displayId, x, y, isStylus);
Michael Wright3dd60e22019-03-27 22:06:44 +00002341
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002342 if (isDown) {
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07002343 targets += findOutsideTargetsLocked(displayId, newTouchedWindowHandle);
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002344 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002345 // Handle the case where we did not find a window.
Yi Kong9b14ac62018-07-17 13:48:38 -07002346 if (newTouchedWindowHandle == nullptr) {
Prabir Pradhan82e081e2022-12-06 09:50:09 +00002347 ALOGD("No new touched window at (%.1f, %.1f) in display %" PRId32, x, y, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002348 // Try to assign the pointer to the first foreground window we find, if there is one.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002349 newTouchedWindowHandle = tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002350 }
2351
Prabir Pradhan5735a322022-04-11 17:23:34 +00002352 // Verify targeted injection.
2353 if (const auto err = verifyTargetedInjection(newTouchedWindowHandle, entry); err) {
2354 ALOGW("Dropping injected touch event: %s", (*err).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002355 outInjectionResult = os::InputEventInjectionResult::TARGET_MISMATCH;
Prabir Pradhan5735a322022-04-11 17:23:34 +00002356 newTouchedWindowHandle = nullptr;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002357 return {};
Prabir Pradhan5735a322022-04-11 17:23:34 +00002358 }
2359
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002360 // Figure out whether splitting will be allowed for this window.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002361 if (newTouchedWindowHandle != nullptr) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002362 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
2363 // New window supports splitting, but we should never split mouse events.
2364 isSplit = !isFromMouse;
2365 } else if (isSplit) {
2366 // New window does not support splitting but we have already split events.
2367 // Ignore the new window.
Siarhei Vishniakou25537f82023-07-18 14:35:47 -07002368 LOG(INFO) << "Skipping " << newTouchedWindowHandle->getName()
2369 << " because it doesn't support split touch";
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002370 newTouchedWindowHandle = nullptr;
2371 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002372 } else {
2373 // No window is touched, so set split to true. This will allow the next pointer down to
Prabir Pradhan713bb3e2021-12-20 02:07:40 -08002374 // be delivered to a new window which supports split touch. Pointers from a mouse device
2375 // should never be split.
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07002376 isSplit = !isFromMouse;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002377 }
2378
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002379 std::vector<sp<WindowInfoHandle>> newTouchedWindows =
Prabir Pradhand65552b2021-10-07 11:23:50 -07002380 findTouchedSpyWindowsAtLocked(displayId, x, y, isStylus);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002381 if (newTouchedWindowHandle != nullptr) {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002382 // Process the foreground window first so that it is the first to receive the event.
2383 newTouchedWindows.insert(newTouchedWindows.begin(), newTouchedWindowHandle);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002384 }
2385
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002386 if (newTouchedWindows.empty()) {
Prabir Pradhan82e081e2022-12-06 09:50:09 +00002387 ALOGI("Dropping event because there is no touchable window at (%.1f, %.1f) on display "
2388 "%d.",
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002389 x, y, displayId);
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002390 outInjectionResult = InputEventInjectionResult::FAILED;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002391 return {};
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002392 }
2393
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002394 for (const sp<WindowInfoHandle>& windowHandle : newTouchedWindows) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07002395 if (!canWindowReceiveMotionLocked(windowHandle, entry)) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002396 continue;
2397 }
2398
Siarhei Vishniakoub681c202023-05-01 11:22:33 -07002399 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2400 maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE) {
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002401 const int32_t pointerId = entry.pointerProperties[0].id;
Siarhei Vishniakoub681c202023-05-01 11:22:33 -07002402 // The "windowHandle" is the target of this hovering pointer.
2403 tempTouchState.addHoveringPointerToWindow(windowHandle, entry.deviceId, pointerId);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002404 }
2405
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002406 // Set target flags.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002407 ftl::Flags<InputTarget::Flags> targetFlags = InputTarget::Flags::DISPATCH_AS_IS;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002408
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002409 if (canReceiveForegroundTouches(*windowHandle->getInfo())) {
2410 // There should only be one touched window that can be "foreground" for the pointer.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002411 targetFlags |= InputTarget::Flags::FOREGROUND;
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002412 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002413
2414 if (isSplit) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002415 targetFlags |= InputTarget::Flags::SPLIT;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002416 }
2417 if (isWindowObscuredAtPointLocked(windowHandle, x, y)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002418 targetFlags |= InputTarget::Flags::WINDOW_IS_OBSCURED;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002419 } else if (isWindowObscuredLocked(windowHandle)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002420 targetFlags |= InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002421 }
Michael Wright3dd60e22019-03-27 22:06:44 +00002422
2423 // Update the temporary touch state.
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08002424 std::bitset<MAX_POINTER_ID + 1> pointerIds;
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002425 if (!isHoverAction) {
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08002426 pointerIds.set(entry.pointerProperties[pointerIndex].id);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002427 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002428
Siarhei Vishniakoue0431e42023-01-28 17:01:39 -08002429 const bool isDownOrPointerDown = maskedAction == AMOTION_EVENT_ACTION_DOWN ||
2430 maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN;
2431
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002432 // TODO(b/211379801): Currently, even if pointerIds are empty (hover case), we would
2433 // still add a window to the touch state. We should avoid doing that, but some of the
2434 // later checks ("at least one foreground window") rely on this in order to dispatch
2435 // the event properly, so that needs to be updated, possibly by looking at InputTargets.
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002436 tempTouchState.addOrUpdateWindow(windowHandle, targetFlags, entry.deviceId, pointerIds,
Siarhei Vishniakoue0431e42023-01-28 17:01:39 -08002437 isDownOrPointerDown
2438 ? std::make_optional(entry.eventTime)
2439 : std::nullopt);
Arthur Hungc539dbb2022-12-08 07:45:36 +00002440
2441 // If this is the pointer going down and the touched window has a wallpaper
2442 // then also add the touched wallpaper windows so they are locked in for the duration
2443 // of the touch gesture.
2444 // We do not collect wallpapers during HOVER_MOVE or SCROLL because the wallpaper
2445 // engine only supports touch events. We would need to add a mechanism similar
2446 // to View.onGenericMotionEvent to enable wallpapers to handle these events.
Siarhei Vishniakoue0431e42023-01-28 17:01:39 -08002447 if (isDownOrPointerDown) {
Arthur Hungc539dbb2022-12-08 07:45:36 +00002448 if (targetFlags.test(InputTarget::Flags::FOREGROUND) &&
2449 windowHandle->getInfo()->inputConfig.test(
2450 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER)) {
2451 sp<WindowInfoHandle> wallpaper = findWallpaperWindowBelow(windowHandle);
2452 if (wallpaper != nullptr) {
2453 ftl::Flags<InputTarget::Flags> wallpaperFlags =
2454 InputTarget::Flags::WINDOW_IS_OBSCURED |
2455 InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED |
2456 InputTarget::Flags::DISPATCH_AS_IS;
2457 if (isSplit) {
2458 wallpaperFlags |= InputTarget::Flags::SPLIT;
2459 }
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002460 tempTouchState.addOrUpdateWindow(wallpaper, wallpaperFlags, entry.deviceId,
2461 pointerIds, entry.eventTime);
Arthur Hungc539dbb2022-12-08 07:45:36 +00002462 }
2463 }
2464 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002465 }
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00002466
Siarhei Vishniakou060f82b2023-01-27 06:39:14 -08002467 // If a window is already pilfering some pointers, give it this new pointer as well and
2468 // make it pilfering. This will prevent other non-spy windows from getting this pointer,
2469 // which is a specific behaviour that we want.
2470 const int32_t pointerId = entry.pointerProperties[pointerIndex].id;
2471 for (TouchedWindow& touchedWindow : tempTouchState.windows) {
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002472 if (touchedWindow.hasTouchingPointer(entry.deviceId, pointerId) &&
2473 touchedWindow.hasPilferingPointers(entry.deviceId)) {
Siarhei Vishniakou060f82b2023-01-27 06:39:14 -08002474 // This window is already pilfering some pointers, and this new pointer is also
2475 // going to it. Therefore, take over this pointer and don't give it to anyone
2476 // else.
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002477 touchedWindow.addPilferingPointer(entry.deviceId, pointerId);
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00002478 }
2479 }
Siarhei Vishniakou060f82b2023-01-27 06:39:14 -08002480
2481 // Restrict all pilfered pointers to the pilfering windows.
2482 tempTouchState.cancelPointersForNonPilferingWindows();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002483 } else {
2484 /* Case 2: Pointer move, up, cancel or non-splittable pointer down. */
2485
2486 // If the pointer is not currently down, then ignore the event.
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07002487 if (!tempTouchState.isDown() && maskedAction != AMOTION_EVENT_ACTION_HOVER_EXIT) {
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002488 LOG(INFO) << "Dropping event because the pointer is not down or we previously "
2489 "dropped the pointer down event in display "
2490 << displayId << ": " << entry.getDescription();
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002491 outInjectionResult = InputEventInjectionResult::FAILED;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002492 return {};
Michael Wrightd02c5b62014-02-10 15:10:22 -08002493 }
2494
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07002495 // If the pointer is not currently hovering, then ignore the event.
2496 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT) {
2497 const int32_t pointerId = entry.pointerProperties[0].id;
2498 if (oldState == nullptr ||
2499 oldState->getWindowsWithHoveringPointer(entry.deviceId, pointerId).empty()) {
2500 LOG(INFO) << "Dropping event because the hovering pointer is not in any windows in "
2501 "display "
2502 << displayId << ": " << entry.getDescription();
2503 outInjectionResult = InputEventInjectionResult::FAILED;
2504 return {};
2505 }
2506 tempTouchState.removeHoveringPointer(entry.deviceId, pointerId);
2507 }
2508
arthurhung6d4bed92021-03-17 11:59:33 +08002509 addDragEventLocked(entry);
arthurhungb89ccb02020-12-30 16:19:01 +08002510
Michael Wrightd02c5b62014-02-10 15:10:22 -08002511 // Check whether touches should slip outside of the current foreground window.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002512 if (maskedAction == AMOTION_EVENT_ACTION_MOVE && entry.pointerCount == 1 &&
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002513 tempTouchState.isSlippery()) {
Siarhei Vishniakou9306c382022-09-30 15:30:31 -07002514 const auto [x, y] = resolveTouchedPosition(entry);
Harry Cutts33476232023-01-30 19:57:29 +00002515 const bool isStylus = isPointerFromStylus(entry, /*pointerIndex=*/0);
chaviw98318de2021-05-19 16:45:23 -05002516 sp<WindowInfoHandle> oldTouchedWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002517 tempTouchState.getFirstForegroundWindowHandle();
Siarhei Vishniakou0f6558d2023-04-21 12:05:13 -07002518 LOG_ALWAYS_FATAL_IF(oldTouchedWindowHandle == nullptr);
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07002519 sp<WindowInfoHandle> newTouchedWindowHandle =
2520 findTouchedWindowAtLocked(displayId, x, y, isStylus);
Vishnu Nair062a8672021-09-03 16:07:44 -07002521
Prabir Pradhan5735a322022-04-11 17:23:34 +00002522 // Verify targeted injection.
2523 if (const auto err = verifyTargetedInjection(newTouchedWindowHandle, entry); err) {
2524 ALOGW("Dropping injected event: %s", (*err).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002525 outInjectionResult = os::InputEventInjectionResult::TARGET_MISMATCH;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002526 return {};
Prabir Pradhan5735a322022-04-11 17:23:34 +00002527 }
2528
Vishnu Nair062a8672021-09-03 16:07:44 -07002529 // Drop touch events if requested by input feature
2530 if (newTouchedWindowHandle != nullptr &&
2531 shouldDropInput(entry, newTouchedWindowHandle)) {
2532 newTouchedWindowHandle = nullptr;
2533 }
2534
Siarhei Vishniakouafa08cc2023-05-08 22:35:50 -07002535 if (newTouchedWindowHandle != nullptr &&
2536 !haveSameToken(oldTouchedWindowHandle, newTouchedWindowHandle)) {
Siarhei Vishniakou0f6558d2023-04-21 12:05:13 -07002537 ALOGD("Touch is slipping out of window %s into window %s in display %" PRId32,
2538 oldTouchedWindowHandle->getName().c_str(),
2539 newTouchedWindowHandle->getName().c_str(), displayId);
2540
Michael Wrightd02c5b62014-02-10 15:10:22 -08002541 // Make a slippery exit from the old window.
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08002542 std::bitset<MAX_POINTER_ID + 1> pointerIds;
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002543 const int32_t pointerId = entry.pointerProperties[0].id;
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08002544 pointerIds.set(pointerId);
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002545
2546 const TouchedWindow& touchedWindow =
2547 tempTouchState.getTouchedWindow(oldTouchedWindowHandle);
2548 addWindowTargetLocked(oldTouchedWindowHandle,
2549 InputTarget::Flags::DISPATCH_AS_SLIPPERY_EXIT, pointerIds,
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002550 touchedWindow.getDownTimeInTarget(entry.deviceId), targets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002551
2552 // Make a slippery entrance into the new window.
2553 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
Prabir Pradhan713bb3e2021-12-20 02:07:40 -08002554 isSplit = !isFromMouse;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002555 }
2556
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002557 ftl::Flags<InputTarget::Flags> targetFlags =
2558 InputTarget::Flags::DISPATCH_AS_SLIPPERY_ENTER;
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002559 if (canReceiveForegroundTouches(*newTouchedWindowHandle->getInfo())) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002560 targetFlags |= InputTarget::Flags::FOREGROUND;
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002561 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002562 if (isSplit) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002563 targetFlags |= InputTarget::Flags::SPLIT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002564 }
2565 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002566 targetFlags |= InputTarget::Flags::WINDOW_IS_OBSCURED;
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002567 } else if (isWindowObscuredLocked(newTouchedWindowHandle)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002568 targetFlags |= InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002569 }
2570
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002571 tempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags,
2572 entry.deviceId, pointerIds, entry.eventTime);
Arthur Hungc539dbb2022-12-08 07:45:36 +00002573
2574 // Check if the wallpaper window should deliver the corresponding event.
2575 slipWallpaperTouch(targetFlags, oldTouchedWindowHandle, newTouchedWindowHandle,
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002576 tempTouchState, entry.deviceId, pointerId, targets);
2577 tempTouchState.removeTouchingPointerFromWindow(entry.deviceId, pointerId,
2578 oldTouchedWindowHandle);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002579 }
2580 }
Arthur Hung96483742022-11-15 03:30:48 +00002581
2582 // Update the pointerIds for non-splittable when it received pointer down.
2583 if (!isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN) {
2584 // If no split, we suppose all touched windows should receive pointer down.
Siarhei Vishniakou5b9766d2023-07-18 14:06:29 -07002585 const int32_t pointerIndex = MotionEvent::getActionIndex(action);
Arthur Hung96483742022-11-15 03:30:48 +00002586 for (size_t i = 0; i < tempTouchState.windows.size(); i++) {
2587 TouchedWindow& touchedWindow = tempTouchState.windows[i];
2588 // Ignore drag window for it should just track one pointer.
2589 if (mDragState && mDragState->dragWindow == touchedWindow.windowHandle) {
2590 continue;
2591 }
Siarhei Vishniakou5b9766d2023-07-18 14:06:29 -07002592 std::bitset<MAX_POINTER_ID + 1> touchingPointers;
2593 touchingPointers.set(entry.pointerProperties[pointerIndex].id);
2594 touchedWindow.addTouchingPointers(entry.deviceId, touchingPointers);
Arthur Hung96483742022-11-15 03:30:48 +00002595 }
2596 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002597 }
2598
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002599 // Update dispatching for hover enter and exit.
Sam Dubeyf886dec2023-01-27 13:28:19 +00002600 {
2601 std::vector<TouchedWindow> hoveringWindows =
2602 getHoveringWindowsLocked(oldState, tempTouchState, entry);
2603 for (const TouchedWindow& touchedWindow : hoveringWindows) {
Siarhei Vishniakoud5876ba2023-05-15 17:58:34 -07002604 std::optional<InputTarget> target =
2605 createInputTargetLocked(touchedWindow.windowHandle, touchedWindow.targetFlags,
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002606 touchedWindow.getDownTimeInTarget(entry.deviceId));
Siarhei Vishniakoud5876ba2023-05-15 17:58:34 -07002607 if (!target) {
2608 continue;
2609 }
2610 // Hardcode to single hovering pointer for now.
2611 std::bitset<MAX_POINTER_ID + 1> pointerIds;
2612 pointerIds.set(entry.pointerProperties[0].id);
2613 target->addPointers(pointerIds, touchedWindow.windowHandle->getInfo()->transform);
2614 targets.push_back(*target);
Sam Dubeyf886dec2023-01-27 13:28:19 +00002615 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002616 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002617
Prabir Pradhan5735a322022-04-11 17:23:34 +00002618 // Ensure that all touched windows are valid for injection.
2619 if (entry.injectionState != nullptr) {
2620 std::string errs;
2621 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Prabir Pradhan5735a322022-04-11 17:23:34 +00002622 const auto err = verifyTargetedInjection(touchedWindow.windowHandle, entry);
2623 if (err) errs += "\n - " + *err;
2624 }
2625 if (!errs.empty()) {
2626 ALOGW("Dropping targeted injection: At least one touched window is not owned by uid "
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00002627 "%s:%s",
2628 entry.injectionState->targetUid->toString().c_str(), errs.c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002629 outInjectionResult = InputEventInjectionResult::TARGET_MISMATCH;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002630 return {};
Prabir Pradhan5735a322022-04-11 17:23:34 +00002631 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002632 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002633
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002634 // Check whether windows listening for outside touches are owned by the same UID. If the owner
2635 // has a different UID, then we will not reveal coordinate information to this window.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002636 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
chaviw98318de2021-05-19 16:45:23 -05002637 sp<WindowInfoHandle> foregroundWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002638 tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002639 if (foregroundWindowHandle) {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00002640 const auto foregroundWindowUid = foregroundWindowHandle->getInfo()->ownerUid;
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002641 for (InputTarget& target : targets) {
2642 if (target.flags.test(InputTarget::Flags::DISPATCH_AS_OUTSIDE)) {
2643 sp<WindowInfoHandle> targetWindow =
2644 getWindowHandleLocked(target.inputChannel->getConnectionToken());
2645 if (targetWindow->getInfo()->ownerUid != foregroundWindowUid) {
2646 target.flags |= InputTarget::Flags::ZERO_COORDS;
Michael Wright3dd60e22019-03-27 22:06:44 +00002647 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002648 }
2649 }
2650 }
2651 }
2652
Harry Cuttsb166c002023-05-09 13:06:05 +00002653 // If this is a touchpad navigation gesture, it needs to only be sent to trusted targets, as we
2654 // only want the system UI to handle these gestures.
2655 const bool isTouchpadNavGesture = isFromSource(entry.source, AINPUT_SOURCE_MOUSE) &&
2656 entry.classification == MotionClassification::MULTI_FINGER_SWIPE;
2657 if (isTouchpadNavGesture) {
2658 filterUntrustedTargets(/* byref */ tempTouchState, /* byref */ targets);
2659 }
2660
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07002661 // Output targets from the touch state.
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002662 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002663 if (!touchedWindow.hasTouchingPointers(entry.deviceId) &&
2664 !touchedWindow.hasHoveringPointers(entry.deviceId)) {
Siarhei Vishniakoue0431e42023-01-28 17:01:39 -08002665 // Windows with hovering pointers are getting persisted inside TouchState.
2666 // Do not send this event to those windows.
2667 continue;
2668 }
Harry Cuttsb166c002023-05-09 13:06:05 +00002669
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002670 addWindowTargetLocked(touchedWindow.windowHandle, touchedWindow.targetFlags,
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002671 touchedWindow.getTouchingPointers(entry.deviceId),
2672 touchedWindow.getDownTimeInTarget(entry.deviceId), targets);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002673 }
Sam Dubey39d37cf2022-12-07 18:05:35 +00002674
Siarhei Vishniakou580fb3a2023-05-05 15:02:20 -07002675 // During targeted injection, only allow owned targets to receive events
2676 std::erase_if(targets, [&](const InputTarget& target) {
2677 LOG_ALWAYS_FATAL_IF(target.windowHandle == nullptr);
2678 const auto err = verifyTargetedInjection(target.windowHandle, entry);
2679 if (err) {
2680 LOG(WARNING) << "Dropping injected event from " << target.windowHandle->getName()
2681 << ": " << (*err);
2682 return true;
2683 }
2684 return false;
2685 });
2686
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07002687 if (targets.empty()) {
2688 LOG(INFO) << "Dropping event because no targets were found: " << entry.getDescription();
2689 outInjectionResult = InputEventInjectionResult::FAILED;
2690 return {};
2691 }
2692
2693 // If we only have windows getting ACTION_OUTSIDE, then drop the event, because there is no
2694 // window that is actually receiving the entire gesture.
2695 if (std::all_of(targets.begin(), targets.end(), [](const InputTarget& target) {
2696 return target.flags.test(InputTarget::Flags::DISPATCH_AS_OUTSIDE);
2697 })) {
2698 LOG(INFO) << "Dropping event because all windows would just receive ACTION_OUTSIDE: "
2699 << entry.getDescription();
2700 outInjectionResult = InputEventInjectionResult::FAILED;
2701 return {};
2702 }
2703
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002704 outInjectionResult = InputEventInjectionResult::SUCCEEDED;
Sam Dubeyf886dec2023-01-27 13:28:19 +00002705 // Drop the outside or hover touch windows since we will not care about them
2706 // in the next iteration.
2707 tempTouchState.filterNonAsIsTouchWindows();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002708
Michael Wrightd02c5b62014-02-10 15:10:22 -08002709 // Update final pieces of touch state if the injector had permission.
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002710 if (switchedDevice) {
2711 if (DEBUG_FOCUS) {
2712 ALOGD("Conflicting pointer actions: Switched to a different device.");
2713 }
2714 *outConflictingPointerActions = true;
2715 }
2716
2717 if (isHoverAction) {
2718 // Started hovering, therefore no longer down.
Siarhei Vishniakou3ad385b2022-11-04 10:09:53 -07002719 if (oldState && oldState->isDown()) {
Siarhei Vishniakou6e1e9872022-11-08 17:51:35 -08002720 ALOGD_IF(DEBUG_FOCUS,
2721 "Conflicting pointer actions: Hover received while pointer was down.");
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002722 *outConflictingPointerActions = true;
2723 }
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002724 } else if (maskedAction == AMOTION_EVENT_ACTION_UP) {
2725 // Pointer went up.
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002726 tempTouchState.removeTouchingPointer(entry.deviceId, entry.pointerProperties[0].id);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002727 } else if (maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002728 // All pointers up or canceled.
2729 tempTouchState.reset();
2730 } else if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
2731 // First pointer went down.
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002732 if (oldState && (oldState->isDown() || oldState->hasHoveringPointers())) {
2733 ALOGD("Conflicting pointer actions: Down received while already down or hovering.");
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002734 *outConflictingPointerActions = true;
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002735 }
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002736 } else if (maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
2737 // One pointer went up.
Siarhei Vishniakou5b9766d2023-07-18 14:06:29 -07002738 const int32_t pointerIndex = MotionEvent::getActionIndex(action);
2739 const uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
2740 tempTouchState.removeTouchingPointer(entry.deviceId, pointerId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002741 }
2742
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002743 // Save changes unless the action was scroll in which case the temporary touch
2744 // state was only valid for this one action.
2745 if (maskedAction != AMOTION_EVENT_ACTION_SCROLL) {
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07002746 if (displayId >= 0) {
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002747 tempTouchState.clearWindowsWithoutPointers();
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002748 mTouchStatesByDisplay[displayId] = tempTouchState;
2749 } else {
2750 mTouchStatesByDisplay.erase(displayId);
2751 }
2752 }
2753
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -08002754 if (tempTouchState.windows.empty()) {
2755 mTouchStatesByDisplay.erase(displayId);
2756 }
2757
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002758 return targets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002759}
2760
arthurhung6d4bed92021-03-17 11:59:33 +08002761void InputDispatcher::finishDragAndDrop(int32_t displayId, float x, float y) {
Prabir Pradhand65552b2021-10-07 11:23:50 -07002762 // Prevent stylus interceptor windows from affecting drag and drop behavior for now, until we
2763 // have an explicit reason to support it.
2764 constexpr bool isStylus = false;
2765
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07002766 sp<WindowInfoHandle> dropWindow =
Harry Cutts33476232023-01-30 19:57:29 +00002767 findTouchedWindowAtLocked(displayId, x, y, isStylus, /*ignoreDragWindow=*/true);
arthurhung6d4bed92021-03-17 11:59:33 +08002768 if (dropWindow) {
2769 vec2 local = dropWindow->getInfo()->transform.transform(x, y);
Prabir Pradhancef936d2021-07-21 16:17:52 +00002770 sendDropWindowCommandLocked(dropWindow->getToken(), local.x, local.y);
Arthur Hung6d0571e2021-04-09 20:18:16 +08002771 } else {
Arthur Hung54745652022-04-20 07:17:41 +00002772 ALOGW("No window found when drop.");
Prabir Pradhancef936d2021-07-21 16:17:52 +00002773 sendDropWindowCommandLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08002774 }
2775 mDragState.reset();
2776}
2777
2778void InputDispatcher::addDragEventLocked(const MotionEntry& entry) {
Arthur Hung3915c1f2022-05-31 07:17:17 +00002779 if (!mDragState || mDragState->dragWindow->getInfo()->displayId != entry.displayId) {
arthurhungb89ccb02020-12-30 16:19:01 +08002780 return;
2781 }
2782
arthurhung6d4bed92021-03-17 11:59:33 +08002783 if (!mDragState->isStartDrag) {
2784 mDragState->isStartDrag = true;
2785 mDragState->isStylusButtonDownAtStart =
2786 (entry.buttonState & AMOTION_EVENT_BUTTON_STYLUS_PRIMARY) != 0;
2787 }
2788
Arthur Hung54745652022-04-20 07:17:41 +00002789 // Find the pointer index by id.
2790 int32_t pointerIndex = 0;
2791 for (; static_cast<uint32_t>(pointerIndex) < entry.pointerCount; pointerIndex++) {
2792 const PointerProperties& pointerProperties = entry.pointerProperties[pointerIndex];
2793 if (pointerProperties.id == mDragState->pointerId) {
2794 break;
arthurhung6d4bed92021-03-17 11:59:33 +08002795 }
Arthur Hung54745652022-04-20 07:17:41 +00002796 }
arthurhung6d4bed92021-03-17 11:59:33 +08002797
Arthur Hung54745652022-04-20 07:17:41 +00002798 if (uint32_t(pointerIndex) == entry.pointerCount) {
2799 LOG_ALWAYS_FATAL("Should find a valid pointer index by id %d", mDragState->pointerId);
Arthur Hung54745652022-04-20 07:17:41 +00002800 }
2801
2802 const int32_t maskedAction = entry.action & AMOTION_EVENT_ACTION_MASK;
2803 const int32_t x = entry.pointerCoords[pointerIndex].getX();
2804 const int32_t y = entry.pointerCoords[pointerIndex].getY();
2805
2806 switch (maskedAction) {
2807 case AMOTION_EVENT_ACTION_MOVE: {
2808 // Handle the special case : stylus button no longer pressed.
2809 bool isStylusButtonDown =
2810 (entry.buttonState & AMOTION_EVENT_BUTTON_STYLUS_PRIMARY) != 0;
2811 if (mDragState->isStylusButtonDownAtStart && !isStylusButtonDown) {
2812 finishDragAndDrop(entry.displayId, x, y);
2813 return;
2814 }
2815
2816 // Prevent stylus interceptor windows from affecting drag and drop behavior for now,
2817 // until we have an explicit reason to support it.
2818 constexpr bool isStylus = false;
2819
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07002820 sp<WindowInfoHandle> hoverWindowHandle =
2821 findTouchedWindowAtLocked(entry.displayId, x, y, isStylus,
2822 /*ignoreDragWindow=*/true);
Arthur Hung54745652022-04-20 07:17:41 +00002823 // enqueue drag exit if needed.
2824 if (hoverWindowHandle != mDragState->dragHoverWindowHandle &&
2825 !haveSameToken(hoverWindowHandle, mDragState->dragHoverWindowHandle)) {
2826 if (mDragState->dragHoverWindowHandle != nullptr) {
Harry Cutts33476232023-01-30 19:57:29 +00002827 enqueueDragEventLocked(mDragState->dragHoverWindowHandle, /*isExiting=*/true, x,
Arthur Hung54745652022-04-20 07:17:41 +00002828 y);
2829 }
2830 mDragState->dragHoverWindowHandle = hoverWindowHandle;
2831 }
2832 // enqueue drag location if needed.
2833 if (hoverWindowHandle != nullptr) {
Harry Cutts33476232023-01-30 19:57:29 +00002834 enqueueDragEventLocked(hoverWindowHandle, /*isExiting=*/false, x, y);
Arthur Hung54745652022-04-20 07:17:41 +00002835 }
2836 break;
2837 }
2838
2839 case AMOTION_EVENT_ACTION_POINTER_UP:
Siarhei Vishniakou5b9766d2023-07-18 14:06:29 -07002840 if (MotionEvent::getActionIndex(entry.action) != pointerIndex) {
Arthur Hung54745652022-04-20 07:17:41 +00002841 break;
2842 }
2843 // The drag pointer is up.
2844 [[fallthrough]];
2845 case AMOTION_EVENT_ACTION_UP:
2846 finishDragAndDrop(entry.displayId, x, y);
2847 break;
2848 case AMOTION_EVENT_ACTION_CANCEL: {
2849 ALOGD("Receiving cancel when drag and drop.");
2850 sendDropWindowCommandLocked(nullptr, 0, 0);
2851 mDragState.reset();
2852 break;
2853 }
arthurhungb89ccb02020-12-30 16:19:01 +08002854 }
2855}
2856
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002857std::optional<InputTarget> InputDispatcher::createInputTargetLocked(
2858 const sp<android::gui::WindowInfoHandle>& windowHandle,
2859 ftl::Flags<InputTarget::Flags> targetFlags,
2860 std::optional<nsecs_t> firstDownTimeInTarget) const {
2861 std::shared_ptr<InputChannel> inputChannel = getInputChannelLocked(windowHandle->getToken());
2862 if (inputChannel == nullptr) {
2863 ALOGW("Not creating InputTarget for %s, no input channel", windowHandle->getName().c_str());
2864 return {};
2865 }
2866 InputTarget inputTarget;
2867 inputTarget.inputChannel = inputChannel;
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00002868 inputTarget.windowHandle = windowHandle;
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002869 inputTarget.flags = targetFlags;
2870 inputTarget.globalScaleFactor = windowHandle->getInfo()->globalScaleFactor;
2871 inputTarget.firstDownTimeInTarget = firstDownTimeInTarget;
2872 const auto& displayInfoIt = mDisplayInfos.find(windowHandle->getInfo()->displayId);
2873 if (displayInfoIt != mDisplayInfos.end()) {
2874 inputTarget.displayTransform = displayInfoIt->second.transform;
2875 } else {
Siarhei Vishniakou580fb3a2023-05-05 15:02:20 -07002876 // DisplayInfo not found for this window on display windowHandle->getInfo()->displayId.
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002877 // TODO(b/198444055): Make this an error message after 'setInputWindows' API is removed.
2878 }
2879 return inputTarget;
2880}
2881
chaviw98318de2021-05-19 16:45:23 -05002882void InputDispatcher::addWindowTargetLocked(const sp<WindowInfoHandle>& windowHandle,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002883 ftl::Flags<InputTarget::Flags> targetFlags,
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08002884 std::bitset<MAX_POINTER_ID + 1> pointerIds,
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002885 std::optional<nsecs_t> firstDownTimeInTarget,
Siarhei Vishniakouf75cddb2022-10-25 10:42:16 -07002886 std::vector<InputTarget>& inputTargets) const {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002887 std::vector<InputTarget>::iterator it =
2888 std::find_if(inputTargets.begin(), inputTargets.end(),
2889 [&windowHandle](const InputTarget& inputTarget) {
2890 return inputTarget.inputChannel->getConnectionToken() ==
2891 windowHandle->getToken();
2892 });
Chavi Weingarten97b8eec2020-01-09 18:09:08 +00002893
chaviw98318de2021-05-19 16:45:23 -05002894 const WindowInfo* windowInfo = windowHandle->getInfo();
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002895
2896 if (it == inputTargets.end()) {
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002897 std::optional<InputTarget> target =
2898 createInputTargetLocked(windowHandle, targetFlags, firstDownTimeInTarget);
2899 if (!target) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002900 return;
2901 }
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002902 inputTargets.push_back(*target);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002903 it = inputTargets.end() - 1;
2904 }
2905
2906 ALOG_ASSERT(it->flags == targetFlags);
2907 ALOG_ASSERT(it->globalScaleFactor == windowInfo->globalScaleFactor);
2908
chaviw1ff3d1e2020-07-01 15:53:47 -07002909 it->addPointers(pointerIds, windowInfo->transform);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002910}
2911
Michael Wright3dd60e22019-03-27 22:06:44 +00002912void InputDispatcher::addGlobalMonitoringTargetsLocked(std::vector<InputTarget>& inputTargets,
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002913 int32_t displayId) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002914 auto monitorsIt = mGlobalMonitorsByDisplay.find(displayId);
2915 if (monitorsIt == mGlobalMonitorsByDisplay.end()) return;
Michael Wright3dd60e22019-03-27 22:06:44 +00002916
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002917 for (const Monitor& monitor : selectResponsiveMonitorsLocked(monitorsIt->second)) {
2918 InputTarget target;
2919 target.inputChannel = monitor.inputChannel;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002920 target.flags = InputTarget::Flags::DISPATCH_AS_IS;
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002921 // target.firstDownTimeInTarget is not set for global monitors. It is only required in split
2922 // touch and global monitoring works as intended even without setting firstDownTimeInTarget
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002923 if (const auto& it = mDisplayInfos.find(displayId); it != mDisplayInfos.end()) {
2924 target.displayTransform = it->second.transform;
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002925 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002926 target.setDefaultPointerTransform(target.displayTransform);
2927 inputTargets.push_back(target);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002928 }
2929}
2930
Robert Carrc9bf1d32020-04-13 17:21:08 -07002931/**
2932 * Indicate whether one window handle should be considered as obscuring
2933 * another window handle. We only check a few preconditions. Actually
2934 * checking the bounds is left to the caller.
2935 */
chaviw98318de2021-05-19 16:45:23 -05002936static bool canBeObscuredBy(const sp<WindowInfoHandle>& windowHandle,
2937 const sp<WindowInfoHandle>& otherHandle) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002938 // Compare by token so cloned layers aren't counted
2939 if (haveSameToken(windowHandle, otherHandle)) {
2940 return false;
2941 }
2942 auto info = windowHandle->getInfo();
2943 auto otherInfo = otherHandle->getInfo();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002944 if (otherInfo->inputConfig.test(WindowInfo::InputConfig::NOT_VISIBLE)) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002945 return false;
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002946 } else if (otherInfo->alpha == 0 &&
2947 otherInfo->inputConfig.test(WindowInfo::InputConfig::NOT_TOUCHABLE)) {
Bernardo Rufino653d2e02020-10-20 17:32:40 +00002948 // Those act as if they were invisible, so we don't need to flag them.
2949 // We do want to potentially flag touchable windows even if they have 0
2950 // opacity, since they can consume touches and alter the effects of the
2951 // user interaction (eg. apps that rely on
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002952 // Flags::WINDOW_IS_PARTIALLY_OBSCURED should still be told about those
Bernardo Rufino653d2e02020-10-20 17:32:40 +00002953 // windows), hence we also check for FLAG_NOT_TOUCHABLE.
2954 return false;
Bernardo Rufino8007daf2020-09-22 09:40:01 +00002955 } else if (info->ownerUid == otherInfo->ownerUid) {
2956 // If ownerUid is the same we don't generate occlusion events as there
2957 // is no security boundary within an uid.
Robert Carrc9bf1d32020-04-13 17:21:08 -07002958 return false;
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002959 } else if (otherInfo->inputConfig.test(gui::WindowInfo::InputConfig::TRUSTED_OVERLAY)) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002960 return false;
2961 } else if (otherInfo->displayId != info->displayId) {
2962 return false;
2963 }
2964 return true;
2965}
2966
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002967/**
2968 * Returns touch occlusion information in the form of TouchOcclusionInfo. To check if the touch is
2969 * untrusted, one should check:
2970 *
2971 * 1. If result.hasBlockingOcclusion is true.
2972 * If it's, it means the touch should be blocked due to a window with occlusion mode of
2973 * BLOCK_UNTRUSTED.
2974 *
2975 * 2. If result.obscuringOpacity > mMaximumObscuringOpacityForTouch.
2976 * If it is (and 1 is false), then the touch should be blocked because a stack of windows
2977 * (possibly only one) with occlusion mode of USE_OPACITY from one UID resulted in a composed
2978 * obscuring opacity above the threshold. Note that if there was no window of occlusion mode
2979 * USE_OPACITY, result.obscuringOpacity would've been 0 and since
2980 * mMaximumObscuringOpacityForTouch >= 0, the condition above would never be true.
2981 *
2982 * If neither of those is true, then it means the touch can be allowed.
2983 */
2984InputDispatcher::TouchOcclusionInfo InputDispatcher::computeTouchOcclusionInfoLocked(
chaviw98318de2021-05-19 16:45:23 -05002985 const sp<WindowInfoHandle>& windowHandle, int32_t x, int32_t y) const {
2986 const WindowInfo* windowInfo = windowHandle->getInfo();
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002987 int32_t displayId = windowInfo->displayId;
chaviw98318de2021-05-19 16:45:23 -05002988 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002989 TouchOcclusionInfo info;
2990 info.hasBlockingOcclusion = false;
2991 info.obscuringOpacity = 0;
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00002992 info.obscuringUid = gui::Uid::INVALID;
2993 std::map<gui::Uid, float> opacityByUid;
chaviw98318de2021-05-19 16:45:23 -05002994 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002995 if (windowHandle == otherHandle) {
2996 break; // All future windows are below us. Exit early.
2997 }
chaviw98318de2021-05-19 16:45:23 -05002998 const WindowInfo* otherInfo = otherHandle->getInfo();
Bernardo Rufino1ff9d592021-01-18 16:58:57 +00002999 if (canBeObscuredBy(windowHandle, otherHandle) && otherInfo->frameContainsPoint(x, y) &&
3000 !haveSameApplicationToken(windowInfo, otherInfo)) {
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00003001 if (DEBUG_TOUCH_OCCLUSION) {
3002 info.debugInfo.push_back(
Harry Cutts101ee9b2023-07-06 18:04:14 +00003003 dumpWindowForTouchOcclusion(otherInfo, /*isTouchedWindow=*/false));
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00003004 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003005 // canBeObscuredBy() has returned true above, which means this window is untrusted, so
3006 // we perform the checks below to see if the touch can be propagated or not based on the
3007 // window's touch occlusion mode
3008 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::BLOCK_UNTRUSTED) {
3009 info.hasBlockingOcclusion = true;
3010 info.obscuringUid = otherInfo->ownerUid;
3011 info.obscuringPackage = otherInfo->packageName;
3012 break;
3013 }
3014 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::USE_OPACITY) {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003015 const auto uid = otherInfo->ownerUid;
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003016 float opacity =
3017 (opacityByUid.find(uid) == opacityByUid.end()) ? 0 : opacityByUid[uid];
3018 // Given windows A and B:
3019 // opacity(A, B) = 1 - [1 - opacity(A)] * [1 - opacity(B)]
3020 opacity = 1 - (1 - opacity) * (1 - otherInfo->alpha);
3021 opacityByUid[uid] = opacity;
3022 if (opacity > info.obscuringOpacity) {
3023 info.obscuringOpacity = opacity;
3024 info.obscuringUid = uid;
3025 info.obscuringPackage = otherInfo->packageName;
3026 }
3027 }
3028 }
3029 }
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00003030 if (DEBUG_TOUCH_OCCLUSION) {
Harry Cutts101ee9b2023-07-06 18:04:14 +00003031 info.debugInfo.push_back(dumpWindowForTouchOcclusion(windowInfo, /*isTouchedWindow=*/true));
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00003032 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003033 return info;
3034}
3035
chaviw98318de2021-05-19 16:45:23 -05003036std::string InputDispatcher::dumpWindowForTouchOcclusion(const WindowInfo* info,
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00003037 bool isTouchedWindow) const {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003038 return StringPrintf(INDENT2 "* %spackage=%s/%s, id=%" PRId32 ", mode=%s, alpha=%.2f, "
Prabir Pradhan51e7db02022-02-07 06:02:57 -08003039 "frame=[%" PRId32 ",%" PRId32 "][%" PRId32 ",%" PRId32
3040 "], touchableRegion=%s, window={%s}, inputConfig={%s}, "
3041 "hasToken=%s, applicationInfo.name=%s, applicationInfo.token=%s\n",
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08003042 isTouchedWindow ? "[TOUCHED] " : "", info->packageName.c_str(),
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003043 info->ownerUid.toString().c_str(), info->id,
Chavi Weingarten7f019192023-08-08 20:39:01 +00003044 toString(info->touchOcclusionMode).c_str(), info->alpha, info->frame.left,
3045 info->frame.top, info->frame.right, info->frame.bottom,
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003046 dumpRegion(info->touchableRegion).c_str(), info->name.c_str(),
3047 info->inputConfig.string().c_str(), toString(info->token != nullptr),
3048 info->applicationInfo.name.c_str(),
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07003049 binderToString(info->applicationInfo.token).c_str());
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00003050}
3051
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003052bool InputDispatcher::isTouchTrustedLocked(const TouchOcclusionInfo& occlusionInfo) const {
3053 if (occlusionInfo.hasBlockingOcclusion) {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003054 ALOGW("Untrusted touch due to occlusion by %s/%s", occlusionInfo.obscuringPackage.c_str(),
3055 occlusionInfo.obscuringUid.toString().c_str());
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003056 return false;
3057 }
3058 if (occlusionInfo.obscuringOpacity > mMaximumObscuringOpacityForTouch) {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003059 ALOGW("Untrusted touch due to occlusion by %s/%s (obscuring opacity = "
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003060 "%.2f, maximum allowed = %.2f)",
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003061 occlusionInfo.obscuringPackage.c_str(), occlusionInfo.obscuringUid.toString().c_str(),
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003062 occlusionInfo.obscuringOpacity, mMaximumObscuringOpacityForTouch);
3063 return false;
3064 }
3065 return true;
3066}
3067
chaviw98318de2021-05-19 16:45:23 -05003068bool InputDispatcher::isWindowObscuredAtPointLocked(const sp<WindowInfoHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003069 int32_t x, int32_t y) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003070 int32_t displayId = windowHandle->getInfo()->displayId;
chaviw98318de2021-05-19 16:45:23 -05003071 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
3072 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07003073 if (windowHandle == otherHandle) {
3074 break; // All future windows are below us. Exit early.
Michael Wrightd02c5b62014-02-10 15:10:22 -08003075 }
chaviw98318de2021-05-19 16:45:23 -05003076 const WindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07003077 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08003078 otherInfo->frameContainsPoint(x, y)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003079 return true;
3080 }
3081 }
3082 return false;
3083}
3084
chaviw98318de2021-05-19 16:45:23 -05003085bool InputDispatcher::isWindowObscuredLocked(const sp<WindowInfoHandle>& windowHandle) const {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07003086 int32_t displayId = windowHandle->getInfo()->displayId;
chaviw98318de2021-05-19 16:45:23 -05003087 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
3088 const WindowInfo* windowInfo = windowHandle->getInfo();
3089 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07003090 if (windowHandle == otherHandle) {
3091 break; // All future windows are below us. Exit early.
Michael Wrightcdcd8f22016-03-22 16:52:13 -07003092 }
chaviw98318de2021-05-19 16:45:23 -05003093 const WindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07003094 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08003095 otherInfo->overlaps(windowInfo)) {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07003096 return true;
3097 }
3098 }
3099 return false;
3100}
3101
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08003102std::string InputDispatcher::getApplicationWindowLabel(
chaviw98318de2021-05-19 16:45:23 -05003103 const InputApplicationHandle* applicationHandle, const sp<WindowInfoHandle>& windowHandle) {
Yi Kong9b14ac62018-07-17 13:48:38 -07003104 if (applicationHandle != nullptr) {
3105 if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07003106 return applicationHandle->getName() + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003107 } else {
3108 return applicationHandle->getName();
3109 }
Yi Kong9b14ac62018-07-17 13:48:38 -07003110 } else if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07003111 return windowHandle->getInfo()->applicationInfo.name + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003112 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003113 return "<unknown application or window>";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003114 }
3115}
3116
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003117void InputDispatcher::pokeUserActivityLocked(const EventEntry& eventEntry) {
Antonio Kantekf16f2832021-09-28 04:39:20 +00003118 if (!isUserActivityEvent(eventEntry)) {
3119 // Not poking user activity if the event type does not represent a user activity
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003120 return;
3121 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003122 int32_t displayId = getTargetDisplayId(eventEntry);
chaviw98318de2021-05-19 16:45:23 -05003123 sp<WindowInfoHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Josep del Riob3981622023-04-18 15:49:45 +00003124 const WindowInfo* windowDisablingUserActivityInfo = nullptr;
Tiger Huang721e26f2018-07-24 22:26:19 +08003125 if (focusedWindowHandle != nullptr) {
chaviw98318de2021-05-19 16:45:23 -05003126 const WindowInfo* info = focusedWindowHandle->getInfo();
Prabir Pradhan51e7db02022-02-07 06:02:57 -08003127 if (info->inputConfig.test(WindowInfo::InputConfig::DISABLE_USER_ACTIVITY)) {
Josep del Riob3981622023-04-18 15:49:45 +00003128 windowDisablingUserActivityInfo = info;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003129 }
3130 }
3131
3132 int32_t eventType = USER_ACTIVITY_EVENT_OTHER;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003133 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003134 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003135 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
3136 if (motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003137 return;
3138 }
Josep del Riob3981622023-04-18 15:49:45 +00003139 if (windowDisablingUserActivityInfo != nullptr) {
3140 if (DEBUG_DISPATCH_CYCLE) {
3141 ALOGD("Not poking user activity: disabled by window '%s'.",
3142 windowDisablingUserActivityInfo->name.c_str());
3143 }
3144 return;
3145 }
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003146 if (MotionEvent::isTouchEvent(motionEntry.source, motionEntry.action)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003147 eventType = USER_ACTIVITY_EVENT_TOUCH;
3148 }
3149 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003150 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003151 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003152 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
3153 if (keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003154 return;
3155 }
Josep del Riob3981622023-04-18 15:49:45 +00003156 // If the key code is unknown, we don't consider it user activity
3157 if (keyEntry.keyCode == AKEYCODE_UNKNOWN) {
3158 return;
3159 }
3160 // Don't inhibit events that were intercepted or are not passed to
3161 // the apps, like system shortcuts
3162 if (windowDisablingUserActivityInfo != nullptr &&
3163 keyEntry.interceptKeyResult != KeyEntry::InterceptKeyResult::SKIP &&
3164 keyEntry.policyFlags & POLICY_FLAG_PASS_TO_USER) {
3165 if (DEBUG_DISPATCH_CYCLE) {
3166 ALOGD("Not poking user activity: disabled by window '%s'.",
3167 windowDisablingUserActivityInfo->name.c_str());
3168 }
3169 return;
3170 }
3171
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003172 eventType = USER_ACTIVITY_EVENT_BUTTON;
3173 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003174 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00003175 default: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003176 LOG_ALWAYS_FATAL("%s events are not user activity",
Dominik Laskowski75788452021-02-09 18:51:25 -08003177 ftl::enum_string(eventEntry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003178 break;
3179 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003180 }
3181
Prabir Pradhancef936d2021-07-21 16:17:52 +00003182 auto command = [this, eventTime = eventEntry.eventTime, eventType, displayId]()
3183 REQUIRES(mLock) {
3184 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00003185 mPolicy.pokeUserActivity(eventTime, eventType, displayId);
Prabir Pradhancef936d2021-07-21 16:17:52 +00003186 };
3187 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003188}
3189
3190void InputDispatcher::prepareDispatchCycleLocked(nsecs_t currentTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003191 const std::shared_ptr<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003192 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003193 const InputTarget& inputTarget) {
Prabir Pradhan2dac8b82023-09-06 01:11:51 +00003194 ATRACE_NAME_IF(ATRACE_ENABLED(),
3195 StringPrintf("prepareDispatchCycleLocked(inputChannel=%s, id=0x%" PRIx32 ")",
3196 connection->getInputChannelName().c_str(), eventEntry->id));
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003197 if (DEBUG_DISPATCH_CYCLE) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003198 ALOGD("channel '%s' ~ prepareDispatchCycle - flags=%s, "
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08003199 "globalScaleFactor=%f, pointerIds=%s %s",
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003200 connection->getInputChannelName().c_str(), inputTarget.flags.string().c_str(),
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08003201 inputTarget.globalScaleFactor, bitsetToString(inputTarget.pointerIds).c_str(),
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003202 inputTarget.getPointerInfoString().c_str());
3203 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003204
3205 // Skip this event if the connection status is not normal.
3206 // We don't want to enqueue additional outbound events if the connection is broken.
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003207 if (connection->status != Connection::Status::NORMAL) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003208 if (DEBUG_DISPATCH_CYCLE) {
3209 ALOGD("channel '%s' ~ Dropping event because the channel status is %s",
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003210 connection->getInputChannelName().c_str(),
3211 ftl::enum_string(connection->status).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003212 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003213 return;
3214 }
3215
3216 // Split a motion event if needed.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003217 if (inputTarget.flags.test(InputTarget::Flags::SPLIT)) {
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003218 LOG_ALWAYS_FATAL_IF(eventEntry->type != EventEntry::Type::MOTION,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003219 "Entry type %s should not have Flags::SPLIT",
Dominik Laskowski75788452021-02-09 18:51:25 -08003220 ftl::enum_string(eventEntry->type).c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003221
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003222 const MotionEntry& originalMotionEntry = static_cast<const MotionEntry&>(*eventEntry);
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003223 if (inputTarget.pointerIds.count() != originalMotionEntry.pointerCount) {
Siarhei Vishniakou16e4fa02023-02-16 17:48:56 -08003224 if (!inputTarget.firstDownTimeInTarget.has_value()) {
3225 logDispatchStateLocked();
3226 LOG(FATAL) << "Splitting motion events requires a down time to be set for the "
3227 "target on connection "
3228 << connection->getInputChannelName() << " for "
3229 << originalMotionEntry.getDescription();
3230 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003231 std::unique_ptr<MotionEntry> splitMotionEntry =
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00003232 splitMotionEvent(originalMotionEntry, inputTarget.pointerIds,
3233 inputTarget.firstDownTimeInTarget.value());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003234 if (!splitMotionEntry) {
3235 return; // split event was dropped
3236 }
Arthur Hungb3307ee2021-10-14 10:57:37 +00003237 if (splitMotionEntry->action == AMOTION_EVENT_ACTION_CANCEL) {
3238 std::string reason = std::string("reason=pointer cancel on split window");
3239 android_log_event_list(LOGTAG_INPUT_CANCEL)
3240 << connection->getInputChannelName().c_str() << reason << LOG_ID_EVENTS;
3241 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003242 if (DEBUG_FOCUS) {
3243 ALOGD("channel '%s' ~ Split motion event.",
3244 connection->getInputChannelName().c_str());
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003245 logOutboundMotionDetails(" ", *splitMotionEntry);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003246 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003247 enqueueDispatchEntriesLocked(currentTime, connection, std::move(splitMotionEntry),
3248 inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003249 return;
3250 }
3251 }
3252
3253 // Not splitting. Enqueue dispatch entries for the event as is.
3254 enqueueDispatchEntriesLocked(currentTime, connection, eventEntry, inputTarget);
3255}
3256
3257void InputDispatcher::enqueueDispatchEntriesLocked(nsecs_t currentTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003258 const std::shared_ptr<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003259 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003260 const InputTarget& inputTarget) {
Prabir Pradhan2dac8b82023-09-06 01:11:51 +00003261 ATRACE_NAME_IF(ATRACE_ENABLED(),
3262 StringPrintf("enqueueDispatchEntriesLocked(inputChannel=%s, id=0x%" PRIx32 ")",
3263 connection->getInputChannelName().c_str(), eventEntry->id));
Siarhei Vishniakou5cee1e32022-11-29 12:35:39 -08003264 LOG_ALWAYS_FATAL_IF(!inputTarget.flags.any(InputTarget::DISPATCH_MASK),
3265 "No dispatch flags are set for %s", eventEntry->getDescription().c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00003266
hongzuo liu95785e22022-09-06 02:51:35 +00003267 const bool wasEmpty = connection->outboundQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003268
3269 // Enqueue dispatch entries for the requested modes.
chaviw8c9cf542019-03-25 13:02:48 -07003270 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003271 InputTarget::Flags::DISPATCH_AS_HOVER_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07003272 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003273 InputTarget::Flags::DISPATCH_AS_OUTSIDE);
chaviw8c9cf542019-03-25 13:02:48 -07003274 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003275 InputTarget::Flags::DISPATCH_AS_HOVER_ENTER);
chaviw8c9cf542019-03-25 13:02:48 -07003276 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003277 InputTarget::Flags::DISPATCH_AS_IS);
chaviw8c9cf542019-03-25 13:02:48 -07003278 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003279 InputTarget::Flags::DISPATCH_AS_SLIPPERY_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07003280 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003281 InputTarget::Flags::DISPATCH_AS_SLIPPERY_ENTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003282
3283 // If the outbound queue was previously empty, start the dispatch cycle going.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003284 if (wasEmpty && !connection->outboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003285 startDispatchCycleLocked(currentTime, connection);
3286 }
3287}
3288
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003289void InputDispatcher::enqueueDispatchEntryLocked(const std::shared_ptr<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003290 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003291 const InputTarget& inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003292 ftl::Flags<InputTarget::Flags> dispatchMode) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003293 ftl::Flags<InputTarget::Flags> inputTargetFlags = inputTarget.flags;
3294 if (!inputTargetFlags.any(dispatchMode)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003295 return;
3296 }
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003297
3298 inputTargetFlags.clear(InputTarget::DISPATCH_MASK);
3299 inputTargetFlags |= dispatchMode;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003300
3301 // This is a new event.
3302 // Enqueue a new dispatch entry onto the outbound queue for this connection.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003303 std::unique_ptr<DispatchEntry> dispatchEntry =
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003304 createDispatchEntry(inputTarget, eventEntry, inputTargetFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003305
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003306 // Use the eventEntry from dispatchEntry since the entry may have changed and can now be a
3307 // different EventEntry than what was passed in.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003308 EventEntry& newEntry = *(dispatchEntry->eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003309 // Apply target flags and update the connection's input state.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003310 switch (newEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003311 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003312 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(newEntry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003313 if (!connection->inputState.trackKey(keyEntry, dispatchEntry->resolvedAction,
3314 dispatchEntry->resolvedFlags)) {
Siarhei Vishniakouc94dafe2023-05-26 10:24:19 -07003315 LOG(WARNING) << "channel " << connection->getInputChannelName()
3316 << "~ dropping inconsistent event: " << *dispatchEntry;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003317 return; // skip the inconsistent event
3318 }
3319 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003320 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003321
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003322 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003323 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003324 // Assign a default value to dispatchEntry that will never be generated by InputReader,
3325 // and assign a InputDispatcher value if it doesn't change in the if-else chain below.
3326 constexpr int32_t DEFAULT_RESOLVED_EVENT_ID =
3327 static_cast<int32_t>(IdGenerator::Source::OTHER);
3328 dispatchEntry->resolvedEventId = DEFAULT_RESOLVED_EVENT_ID;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003329 if (dispatchMode.test(InputTarget::Flags::DISPATCH_AS_OUTSIDE)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003330 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_OUTSIDE;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003331 } else if (dispatchMode.test(InputTarget::Flags::DISPATCH_AS_HOVER_EXIT)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003332 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_EXIT;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003333 } else if (dispatchMode.test(InputTarget::Flags::DISPATCH_AS_HOVER_ENTER)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003334 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003335 } else if (dispatchMode.test(InputTarget::Flags::DISPATCH_AS_SLIPPERY_EXIT)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003336 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_CANCEL;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003337 } else if (dispatchMode.test(InputTarget::Flags::DISPATCH_AS_SLIPPERY_ENTER)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003338 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_DOWN;
3339 } else {
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003340 dispatchEntry->resolvedEventId = motionEntry.id;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003341 }
3342 if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_HOVER_MOVE &&
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003343 !connection->inputState.isHovering(motionEntry.deviceId, motionEntry.source,
3344 motionEntry.displayId)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003345 if (DEBUG_DISPATCH_CYCLE) {
3346 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: filling in missing hover "
3347 "enter event",
3348 connection->getInputChannelName().c_str());
3349 }
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00003350 // We keep the 'resolvedEventId' here equal to the original 'motionEntry.id' because
3351 // this is a one-to-one event conversion.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003352 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
3353 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003354
Siarhei Vishniakou1ae72f12023-01-29 12:55:30 -08003355 if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_CANCEL) {
3356 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_CANCELED;
3357 }
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003358 if (dispatchEntry->targetFlags.test(InputTarget::Flags::WINDOW_IS_OBSCURED)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003359 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED;
3360 }
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003361 if (dispatchEntry->targetFlags.test(InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003362 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
3363 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003364
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003365 if (!connection->inputState.trackMotion(motionEntry, dispatchEntry->resolvedAction,
3366 dispatchEntry->resolvedFlags)) {
Siarhei Vishniakouc94dafe2023-05-26 10:24:19 -07003367 LOG(WARNING) << "channel " << connection->getInputChannelName()
3368 << "~ dropping inconsistent event: " << *dispatchEntry;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003369 return; // skip the inconsistent event
3370 }
3371
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003372 dispatchEntry->resolvedEventId =
3373 dispatchEntry->resolvedEventId == DEFAULT_RESOLVED_EVENT_ID
3374 ? mIdGenerator.nextId()
3375 : motionEntry.id;
3376 if (ATRACE_ENABLED() && dispatchEntry->resolvedEventId != motionEntry.id) {
3377 std::string message = StringPrintf("Transmute MotionEvent(id=0x%" PRIx32
3378 ") to MotionEvent(id=0x%" PRIx32 ").",
3379 motionEntry.id, dispatchEntry->resolvedEventId);
3380 ATRACE_NAME(message.c_str());
3381 }
3382
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08003383 if ((motionEntry.flags & AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE) &&
3384 (motionEntry.policyFlags & POLICY_FLAG_TRUSTED)) {
3385 // Skip reporting pointer down outside focus to the policy.
3386 break;
3387 }
3388
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003389 dispatchPointerDownOutsideFocus(motionEntry.source, dispatchEntry->resolvedAction,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003390 inputTarget.inputChannel->getConnectionToken());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003391
3392 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003393 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003394 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003395 case EventEntry::Type::TOUCH_MODE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08003396 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
3397 case EventEntry::Type::DRAG: {
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003398 break;
3399 }
Chris Yef59a2f42020-10-16 12:55:26 -07003400 case EventEntry::Type::SENSOR: {
3401 LOG_ALWAYS_FATAL("SENSOR events should not go to apps via input channel");
3402 break;
3403 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003404 case EventEntry::Type::CONFIGURATION_CHANGED:
3405 case EventEntry::Type::DEVICE_RESET: {
3406 LOG_ALWAYS_FATAL("%s events should not go to apps",
Dominik Laskowski75788452021-02-09 18:51:25 -08003407 ftl::enum_string(newEntry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003408 break;
3409 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003410 }
3411
3412 // Remember that we are waiting for this dispatch to complete.
3413 if (dispatchEntry->hasForegroundTarget()) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003414 incrementPendingForegroundDispatches(newEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003415 }
3416
3417 // Enqueue the dispatch entry.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003418 connection->outboundQueue.push_back(dispatchEntry.release());
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003419 traceOutboundQueueLength(*connection);
chaviw8c9cf542019-03-25 13:02:48 -07003420}
3421
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003422/**
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003423 * This function is for debugging and metrics collection. It has two roles.
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003424 *
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003425 * The first role is to log input interaction with windows, which helps determine what the user was
3426 * interacting with. For example, if user is touching launcher, we will see an input_interaction log
3427 * that user started interacting with launcher window, as well as any other window that received
3428 * that gesture, such as the wallpaper or other spy windows. A new input_interaction is only logged
3429 * when the set of tokens that received the event changes. It is not logged again as long as the
3430 * user is interacting with the same windows.
3431 *
3432 * The second role is to track input device activity for metrics collection. For each input event,
3433 * we report the set of UIDs that the input device interacted with to the policy. Unlike for the
3434 * input_interaction logs, the device interaction is reported even when the set of interaction
3435 * tokens do not change.
3436 *
3437 * For these purposes, we do not count ACTION_OUTSIDE, ACTION_UP and ACTION_CANCEL actions as
3438 * interaction. This includes up and cancel events for both keys and motions.
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003439 */
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003440void InputDispatcher::processInteractionsLocked(const EventEntry& entry,
3441 const std::vector<InputTarget>& targets) {
3442 int32_t deviceId;
3443 nsecs_t eventTime;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003444 // Skip ACTION_UP events, and all events other than keys and motions
3445 if (entry.type == EventEntry::Type::KEY) {
3446 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
3447 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
3448 return;
3449 }
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003450 deviceId = keyEntry.deviceId;
3451 eventTime = keyEntry.eventTime;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003452 } else if (entry.type == EventEntry::Type::MOTION) {
3453 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
3454 if (motionEntry.action == AMOTION_EVENT_ACTION_UP ||
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003455 motionEntry.action == AMOTION_EVENT_ACTION_CANCEL ||
3456 MotionEvent::getActionMasked(motionEntry.action) == AMOTION_EVENT_ACTION_POINTER_UP) {
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003457 return;
3458 }
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003459 deviceId = motionEntry.deviceId;
3460 eventTime = motionEntry.eventTime;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003461 } else {
3462 return; // Not a key or a motion
3463 }
3464
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003465 std::set<gui::Uid> interactionUids;
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07003466 std::unordered_set<sp<IBinder>, StrongPointerHash<IBinder>> newConnectionTokens;
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003467 std::vector<std::shared_ptr<Connection>> newConnections;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003468 for (const InputTarget& target : targets) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003469 if (target.flags.test(InputTarget::Flags::DISPATCH_AS_OUTSIDE)) {
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003470 continue; // Skip windows that receive ACTION_OUTSIDE
3471 }
3472
3473 sp<IBinder> token = target.inputChannel->getConnectionToken();
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003474 std::shared_ptr<Connection> connection = getConnectionLocked(token);
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003475 if (connection == nullptr) {
3476 continue;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003477 }
3478 newConnectionTokens.insert(std::move(token));
3479 newConnections.emplace_back(connection);
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003480 if (target.windowHandle) {
3481 interactionUids.emplace(target.windowHandle->getInfo()->ownerUid);
3482 }
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003483 }
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003484
3485 auto command = [this, deviceId, eventTime, uids = std::move(interactionUids)]()
3486 REQUIRES(mLock) {
3487 scoped_unlock unlock(mLock);
3488 mPolicy.notifyDeviceInteraction(deviceId, eventTime, uids);
3489 };
3490 postCommandLocked(std::move(command));
3491
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003492 if (newConnectionTokens == mInteractionConnectionTokens) {
3493 return; // no change
3494 }
3495 mInteractionConnectionTokens = newConnectionTokens;
3496
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003497 std::string targetList;
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003498 for (const std::shared_ptr<Connection>& connection : newConnections) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003499 targetList += connection->getWindowName() + ", ";
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003500 }
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003501 std::string message = "Interaction with: " + targetList;
3502 if (targetList.empty()) {
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003503 message += "<none>";
3504 }
3505 android_log_event_list(LOGTAG_INPUT_INTERACTION) << message << LOG_ID_EVENTS;
3506}
3507
chaviwfd6d3512019-03-25 13:23:49 -07003508void InputDispatcher::dispatchPointerDownOutsideFocus(uint32_t source, int32_t action,
Vishnu Nairad321cd2020-08-20 16:40:21 -07003509 const sp<IBinder>& token) {
chaviw8c9cf542019-03-25 13:02:48 -07003510 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
chaviwfd6d3512019-03-25 13:23:49 -07003511 uint32_t maskedSource = source & AINPUT_SOURCE_CLASS_MASK;
3512 if (maskedSource != AINPUT_SOURCE_CLASS_POINTER || maskedAction != AMOTION_EVENT_ACTION_DOWN) {
chaviw8c9cf542019-03-25 13:02:48 -07003513 return;
3514 }
3515
Vishnu Nairc519ff72021-01-21 08:23:08 -08003516 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07003517 if (focusedToken == token) {
3518 // ignore since token is focused
chaviw8c9cf542019-03-25 13:02:48 -07003519 return;
3520 }
3521
Prabir Pradhancef936d2021-07-21 16:17:52 +00003522 auto command = [this, token]() REQUIRES(mLock) {
3523 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00003524 mPolicy.onPointerDownOutsideFocus(token);
Prabir Pradhancef936d2021-07-21 16:17:52 +00003525 };
3526 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003527}
3528
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003529status_t InputDispatcher::publishMotionEvent(Connection& connection,
3530 DispatchEntry& dispatchEntry) const {
3531 const EventEntry& eventEntry = *(dispatchEntry.eventEntry);
3532 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
3533
3534 PointerCoords scaledCoords[MAX_POINTERS];
3535 const PointerCoords* usingCoords = motionEntry.pointerCoords;
3536
3537 // Set the X and Y offset and X and Y scale depending on the input source.
3538 if ((motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) &&
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003539 !(dispatchEntry.targetFlags.test(InputTarget::Flags::ZERO_COORDS))) {
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003540 float globalScaleFactor = dispatchEntry.globalScaleFactor;
3541 if (globalScaleFactor != 1.0f) {
3542 for (uint32_t i = 0; i < motionEntry.pointerCount; i++) {
3543 scaledCoords[i] = motionEntry.pointerCoords[i];
3544 // Don't apply window scale here since we don't want scale to affect raw
3545 // coordinates. The scale will be sent back to the client and applied
3546 // later when requesting relative coordinates.
Harry Cutts33476232023-01-30 19:57:29 +00003547 scaledCoords[i].scale(globalScaleFactor, /*windowXScale=*/1, /*windowYScale=*/1);
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003548 }
3549 usingCoords = scaledCoords;
3550 }
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003551 } else if (dispatchEntry.targetFlags.test(InputTarget::Flags::ZERO_COORDS)) {
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003552 // We don't want the dispatch target to know the coordinates
3553 for (uint32_t i = 0; i < motionEntry.pointerCount; i++) {
3554 scaledCoords[i].clear();
3555 }
3556 usingCoords = scaledCoords;
3557 }
3558
3559 std::array<uint8_t, 32> hmac = getSignature(motionEntry, dispatchEntry);
3560
3561 // Publish the motion event.
3562 return connection.inputPublisher
3563 .publishMotionEvent(dispatchEntry.seq, dispatchEntry.resolvedEventId,
3564 motionEntry.deviceId, motionEntry.source, motionEntry.displayId,
3565 std::move(hmac), dispatchEntry.resolvedAction,
3566 motionEntry.actionButton, dispatchEntry.resolvedFlags,
3567 motionEntry.edgeFlags, motionEntry.metaState,
3568 motionEntry.buttonState, motionEntry.classification,
3569 dispatchEntry.transform, motionEntry.xPrecision,
3570 motionEntry.yPrecision, motionEntry.xCursorPosition,
3571 motionEntry.yCursorPosition, dispatchEntry.rawTransform,
3572 motionEntry.downTime, motionEntry.eventTime,
3573 motionEntry.pointerCount, motionEntry.pointerProperties,
3574 usingCoords);
3575}
3576
Michael Wrightd02c5b62014-02-10 15:10:22 -08003577void InputDispatcher::startDispatchCycleLocked(nsecs_t currentTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003578 const std::shared_ptr<Connection>& connection) {
Prabir Pradhan2dac8b82023-09-06 01:11:51 +00003579 ATRACE_NAME_IF(ATRACE_ENABLED(),
3580 StringPrintf("startDispatchCycleLocked(inputChannel=%s)",
3581 connection->getInputChannelName().c_str()));
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003582 if (DEBUG_DISPATCH_CYCLE) {
3583 ALOGD("channel '%s' ~ startDispatchCycle", connection->getInputChannelName().c_str());
3584 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003585
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003586 while (connection->status == Connection::Status::NORMAL && !connection->outboundQueue.empty()) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003587 DispatchEntry* dispatchEntry = connection->outboundQueue.front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003588 dispatchEntry->deliveryTime = currentTime;
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003589 const std::chrono::nanoseconds timeout = getDispatchingTimeoutLocked(connection);
Siarhei Vishniakou70622952020-07-30 11:17:23 -05003590 dispatchEntry->timeoutTime = currentTime + timeout.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003591
3592 // Publish the event.
3593 status_t status;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003594 const EventEntry& eventEntry = *(dispatchEntry->eventEntry);
3595 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003596 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003597 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
3598 std::array<uint8_t, 32> hmac = getSignature(keyEntry, *dispatchEntry);
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08003599 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07003600 LOG(INFO) << "Publishing " << *dispatchEntry << " to "
3601 << connection->getInputChannelName();
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08003602 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003603
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003604 // Publish the key event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003605 status = connection->inputPublisher
3606 .publishKeyEvent(dispatchEntry->seq,
3607 dispatchEntry->resolvedEventId, keyEntry.deviceId,
3608 keyEntry.source, keyEntry.displayId,
3609 std::move(hmac), dispatchEntry->resolvedAction,
3610 dispatchEntry->resolvedFlags, keyEntry.keyCode,
3611 keyEntry.scanCode, keyEntry.metaState,
3612 keyEntry.repeatCount, keyEntry.downTime,
3613 keyEntry.eventTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003614 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003615 }
3616
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003617 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08003618 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07003619 LOG(INFO) << "Publishing " << *dispatchEntry << " to "
3620 << connection->getInputChannelName();
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08003621 }
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003622 status = publishMotionEvent(*connection, *dispatchEntry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003623 break;
3624 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003625
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003626 case EventEntry::Type::FOCUS: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003627 const FocusEntry& focusEntry = static_cast<const FocusEntry&>(eventEntry);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003628 status = connection->inputPublisher.publishFocusEvent(dispatchEntry->seq,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003629 focusEntry.id,
Antonio Kantek3cfec7b2021-11-05 18:26:17 -07003630 focusEntry.hasFocus);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003631 break;
3632 }
3633
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003634 case EventEntry::Type::TOUCH_MODE_CHANGED: {
3635 const TouchModeEntry& touchModeEntry =
3636 static_cast<const TouchModeEntry&>(eventEntry);
3637 status = connection->inputPublisher
3638 .publishTouchModeEvent(dispatchEntry->seq, touchModeEntry.id,
3639 touchModeEntry.inTouchMode);
3640
3641 break;
3642 }
3643
Prabir Pradhan99987712020-11-10 18:43:05 -08003644 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
3645 const auto& captureEntry =
3646 static_cast<const PointerCaptureChangedEntry&>(eventEntry);
3647 status = connection->inputPublisher
3648 .publishCaptureEvent(dispatchEntry->seq, captureEntry.id,
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00003649 captureEntry.pointerCaptureRequest.enable);
Prabir Pradhan99987712020-11-10 18:43:05 -08003650 break;
3651 }
3652
arthurhungb89ccb02020-12-30 16:19:01 +08003653 case EventEntry::Type::DRAG: {
3654 const DragEntry& dragEntry = static_cast<const DragEntry&>(eventEntry);
3655 status = connection->inputPublisher.publishDragEvent(dispatchEntry->seq,
3656 dragEntry.id, dragEntry.x,
3657 dragEntry.y,
3658 dragEntry.isExiting);
3659 break;
3660 }
3661
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003662 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07003663 case EventEntry::Type::DEVICE_RESET:
3664 case EventEntry::Type::SENSOR: {
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003665 LOG_ALWAYS_FATAL("Should never start dispatch cycles for %s events",
Dominik Laskowski75788452021-02-09 18:51:25 -08003666 ftl::enum_string(eventEntry.type).c_str());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003667 return;
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003668 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003669 }
3670
3671 // Check the result.
3672 if (status) {
3673 if (status == WOULD_BLOCK) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003674 if (connection->waitQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003675 ALOGE("channel '%s' ~ Could not publish event because the pipe is full. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003676 "This is unexpected because the wait queue is empty, so the pipe "
3677 "should be empty and we shouldn't have any problems writing an "
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +00003678 "event to it, status=%s(%d)",
3679 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3680 status);
Harry Cutts33476232023-01-30 19:57:29 +00003681 abortBrokenDispatchCycleLocked(currentTime, connection, /*notify=*/true);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003682 } else {
3683 // Pipe is full and we are waiting for the app to finish process some events
3684 // before sending more events to it.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003685 if (DEBUG_DISPATCH_CYCLE) {
3686 ALOGD("channel '%s' ~ Could not publish event because the pipe is full, "
3687 "waiting for the application to catch up",
3688 connection->getInputChannelName().c_str());
3689 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003690 }
3691 } else {
3692 ALOGE("channel '%s' ~ Could not publish event due to an unexpected error, "
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +00003693 "status=%s(%d)",
3694 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3695 status);
Harry Cutts33476232023-01-30 19:57:29 +00003696 abortBrokenDispatchCycleLocked(currentTime, connection, /*notify=*/true);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003697 }
3698 return;
3699 }
3700
3701 // Re-enqueue the event on the wait queue.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003702 connection->outboundQueue.erase(std::remove(connection->outboundQueue.begin(),
3703 connection->outboundQueue.end(),
3704 dispatchEntry));
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003705 traceOutboundQueueLength(*connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003706 connection->waitQueue.push_back(dispatchEntry);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003707 if (connection->responsive) {
3708 mAnrTracker.insert(dispatchEntry->timeoutTime,
3709 connection->inputChannel->getConnectionToken());
3710 }
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003711 traceWaitQueueLength(*connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003712 }
3713}
3714
chaviw09c8d2d2020-08-24 15:48:26 -07003715std::array<uint8_t, 32> InputDispatcher::sign(const VerifiedInputEvent& event) const {
3716 size_t size;
3717 switch (event.type) {
3718 case VerifiedInputEvent::Type::KEY: {
3719 size = sizeof(VerifiedKeyEvent);
3720 break;
3721 }
3722 case VerifiedInputEvent::Type::MOTION: {
3723 size = sizeof(VerifiedMotionEvent);
3724 break;
3725 }
3726 }
3727 const uint8_t* start = reinterpret_cast<const uint8_t*>(&event);
3728 return mHmacKeyManager.sign(start, size);
3729}
3730
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003731const std::array<uint8_t, 32> InputDispatcher::getSignature(
3732 const MotionEntry& motionEntry, const DispatchEntry& dispatchEntry) const {
Siarhei Vishniakoubf880522023-05-01 11:03:22 -07003733 const int32_t actionMasked = MotionEvent::getActionMasked(dispatchEntry.resolvedAction);
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003734 if (actionMasked != AMOTION_EVENT_ACTION_UP && actionMasked != AMOTION_EVENT_ACTION_DOWN) {
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003735 // Only sign events up and down events as the purely move events
3736 // are tied to their up/down counterparts so signing would be redundant.
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003737 return INVALID_HMAC;
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003738 }
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003739
3740 VerifiedMotionEvent verifiedEvent =
3741 verifiedMotionEventFromMotionEntry(motionEntry, dispatchEntry.rawTransform);
3742 verifiedEvent.actionMasked = actionMasked;
3743 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_MOTION_EVENT_FLAGS;
3744 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003745}
3746
3747const std::array<uint8_t, 32> InputDispatcher::getSignature(
3748 const KeyEntry& keyEntry, const DispatchEntry& dispatchEntry) const {
3749 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEntry(keyEntry);
3750 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_KEY_EVENT_FLAGS;
3751 verifiedEvent.action = dispatchEntry.resolvedAction;
chaviw09c8d2d2020-08-24 15:48:26 -07003752 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003753}
3754
Michael Wrightd02c5b62014-02-10 15:10:22 -08003755void InputDispatcher::finishDispatchCycleLocked(nsecs_t currentTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003756 const std::shared_ptr<Connection>& connection,
3757 uint32_t seq, bool handled, nsecs_t consumeTime) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003758 if (DEBUG_DISPATCH_CYCLE) {
3759 ALOGD("channel '%s' ~ finishDispatchCycle - seq=%u, handled=%s",
3760 connection->getInputChannelName().c_str(), seq, toString(handled));
3761 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003762
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003763 if (connection->status == Connection::Status::BROKEN ||
3764 connection->status == Connection::Status::ZOMBIE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003765 return;
3766 }
3767
3768 // Notify other system components and prepare to start the next dispatch cycle.
Prabir Pradhancef936d2021-07-21 16:17:52 +00003769 auto command = [this, currentTime, connection, seq, handled, consumeTime]() REQUIRES(mLock) {
3770 doDispatchCycleFinishedCommand(currentTime, connection, seq, handled, consumeTime);
3771 };
3772 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003773}
3774
3775void InputDispatcher::abortBrokenDispatchCycleLocked(nsecs_t currentTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003776 const std::shared_ptr<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003777 bool notify) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003778 if (DEBUG_DISPATCH_CYCLE) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07003779 LOG(INFO) << "channel '" << connection->getInputChannelName() << "'~ " << __func__
3780 << " - notify=" << toString(notify);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003781 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003782
3783 // Clear the dispatch queues.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003784 drainDispatchQueue(connection->outboundQueue);
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003785 traceOutboundQueueLength(*connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003786 drainDispatchQueue(connection->waitQueue);
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003787 traceWaitQueueLength(*connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003788
3789 // The connection appears to be unrecoverably broken.
3790 // Ignore already broken or zombie connections.
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003791 if (connection->status == Connection::Status::NORMAL) {
3792 connection->status = Connection::Status::BROKEN;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003793
3794 if (notify) {
3795 // Notify other system components.
Prabir Pradhancef936d2021-07-21 16:17:52 +00003796 ALOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
3797 connection->getInputChannelName().c_str());
3798
3799 auto command = [this, connection]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00003800 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00003801 mPolicy.notifyInputChannelBroken(connection->inputChannel->getConnectionToken());
Prabir Pradhancef936d2021-07-21 16:17:52 +00003802 };
3803 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003804 }
3805 }
3806}
3807
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003808void InputDispatcher::drainDispatchQueue(std::deque<DispatchEntry*>& queue) {
3809 while (!queue.empty()) {
3810 DispatchEntry* dispatchEntry = queue.front();
3811 queue.pop_front();
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003812 releaseDispatchEntry(dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003813 }
3814}
3815
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003816void InputDispatcher::releaseDispatchEntry(DispatchEntry* dispatchEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003817 if (dispatchEntry->hasForegroundTarget()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003818 decrementPendingForegroundDispatches(*(dispatchEntry->eventEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003819 }
3820 delete dispatchEntry;
3821}
3822
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003823int InputDispatcher::handleReceiveCallback(int events, sp<IBinder> connectionToken) {
3824 std::scoped_lock _l(mLock);
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003825 std::shared_ptr<Connection> connection = getConnectionLocked(connectionToken);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003826 if (connection == nullptr) {
3827 ALOGW("Received looper callback for unknown input channel token %p. events=0x%x",
3828 connectionToken.get(), events);
3829 return 0; // remove the callback
3830 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003831
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003832 bool notify;
3833 if (!(events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP))) {
3834 if (!(events & ALOOPER_EVENT_INPUT)) {
3835 ALOGW("channel '%s' ~ Received spurious callback for unhandled poll event. "
3836 "events=0x%x",
3837 connection->getInputChannelName().c_str(), events);
3838 return 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003839 }
3840
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003841 nsecs_t currentTime = now();
3842 bool gotOne = false;
3843 status_t status = OK;
3844 for (;;) {
3845 Result<InputPublisher::ConsumerResponse> result =
3846 connection->inputPublisher.receiveConsumerResponse();
3847 if (!result.ok()) {
3848 status = result.error().code();
3849 break;
3850 }
3851
3852 if (std::holds_alternative<InputPublisher::Finished>(*result)) {
3853 const InputPublisher::Finished& finish =
3854 std::get<InputPublisher::Finished>(*result);
3855 finishDispatchCycleLocked(currentTime, connection, finish.seq, finish.handled,
3856 finish.consumeTime);
3857 } else if (std::holds_alternative<InputPublisher::Timeline>(*result)) {
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00003858 if (shouldReportMetricsForConnection(*connection)) {
3859 const InputPublisher::Timeline& timeline =
3860 std::get<InputPublisher::Timeline>(*result);
3861 mLatencyTracker
3862 .trackGraphicsLatency(timeline.inputEventId,
3863 connection->inputChannel->getConnectionToken(),
3864 std::move(timeline.graphicsTimeline));
3865 }
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003866 }
3867 gotOne = true;
3868 }
3869 if (gotOne) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00003870 runCommandsLockedInterruptable();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003871 if (status == WOULD_BLOCK) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003872 return 1;
3873 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003874 }
3875
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003876 notify = status != DEAD_OBJECT || !connection->monitor;
3877 if (notify) {
3878 ALOGE("channel '%s' ~ Failed to receive finished signal. status=%s(%d)",
3879 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3880 status);
3881 }
3882 } else {
3883 // Monitor channels are never explicitly unregistered.
3884 // We do it automatically when the remote endpoint is closed so don't warn about them.
3885 const bool stillHaveWindowHandle =
3886 getWindowHandleLocked(connection->inputChannel->getConnectionToken()) != nullptr;
3887 notify = !connection->monitor && stillHaveWindowHandle;
3888 if (notify) {
3889 ALOGW("channel '%s' ~ Consumer closed input channel or an error occurred. events=0x%x",
3890 connection->getInputChannelName().c_str(), events);
3891 }
3892 }
3893
3894 // Remove the channel.
3895 removeInputChannelLocked(connection->inputChannel->getConnectionToken(), notify);
3896 return 0; // remove the callback
Michael Wrightd02c5b62014-02-10 15:10:22 -08003897}
3898
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003899void InputDispatcher::synthesizeCancelationEventsForAllConnectionsLocked(
Michael Wrightd02c5b62014-02-10 15:10:22 -08003900 const CancelationOptions& options) {
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003901 for (const auto& [token, connection] : mConnectionsByToken) {
Siarhei Vishniakou2e2ea992020-12-15 02:57:19 +00003902 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003903 }
3904}
3905
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003906void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
Michael Wrightfa13dcf2015-06-12 13:25:11 +01003907 const CancelationOptions& options) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08003908 for (const auto& [_, monitors] : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003909 for (const Monitor& monitor : monitors) {
3910 synthesizeCancelationEventsForInputChannelLocked(monitor.inputChannel, options);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003911 }
Michael Wrightfa13dcf2015-06-12 13:25:11 +01003912 }
3913}
3914
Michael Wrightd02c5b62014-02-10 15:10:22 -08003915void InputDispatcher::synthesizeCancelationEventsForInputChannelLocked(
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05003916 const std::shared_ptr<InputChannel>& channel, const CancelationOptions& options) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003917 std::shared_ptr<Connection> connection = getConnectionLocked(channel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003918 if (connection == nullptr) {
3919 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003920 }
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003921
3922 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003923}
3924
3925void InputDispatcher::synthesizeCancelationEventsForConnectionLocked(
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003926 const std::shared_ptr<Connection>& connection, const CancelationOptions& options) {
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003927 if (connection->status == Connection::Status::BROKEN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003928 return;
3929 }
3930
3931 nsecs_t currentTime = now();
3932
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003933 std::vector<std::unique_ptr<EventEntry>> cancelationEvents =
Siarhei Vishniakou00fca7c2019-10-29 13:05:57 -07003934 connection->inputState.synthesizeCancelationEvents(currentTime, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003935
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003936 if (cancelationEvents.empty()) {
3937 return;
3938 }
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003939 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
3940 ALOGD("channel '%s' ~ Synthesized %zu cancelation events to bring channel back in sync "
Siarhei Vishniakou2e3e4432023-02-09 18:34:11 -08003941 "with reality: %s, mode=%s.",
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003942 connection->getInputChannelName().c_str(), cancelationEvents.size(), options.reason,
Siarhei Vishniakou2e3e4432023-02-09 18:34:11 -08003943 ftl::enum_string(options.mode).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003944 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08003945
Arthur Hungb3307ee2021-10-14 10:57:37 +00003946 std::string reason = std::string("reason=").append(options.reason);
3947 android_log_event_list(LOGTAG_INPUT_CANCEL)
3948 << connection->getInputChannelName().c_str() << reason << LOG_ID_EVENTS;
3949
Svet Ganov5d3bc372020-01-26 23:11:07 -08003950 InputTarget target;
Hu Guo771a7692023-09-17 20:51:08 +08003951 sp<WindowInfoHandle> windowHandle;
3952 if (options.displayId) {
3953 windowHandle = getWindowHandleLocked(connection->inputChannel->getConnectionToken(),
3954 options.displayId.value());
3955 } else {
3956 windowHandle = getWindowHandleLocked(connection->inputChannel->getConnectionToken());
3957 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08003958 if (windowHandle != nullptr) {
chaviw98318de2021-05-19 16:45:23 -05003959 const WindowInfo* windowInfo = windowHandle->getInfo();
chaviw1ff3d1e2020-07-01 15:53:47 -07003960 target.setDefaultPointerTransform(windowInfo->transform);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003961 target.globalScaleFactor = windowInfo->globalScaleFactor;
3962 }
3963 target.inputChannel = connection->inputChannel;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003964 target.flags = InputTarget::Flags::DISPATCH_AS_IS;
Svet Ganov5d3bc372020-01-26 23:11:07 -08003965
hongzuo liu95785e22022-09-06 02:51:35 +00003966 const bool wasEmpty = connection->outboundQueue.empty();
3967
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003968 for (size_t i = 0; i < cancelationEvents.size(); i++) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003969 std::unique_ptr<EventEntry> cancelationEventEntry = std::move(cancelationEvents[i]);
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003970 switch (cancelationEventEntry->type) {
3971 case EventEntry::Type::KEY: {
3972 logOutboundKeyDetails("cancel - ",
3973 static_cast<const KeyEntry&>(*cancelationEventEntry));
3974 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003975 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003976 case EventEntry::Type::MOTION: {
3977 logOutboundMotionDetails("cancel - ",
3978 static_cast<const MotionEntry&>(*cancelationEventEntry));
3979 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003980 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003981 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003982 case EventEntry::Type::TOUCH_MODE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08003983 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
3984 case EventEntry::Type::DRAG: {
Prabir Pradhan99987712020-11-10 18:43:05 -08003985 LOG_ALWAYS_FATAL("Canceling %s events is not supported",
Dominik Laskowski75788452021-02-09 18:51:25 -08003986 ftl::enum_string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003987 break;
3988 }
3989 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07003990 case EventEntry::Type::DEVICE_RESET:
3991 case EventEntry::Type::SENSOR: {
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003992 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Dominik Laskowski75788452021-02-09 18:51:25 -08003993 ftl::enum_string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003994 break;
3995 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003996 }
3997
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003998 enqueueDispatchEntryLocked(connection, std::move(cancelationEventEntry), target,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003999 InputTarget::Flags::DISPATCH_AS_IS);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004000 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004001
hongzuo liu95785e22022-09-06 02:51:35 +00004002 // If the outbound queue was previously empty, start the dispatch cycle going.
4003 if (wasEmpty && !connection->outboundQueue.empty()) {
4004 startDispatchCycleLocked(currentTime, connection);
4005 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004006}
4007
Svet Ganov5d3bc372020-01-26 23:11:07 -08004008void InputDispatcher::synthesizePointerDownEventsForConnectionLocked(
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07004009 const nsecs_t downTime, const std::shared_ptr<Connection>& connection,
Arthur Hungc539dbb2022-12-08 07:45:36 +00004010 ftl::Flags<InputTarget::Flags> targetFlags) {
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08004011 if (connection->status == Connection::Status::BROKEN) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08004012 return;
4013 }
4014
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004015 std::vector<std::unique_ptr<EventEntry>> downEvents =
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00004016 connection->inputState.synthesizePointerDownEvents(downTime);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004017
4018 if (downEvents.empty()) {
4019 return;
4020 }
4021
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004022 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08004023 ALOGD("channel '%s' ~ Synthesized %zu down events to ensure consistent event stream.",
4024 connection->getInputChannelName().c_str(), downEvents.size());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004025 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08004026
4027 InputTarget target;
chaviw98318de2021-05-19 16:45:23 -05004028 sp<WindowInfoHandle> windowHandle =
Svet Ganov5d3bc372020-01-26 23:11:07 -08004029 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
4030 if (windowHandle != nullptr) {
chaviw98318de2021-05-19 16:45:23 -05004031 const WindowInfo* windowInfo = windowHandle->getInfo();
chaviw1ff3d1e2020-07-01 15:53:47 -07004032 target.setDefaultPointerTransform(windowInfo->transform);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004033 target.globalScaleFactor = windowInfo->globalScaleFactor;
4034 }
4035 target.inputChannel = connection->inputChannel;
Arthur Hungc539dbb2022-12-08 07:45:36 +00004036 target.flags = targetFlags;
Svet Ganov5d3bc372020-01-26 23:11:07 -08004037
hongzuo liu95785e22022-09-06 02:51:35 +00004038 const bool wasEmpty = connection->outboundQueue.empty();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004039 for (std::unique_ptr<EventEntry>& downEventEntry : downEvents) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08004040 switch (downEventEntry->type) {
4041 case EventEntry::Type::MOTION: {
4042 logOutboundMotionDetails("down - ",
4043 static_cast<const MotionEntry&>(*downEventEntry));
4044 break;
4045 }
4046
4047 case EventEntry::Type::KEY:
4048 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07004049 case EventEntry::Type::TOUCH_MODE_CHANGED:
Svet Ganov5d3bc372020-01-26 23:11:07 -08004050 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08004051 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07004052 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08004053 case EventEntry::Type::SENSOR:
4054 case EventEntry::Type::DRAG: {
Svet Ganov5d3bc372020-01-26 23:11:07 -08004055 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Dominik Laskowski75788452021-02-09 18:51:25 -08004056 ftl::enum_string(downEventEntry->type).c_str());
Svet Ganov5d3bc372020-01-26 23:11:07 -08004057 break;
4058 }
4059 }
4060
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004061 enqueueDispatchEntryLocked(connection, std::move(downEventEntry), target,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08004062 InputTarget::Flags::DISPATCH_AS_IS);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004063 }
4064
hongzuo liu95785e22022-09-06 02:51:35 +00004065 // If the outbound queue was previously empty, start the dispatch cycle going.
4066 if (wasEmpty && !connection->outboundQueue.empty()) {
4067 startDispatchCycleLocked(downTime, connection);
4068 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08004069}
4070
Arthur Hungc539dbb2022-12-08 07:45:36 +00004071void InputDispatcher::synthesizeCancelationEventsForWindowLocked(
4072 const sp<WindowInfoHandle>& windowHandle, const CancelationOptions& options) {
4073 if (windowHandle != nullptr) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07004074 std::shared_ptr<Connection> wallpaperConnection =
4075 getConnectionLocked(windowHandle->getToken());
Arthur Hungc539dbb2022-12-08 07:45:36 +00004076 if (wallpaperConnection != nullptr) {
4077 synthesizeCancelationEventsForConnectionLocked(wallpaperConnection, options);
4078 }
4079 }
4080}
4081
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004082std::unique_ptr<MotionEntry> InputDispatcher::splitMotionEvent(
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08004083 const MotionEntry& originalMotionEntry, std::bitset<MAX_POINTER_ID + 1> pointerIds,
4084 nsecs_t splitDownTime) {
4085 ALOG_ASSERT(pointerIds.any());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004086
4087 uint32_t splitPointerIndexMap[MAX_POINTERS];
4088 PointerProperties splitPointerProperties[MAX_POINTERS];
4089 PointerCoords splitPointerCoords[MAX_POINTERS];
4090
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07004091 uint32_t originalPointerCount = originalMotionEntry.pointerCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004092 uint32_t splitPointerCount = 0;
4093
4094 for (uint32_t originalPointerIndex = 0; originalPointerIndex < originalPointerCount;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004095 originalPointerIndex++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004096 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07004097 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08004098 uint32_t pointerId = uint32_t(pointerProperties.id);
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08004099 if (pointerIds.test(pointerId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004100 splitPointerIndexMap[splitPointerCount] = originalPointerIndex;
Siarhei Vishniakou73e6d372023-07-06 18:07:21 -07004101 splitPointerProperties[splitPointerCount] = pointerProperties;
4102 splitPointerCoords[splitPointerCount] =
4103 originalMotionEntry.pointerCoords[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08004104 splitPointerCount += 1;
4105 }
4106 }
4107
4108 if (splitPointerCount != pointerIds.count()) {
4109 // This is bad. We are missing some of the pointers that we expected to deliver.
4110 // Most likely this indicates that we received an ACTION_MOVE events that has
4111 // different pointer ids than we expected based on the previous ACTION_DOWN
4112 // or ACTION_POINTER_DOWN events that caused us to decide to split the pointers
4113 // in this way.
4114 ALOGW("Dropping split motion event because the pointer count is %d but "
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08004115 "we expected there to be %zu pointers. This probably means we received "
Siarhei Vishniakou16e4fa02023-02-16 17:48:56 -08004116 "a broken sequence of pointer ids from the input device: %s",
4117 splitPointerCount, pointerIds.count(), originalMotionEntry.getDescription().c_str());
Yi Kong9b14ac62018-07-17 13:48:38 -07004118 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004119 }
4120
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07004121 int32_t action = originalMotionEntry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004122 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004123 if (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN ||
4124 maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
Siarhei Vishniakou5b9766d2023-07-18 14:06:29 -07004125 int32_t originalPointerIndex = MotionEvent::getActionIndex(action);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004126 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07004127 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08004128 uint32_t pointerId = uint32_t(pointerProperties.id);
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08004129 if (pointerIds.test(pointerId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004130 if (pointerIds.count() == 1) {
4131 // The first/last pointer went down/up.
4132 action = maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004133 ? AMOTION_EVENT_ACTION_DOWN
arthurhungea3f4fc2020-12-21 23:18:53 +08004134 : (originalMotionEntry.flags & AMOTION_EVENT_FLAG_CANCELED) != 0
4135 ? AMOTION_EVENT_ACTION_CANCEL
4136 : AMOTION_EVENT_ACTION_UP;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004137 } else {
4138 // A secondary pointer went down/up.
4139 uint32_t splitPointerIndex = 0;
4140 while (pointerId != uint32_t(splitPointerProperties[splitPointerIndex].id)) {
4141 splitPointerIndex += 1;
4142 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004143 action = maskedAction |
4144 (splitPointerIndex << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004145 }
4146 } else {
4147 // An unrelated pointer changed.
4148 action = AMOTION_EVENT_ACTION_MOVE;
4149 }
4150 }
4151
Siarhei Vishniakou59e302b2023-06-05 08:04:53 -07004152 if (action == AMOTION_EVENT_ACTION_DOWN && splitDownTime != originalMotionEntry.eventTime) {
4153 logDispatchStateLocked();
4154 LOG_ALWAYS_FATAL("Split motion event has mismatching downTime and eventTime for "
4155 "ACTION_DOWN, motionEntry=%s, splitDownTime=%" PRId64,
4156 originalMotionEntry.getDescription().c_str(), splitDownTime);
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00004157 }
4158
Garfield Tanff1f1bb2020-01-28 13:24:04 -08004159 int32_t newId = mIdGenerator.nextId();
Prabir Pradhan2dac8b82023-09-06 01:11:51 +00004160 ATRACE_NAME_IF(ATRACE_ENABLED(),
4161 StringPrintf("Split MotionEvent(id=0x%" PRIx32 ") to MotionEvent(id=0x%" PRIx32
4162 ").",
4163 originalMotionEntry.id, newId));
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004164 std::unique_ptr<MotionEntry> splitMotionEntry =
4165 std::make_unique<MotionEntry>(newId, originalMotionEntry.eventTime,
4166 originalMotionEntry.deviceId, originalMotionEntry.source,
4167 originalMotionEntry.displayId,
4168 originalMotionEntry.policyFlags, action,
4169 originalMotionEntry.actionButton,
4170 originalMotionEntry.flags, originalMotionEntry.metaState,
4171 originalMotionEntry.buttonState,
4172 originalMotionEntry.classification,
4173 originalMotionEntry.edgeFlags,
4174 originalMotionEntry.xPrecision,
4175 originalMotionEntry.yPrecision,
4176 originalMotionEntry.xCursorPosition,
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00004177 originalMotionEntry.yCursorPosition, splitDownTime,
4178 splitPointerCount, splitPointerProperties,
4179 splitPointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004180
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07004181 if (originalMotionEntry.injectionState) {
4182 splitMotionEntry->injectionState = originalMotionEntry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004183 splitMotionEntry->injectionState->refCount += 1;
4184 }
4185
4186 return splitMotionEntry;
4187}
4188
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004189void InputDispatcher::notifyConfigurationChanged(const NotifyConfigurationChangedArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004190 if (debugInboundEventDetails()) {
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004191 ALOGD("notifyConfigurationChanged - eventTime=%" PRId64, args.eventTime);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004192 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004193
Antonio Kantekf16f2832021-09-28 04:39:20 +00004194 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004195 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004196 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004197
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004198 std::unique_ptr<ConfigurationChangedEntry> newEntry =
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004199 std::make_unique<ConfigurationChangedEntry>(args.id, args.eventTime);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004200 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004201 } // release lock
4202
4203 if (needWake) {
4204 mLooper->wake();
4205 }
4206}
4207
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004208void InputDispatcher::notifyKey(const NotifyKeyArgs& args) {
Prabir Pradhan96282b02023-02-24 22:36:17 +00004209 ALOGD_IF(debugInboundEventDetails(),
4210 "notifyKey - id=%" PRIx32 ", eventTime=%" PRId64
4211 ", deviceId=%d, source=%s, displayId=%" PRId32
4212 "policyFlags=0x%x, action=%s, flags=0x%x, keyCode=%s, scanCode=0x%x, metaState=0x%x, "
4213 "downTime=%" PRId64,
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004214 args.id, args.eventTime, args.deviceId, inputEventSourceToString(args.source).c_str(),
4215 args.displayId, args.policyFlags, KeyEvent::actionToString(args.action), args.flags,
4216 KeyEvent::getLabel(args.keyCode), args.scanCode, args.metaState, args.downTime);
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004217 Result<void> keyCheck = validateKeyEvent(args.action);
4218 if (!keyCheck.ok()) {
4219 LOG(ERROR) << "invalid key event: " << keyCheck.error();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004220 return;
4221 }
4222
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004223 uint32_t policyFlags = args.policyFlags;
4224 int32_t flags = args.flags;
4225 int32_t metaState = args.metaState;
Siarhei Vishniakou622bd322018-10-29 18:02:27 -07004226 // InputDispatcher tracks and generates key repeats on behalf of
4227 // whatever notifies it, so repeatCount should always be set to 0
4228 constexpr int32_t repeatCount = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004229 if ((policyFlags & POLICY_FLAG_VIRTUAL) || (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY)) {
4230 policyFlags |= POLICY_FLAG_VIRTUAL;
4231 flags |= AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
4232 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004233 if (policyFlags & POLICY_FLAG_FUNCTION) {
4234 metaState |= AMETA_FUNCTION_ON;
4235 }
4236
4237 policyFlags |= POLICY_FLAG_TRUSTED;
4238
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004239 int32_t keyCode = args.keyCode;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004240 KeyEvent event;
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004241 event.initialize(args.id, args.deviceId, args.source, args.displayId, INVALID_HMAC, args.action,
4242 flags, keyCode, args.scanCode, metaState, repeatCount, args.downTime,
4243 args.eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004244
Michael Wright2b3c3302018-03-02 17:19:13 +00004245 android::base::Timer t;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004246 mPolicy.interceptKeyBeforeQueueing(event, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00004247 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4248 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004249 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00004250 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004251
Antonio Kantekf16f2832021-09-28 04:39:20 +00004252 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004253 { // acquire lock
4254 mLock.lock();
4255
4256 if (shouldSendKeyToInputFilterLocked(args)) {
4257 mLock.unlock();
4258
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004259 policyFlags |= POLICY_FLAG_FILTERED;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004260 if (!mPolicy.filterInputEvent(event, policyFlags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004261 return; // event was consumed by the filter
4262 }
4263
4264 mLock.lock();
4265 }
4266
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004267 std::unique_ptr<KeyEntry> newEntry =
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004268 std::make_unique<KeyEntry>(args.id, args.eventTime, args.deviceId, args.source,
4269 args.displayId, policyFlags, args.action, flags, keyCode,
4270 args.scanCode, metaState, repeatCount, args.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004271
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004272 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004273 mLock.unlock();
4274 } // release lock
4275
4276 if (needWake) {
4277 mLooper->wake();
4278 }
4279}
4280
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004281bool InputDispatcher::shouldSendKeyToInputFilterLocked(const NotifyKeyArgs& args) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004282 return mInputFilterEnabled;
4283}
4284
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004285void InputDispatcher::notifyMotion(const NotifyMotionArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004286 if (debugInboundEventDetails()) {
Prabir Pradhan96282b02023-02-24 22:36:17 +00004287 ALOGD("notifyMotion - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=%s, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004288 "displayId=%" PRId32 ", policyFlags=0x%x, "
Siarhei Vishniakou6ebd0692022-10-20 15:05:45 -07004289 "action=%s, actionButton=0x%x, flags=0x%x, metaState=0x%x, buttonState=0x%x, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004290 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, xCursorPosition=%f, "
4291 "yCursorPosition=%f, downTime=%" PRId64,
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004292 args.id, args.eventTime, args.deviceId, inputEventSourceToString(args.source).c_str(),
4293 args.displayId, args.policyFlags, MotionEvent::actionToString(args.action).c_str(),
4294 args.actionButton, args.flags, args.metaState, args.buttonState, args.edgeFlags,
4295 args.xPrecision, args.yPrecision, args.xCursorPosition, args.yCursorPosition,
4296 args.downTime);
Siarhei Vishniakou3218fc02023-06-15 20:41:02 -07004297 for (uint32_t i = 0; i < args.getPointerCount(); i++) {
Prabir Pradhan96282b02023-02-24 22:36:17 +00004298 ALOGD(" Pointer %d: id=%d, toolType=%s, x=%f, y=%f, pressure=%f, size=%f, "
4299 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, orientation=%f",
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004300 i, args.pointerProperties[i].id,
4301 ftl::enum_string(args.pointerProperties[i].toolType).c_str(),
4302 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
4303 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
4304 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
4305 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
4306 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
4307 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
4308 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
4309 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
4310 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004311 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004312 }
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004313
Siarhei Vishniakou3218fc02023-06-15 20:41:02 -07004314 Result<void> motionCheck =
4315 validateMotionEvent(args.action, args.actionButton, args.getPointerCount(),
4316 args.pointerProperties.data());
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004317 if (!motionCheck.ok()) {
4318 LOG(FATAL) << "Invalid event: " << args.dump() << "; reason: " << motionCheck.error();
4319 return;
4320 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004321
Siarhei Vishniakou5c02a712023-05-15 15:45:02 -07004322 if (DEBUG_VERIFY_EVENTS) {
4323 auto [it, _] =
4324 mVerifiersByDisplay.try_emplace(args.displayId,
4325 StringPrintf("display %" PRId32, args.displayId));
4326 Result<void> result =
Siarhei Vishniakou2d151ac2023-09-19 13:30:24 -07004327 it->second.processMovement(args.deviceId, args.source, args.action,
4328 args.getPointerCount(), args.pointerProperties.data(),
4329 args.pointerCoords.data(), args.flags);
Siarhei Vishniakou5c02a712023-05-15 15:45:02 -07004330 if (!result.ok()) {
4331 LOG(FATAL) << "Bad stream: " << result.error() << " caused by " << args.dump();
4332 }
4333 }
4334
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004335 uint32_t policyFlags = args.policyFlags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004336 policyFlags |= POLICY_FLAG_TRUSTED;
Michael Wright2b3c3302018-03-02 17:19:13 +00004337
4338 android::base::Timer t;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004339 mPolicy.interceptMotionBeforeQueueing(args.displayId, args.eventTime, policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00004340 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4341 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004342 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00004343 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004344
Antonio Kantekf16f2832021-09-28 04:39:20 +00004345 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004346 { // acquire lock
4347 mLock.lock();
Siarhei Vishniakou5bf25d92023-02-08 15:43:38 -08004348 if (!(policyFlags & POLICY_FLAG_PASS_TO_USER)) {
4349 // Set the flag anyway if we already have an ongoing gesture. That would allow us to
4350 // complete the processing of the current stroke.
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004351 const auto touchStateIt = mTouchStatesByDisplay.find(args.displayId);
Siarhei Vishniakou5bf25d92023-02-08 15:43:38 -08004352 if (touchStateIt != mTouchStatesByDisplay.end()) {
4353 const TouchState& touchState = touchStateIt->second;
Siarhei Vishniakou45504fe2023-05-05 16:05:10 -07004354 if (touchState.hasTouchingPointers(args.deviceId)) {
Siarhei Vishniakou5bf25d92023-02-08 15:43:38 -08004355 policyFlags |= POLICY_FLAG_PASS_TO_USER;
4356 }
4357 }
4358 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004359
4360 if (shouldSendMotionToInputFilterLocked(args)) {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004361 ui::Transform displayTransform;
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004362 if (const auto it = mDisplayInfos.find(args.displayId); it != mDisplayInfos.end()) {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004363 displayTransform = it->second.transform;
4364 }
4365
Michael Wrightd02c5b62014-02-10 15:10:22 -08004366 mLock.unlock();
4367
4368 MotionEvent event;
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004369 event.initialize(args.id, args.deviceId, args.source, args.displayId, INVALID_HMAC,
4370 args.action, args.actionButton, args.flags, args.edgeFlags,
4371 args.metaState, args.buttonState, args.classification,
4372 displayTransform, args.xPrecision, args.yPrecision,
4373 args.xCursorPosition, args.yCursorPosition, displayTransform,
Siarhei Vishniakou3218fc02023-06-15 20:41:02 -07004374 args.downTime, args.eventTime, args.getPointerCount(),
4375 args.pointerProperties.data(), args.pointerCoords.data());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004376
4377 policyFlags |= POLICY_FLAG_FILTERED;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004378 if (!mPolicy.filterInputEvent(event, policyFlags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004379 return; // event was consumed by the filter
4380 }
4381
4382 mLock.lock();
4383 }
4384
4385 // Just enqueue a new motion event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004386 std::unique_ptr<MotionEntry> newEntry =
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004387 std::make_unique<MotionEntry>(args.id, args.eventTime, args.deviceId, args.source,
4388 args.displayId, policyFlags, args.action,
4389 args.actionButton, args.flags, args.metaState,
4390 args.buttonState, args.classification, args.edgeFlags,
4391 args.xPrecision, args.yPrecision,
4392 args.xCursorPosition, args.yCursorPosition,
Siarhei Vishniakou3218fc02023-06-15 20:41:02 -07004393 args.downTime, args.getPointerCount(),
4394 args.pointerProperties.data(),
4395 args.pointerCoords.data());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004396
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004397 if (args.id != android::os::IInputConstants::INVALID_INPUT_EVENT_ID &&
4398 IdGenerator::getSource(args.id) == IdGenerator::Source::INPUT_READER &&
Siarhei Vishniakou363e7292021-07-09 03:22:42 +00004399 !mInputFilterEnabled) {
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004400 const bool isDown = args.action == AMOTION_EVENT_ACTION_DOWN;
4401 mLatencyTracker.trackListener(args.id, isDown, args.eventTime, args.readTime);
Siarhei Vishniakou363e7292021-07-09 03:22:42 +00004402 }
4403
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004404 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004405 mLock.unlock();
4406 } // release lock
4407
4408 if (needWake) {
4409 mLooper->wake();
4410 }
4411}
4412
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004413void InputDispatcher::notifySensor(const NotifySensorArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004414 if (debugInboundEventDetails()) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004415 ALOGD("notifySensor - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=0x%x, "
4416 " sensorType=%s",
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004417 args.id, args.eventTime, args.deviceId, args.source,
4418 ftl::enum_string(args.sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004419 }
Chris Yef59a2f42020-10-16 12:55:26 -07004420
Antonio Kantekf16f2832021-09-28 04:39:20 +00004421 bool needWake = false;
Chris Yef59a2f42020-10-16 12:55:26 -07004422 { // acquire lock
4423 mLock.lock();
4424
4425 // Just enqueue a new sensor event.
4426 std::unique_ptr<SensorEntry> newEntry =
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004427 std::make_unique<SensorEntry>(args.id, args.eventTime, args.deviceId, args.source,
4428 /* policyFlags=*/0, args.hwTimestamp, args.sensorType,
4429 args.accuracy, args.accuracyChanged, args.values);
Chris Yef59a2f42020-10-16 12:55:26 -07004430
4431 needWake = enqueueInboundEventLocked(std::move(newEntry));
4432 mLock.unlock();
4433 } // release lock
4434
4435 if (needWake) {
4436 mLooper->wake();
4437 }
4438}
4439
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004440void InputDispatcher::notifyVibratorState(const NotifyVibratorStateArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004441 if (debugInboundEventDetails()) {
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004442 ALOGD("notifyVibratorState - eventTime=%" PRId64 ", device=%d, isOn=%d", args.eventTime,
4443 args.deviceId, args.isOn);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004444 }
Prabir Pradhana41d2442023-04-20 21:30:40 +00004445 mPolicy.notifyVibratorState(args.deviceId, args.isOn);
Chris Yefb552902021-02-03 17:18:37 -08004446}
4447
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004448bool InputDispatcher::shouldSendMotionToInputFilterLocked(const NotifyMotionArgs& args) {
Jackal Guof9696682018-10-05 12:23:23 +08004449 return mInputFilterEnabled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004450}
4451
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004452void InputDispatcher::notifySwitch(const NotifySwitchArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004453 if (debugInboundEventDetails()) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004454 ALOGD("notifySwitch - eventTime=%" PRId64 ", policyFlags=0x%x, switchValues=0x%08x, "
4455 "switchMask=0x%08x",
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004456 args.eventTime, args.policyFlags, args.switchValues, args.switchMask);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004457 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004458
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004459 uint32_t policyFlags = args.policyFlags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004460 policyFlags |= POLICY_FLAG_TRUSTED;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004461 mPolicy.notifySwitch(args.eventTime, args.switchValues, args.switchMask, policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004462}
4463
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004464void InputDispatcher::notifyDeviceReset(const NotifyDeviceResetArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004465 if (debugInboundEventDetails()) {
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004466 ALOGD("notifyDeviceReset - eventTime=%" PRId64 ", deviceId=%d", args.eventTime,
4467 args.deviceId);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004468 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004469
Antonio Kantekf16f2832021-09-28 04:39:20 +00004470 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004471 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004472 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004473
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004474 std::unique_ptr<DeviceResetEntry> newEntry =
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004475 std::make_unique<DeviceResetEntry>(args.id, args.eventTime, args.deviceId);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004476 needWake = enqueueInboundEventLocked(std::move(newEntry));
Siarhei Vishniakou1160ecd2023-06-28 15:57:47 -07004477
4478 for (auto& [_, verifier] : mVerifiersByDisplay) {
4479 verifier.resetDevice(args.deviceId);
4480 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004481 } // release lock
4482
4483 if (needWake) {
4484 mLooper->wake();
4485 }
4486}
4487
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004488void InputDispatcher::notifyPointerCaptureChanged(const NotifyPointerCaptureChangedArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004489 if (debugInboundEventDetails()) {
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004490 ALOGD("notifyPointerCaptureChanged - eventTime=%" PRId64 ", enabled=%s", args.eventTime,
4491 args.request.enable ? "true" : "false");
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004492 }
Prabir Pradhan7e186182020-11-10 13:56:45 -08004493
Antonio Kantekf16f2832021-09-28 04:39:20 +00004494 bool needWake = false;
Prabir Pradhan99987712020-11-10 18:43:05 -08004495 { // acquire lock
4496 std::scoped_lock _l(mLock);
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004497 auto entry =
4498 std::make_unique<PointerCaptureChangedEntry>(args.id, args.eventTime, args.request);
Prabir Pradhan99987712020-11-10 18:43:05 -08004499 needWake = enqueueInboundEventLocked(std::move(entry));
4500 } // release lock
4501
4502 if (needWake) {
4503 mLooper->wake();
4504 }
Prabir Pradhan7e186182020-11-10 13:56:45 -08004505}
4506
Prabir Pradhan5735a322022-04-11 17:23:34 +00004507InputEventInjectionResult InputDispatcher::injectInputEvent(const InputEvent* event,
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00004508 std::optional<gui::Uid> targetUid,
Prabir Pradhan5735a322022-04-11 17:23:34 +00004509 InputEventInjectionSync syncMode,
4510 std::chrono::milliseconds timeout,
4511 uint32_t policyFlags) {
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004512 Result<void> eventValidation = validateInputEvent(*event);
4513 if (!eventValidation.ok()) {
4514 LOG(INFO) << "Injection failed: invalid event: " << eventValidation.error();
4515 return InputEventInjectionResult::FAILED;
4516 }
4517
Prabir Pradhan65613802023-02-22 23:36:58 +00004518 if (debugInboundEventDetails()) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07004519 LOG(INFO) << __func__ << ": targetUid=" << toString(targetUid, &uidString)
4520 << ", syncMode=" << ftl::enum_string(syncMode) << ", timeout=" << timeout.count()
4521 << "ms, policyFlags=0x" << std::hex << policyFlags << std::dec
4522 << ", event=" << *event;
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004523 }
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07004524 nsecs_t endTime = now() + std::chrono::duration_cast<std::chrono::nanoseconds>(timeout).count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004525
Prabir Pradhan5735a322022-04-11 17:23:34 +00004526 policyFlags |= POLICY_FLAG_INJECTED | POLICY_FLAG_TRUSTED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004527
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004528 // For all injected events, set device id = VIRTUAL_KEYBOARD_ID. The only exception is events
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004529 // that have gone through the InputFilter. If the event passed through the InputFilter, assign
4530 // the provided device id. If the InputFilter is accessibility, and it modifies or synthesizes
4531 // the injected event, it is responsible for setting POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY.
4532 // For those events, we will set FLAG_IS_ACCESSIBILITY_EVENT to allow apps to distinguish them
4533 // from events that originate from actual hardware.
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004534 int32_t resolvedDeviceId = VIRTUAL_KEYBOARD_ID;
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004535 if (policyFlags & POLICY_FLAG_FILTERED) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004536 resolvedDeviceId = event->getDeviceId();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004537 }
4538
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004539 std::queue<std::unique_ptr<EventEntry>> injectedEntries;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004540 switch (event->getType()) {
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004541 case InputEventType::KEY: {
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004542 const KeyEvent& incomingKey = static_cast<const KeyEvent&>(*event);
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004543 const int32_t action = incomingKey.getAction();
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004544 int32_t flags = incomingKey.getFlags();
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004545 if (policyFlags & POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY) {
4546 flags |= AKEY_EVENT_FLAG_IS_ACCESSIBILITY_EVENT;
4547 }
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004548 int32_t keyCode = incomingKey.getKeyCode();
4549 int32_t metaState = incomingKey.getMetaState();
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004550 KeyEvent keyEvent;
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004551 keyEvent.initialize(incomingKey.getId(), resolvedDeviceId, incomingKey.getSource(),
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004552 incomingKey.getDisplayId(), INVALID_HMAC, action, flags, keyCode,
4553 incomingKey.getScanCode(), metaState, incomingKey.getRepeatCount(),
4554 incomingKey.getDownTime(), incomingKey.getEventTime());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004555
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004556 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
4557 policyFlags |= POLICY_FLAG_VIRTUAL;
Michael Wright2b3c3302018-03-02 17:19:13 +00004558 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004559
4560 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
4561 android::base::Timer t;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004562 mPolicy.interceptKeyBeforeQueueing(keyEvent, /*byref*/ policyFlags);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004563 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4564 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
4565 std::to_string(t.duration().count()).c_str());
4566 }
4567 }
4568
4569 mLock.lock();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004570 std::unique_ptr<KeyEntry> injectedEntry =
4571 std::make_unique<KeyEntry>(incomingKey.getId(), incomingKey.getEventTime(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004572 resolvedDeviceId, incomingKey.getSource(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004573 incomingKey.getDisplayId(), policyFlags, action,
4574 flags, keyCode, incomingKey.getScanCode(), metaState,
4575 incomingKey.getRepeatCount(),
4576 incomingKey.getDownTime());
4577 injectedEntries.push(std::move(injectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004578 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004579 }
4580
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004581 case InputEventType::MOTION: {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004582 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(*event);
Prabir Pradhanaa561d12021-09-24 06:57:33 -07004583 const bool isPointerEvent =
4584 isFromSource(event->getSource(), AINPUT_SOURCE_CLASS_POINTER);
4585 // If a pointer event has no displayId specified, inject it to the default display.
4586 const uint32_t displayId = isPointerEvent && (event->getDisplayId() == ADISPLAY_ID_NONE)
4587 ? ADISPLAY_ID_DEFAULT
4588 : event->getDisplayId();
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004589 int32_t flags = motionEvent.getFlags();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004590
4591 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004592 nsecs_t eventTime = motionEvent.getEventTime();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004593 android::base::Timer t;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004594 mPolicy.interceptMotionBeforeQueueing(displayId, eventTime, /*byref*/ policyFlags);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004595 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4596 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
4597 std::to_string(t.duration().count()).c_str());
4598 }
4599 }
4600
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004601 if (policyFlags & POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY) {
4602 flags |= AMOTION_EVENT_FLAG_IS_ACCESSIBILITY_EVENT;
4603 }
4604
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004605 mLock.lock();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004606 const nsecs_t* sampleEventTimes = motionEvent.getSampleEventTimes();
4607 const PointerCoords* samplePointerCoords = motionEvent.getSamplePointerCoords();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004608 std::unique_ptr<MotionEntry> injectedEntry =
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004609 std::make_unique<MotionEntry>(motionEvent.getId(), *sampleEventTimes,
4610 resolvedDeviceId, motionEvent.getSource(),
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004611 displayId, policyFlags, motionEvent.getAction(),
4612 motionEvent.getActionButton(), flags,
4613 motionEvent.getMetaState(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004614 motionEvent.getButtonState(),
4615 motionEvent.getClassification(),
4616 motionEvent.getEdgeFlags(),
4617 motionEvent.getXPrecision(),
4618 motionEvent.getYPrecision(),
4619 motionEvent.getRawXCursorPosition(),
4620 motionEvent.getRawYCursorPosition(),
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004621 motionEvent.getDownTime(),
4622 motionEvent.getPointerCount(),
4623 motionEvent.getPointerProperties(),
4624 samplePointerCoords);
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004625 transformMotionEntryForInjectionLocked(*injectedEntry, motionEvent.getTransform());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004626 injectedEntries.push(std::move(injectedEntry));
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004627 for (size_t i = motionEvent.getHistorySize(); i > 0; i--) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004628 sampleEventTimes += 1;
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004629 samplePointerCoords += motionEvent.getPointerCount();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004630 std::unique_ptr<MotionEntry> nextInjectedEntry =
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004631 std::make_unique<MotionEntry>(motionEvent.getId(), *sampleEventTimes,
4632 resolvedDeviceId, motionEvent.getSource(),
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004633 displayId, policyFlags,
4634 motionEvent.getAction(),
4635 motionEvent.getActionButton(), flags,
4636 motionEvent.getMetaState(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004637 motionEvent.getButtonState(),
4638 motionEvent.getClassification(),
4639 motionEvent.getEdgeFlags(),
4640 motionEvent.getXPrecision(),
4641 motionEvent.getYPrecision(),
4642 motionEvent.getRawXCursorPosition(),
4643 motionEvent.getRawYCursorPosition(),
4644 motionEvent.getDownTime(),
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004645 motionEvent.getPointerCount(),
4646 motionEvent.getPointerProperties(),
Prabir Pradhan5beda762021-12-10 09:30:08 +00004647 samplePointerCoords);
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004648 transformMotionEntryForInjectionLocked(*nextInjectedEntry,
4649 motionEvent.getTransform());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004650 injectedEntries.push(std::move(nextInjectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004651 }
4652 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004653 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004654
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004655 default:
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004656 LOG(WARNING) << "Cannot inject " << ftl::enum_string(event->getType()) << " events";
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004657 return InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004658 }
4659
Prabir Pradhan5735a322022-04-11 17:23:34 +00004660 InjectionState* injectionState = new InjectionState(targetUid);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004661 if (syncMode == InputEventInjectionSync::NONE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004662 injectionState->injectionIsAsync = true;
4663 }
4664
4665 injectionState->refCount += 1;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004666 injectedEntries.back()->injectionState = injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004667
4668 bool needWake = false;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004669 while (!injectedEntries.empty()) {
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08004670 if (DEBUG_INJECTION) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07004671 LOG(INFO) << "Injecting " << injectedEntries.front()->getDescription();
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08004672 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004673 needWake |= enqueueInboundEventLocked(std::move(injectedEntries.front()));
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004674 injectedEntries.pop();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004675 }
4676
4677 mLock.unlock();
4678
4679 if (needWake) {
4680 mLooper->wake();
4681 }
4682
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004683 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004684 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004685 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004686
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004687 if (syncMode == InputEventInjectionSync::NONE) {
4688 injectionResult = InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004689 } else {
4690 for (;;) {
4691 injectionResult = injectionState->injectionResult;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004692 if (injectionResult != InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004693 break;
4694 }
4695
4696 nsecs_t remainingTimeout = endTime - now();
4697 if (remainingTimeout <= 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004698 if (DEBUG_INJECTION) {
4699 ALOGD("injectInputEvent - Timed out waiting for injection result "
4700 "to become available.");
4701 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004702 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004703 break;
4704 }
4705
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004706 mInjectionResultAvailable.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004707 }
4708
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004709 if (injectionResult == InputEventInjectionResult::SUCCEEDED &&
4710 syncMode == InputEventInjectionSync::WAIT_FOR_FINISHED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004711 while (injectionState->pendingForegroundDispatches != 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004712 if (DEBUG_INJECTION) {
4713 ALOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
4714 injectionState->pendingForegroundDispatches);
4715 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004716 nsecs_t remainingTimeout = endTime - now();
4717 if (remainingTimeout <= 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004718 if (DEBUG_INJECTION) {
4719 ALOGD("injectInputEvent - Timed out waiting for pending foreground "
4720 "dispatches to finish.");
4721 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004722 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004723 break;
4724 }
4725
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004726 mInjectionSyncFinished.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004727 }
4728 }
4729 }
4730
4731 injectionState->release();
4732 } // release lock
4733
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004734 if (DEBUG_INJECTION) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07004735 LOG(INFO) << "injectInputEvent - Finished with result "
4736 << ftl::enum_string(injectionResult);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004737 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004738
4739 return injectionResult;
4740}
4741
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004742std::unique_ptr<VerifiedInputEvent> InputDispatcher::verifyInputEvent(const InputEvent& event) {
Gang Wange9087892020-01-07 12:17:14 -05004743 std::array<uint8_t, 32> calculatedHmac;
4744 std::unique_ptr<VerifiedInputEvent> result;
4745 switch (event.getType()) {
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004746 case InputEventType::KEY: {
Gang Wange9087892020-01-07 12:17:14 -05004747 const KeyEvent& keyEvent = static_cast<const KeyEvent&>(event);
4748 VerifiedKeyEvent verifiedKeyEvent = verifiedKeyEventFromKeyEvent(keyEvent);
4749 result = std::make_unique<VerifiedKeyEvent>(verifiedKeyEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004750 calculatedHmac = sign(verifiedKeyEvent);
Gang Wange9087892020-01-07 12:17:14 -05004751 break;
4752 }
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004753 case InputEventType::MOTION: {
Gang Wange9087892020-01-07 12:17:14 -05004754 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(event);
4755 VerifiedMotionEvent verifiedMotionEvent =
4756 verifiedMotionEventFromMotionEvent(motionEvent);
4757 result = std::make_unique<VerifiedMotionEvent>(verifiedMotionEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004758 calculatedHmac = sign(verifiedMotionEvent);
Gang Wange9087892020-01-07 12:17:14 -05004759 break;
4760 }
4761 default: {
4762 ALOGE("Cannot verify events of type %" PRId32, event.getType());
4763 return nullptr;
4764 }
4765 }
4766 if (calculatedHmac == INVALID_HMAC) {
4767 return nullptr;
4768 }
tyiu1573a672023-02-21 22:38:32 +00004769 if (0 != CRYPTO_memcmp(calculatedHmac.data(), event.getHmac().data(), calculatedHmac.size())) {
Gang Wange9087892020-01-07 12:17:14 -05004770 return nullptr;
4771 }
4772 return result;
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004773}
4774
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004775void InputDispatcher::setInjectionResult(EventEntry& entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004776 InputEventInjectionResult injectionResult) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004777 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004778 if (injectionState) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004779 if (DEBUG_INJECTION) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07004780 LOG(INFO) << "Setting input event injection result to "
4781 << ftl::enum_string(injectionResult);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004782 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004783
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004784 if (injectionState->injectionIsAsync && !(entry.policyFlags & POLICY_FLAG_FILTERED)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004785 // Log the outcome since the injector did not wait for the injection result.
4786 switch (injectionResult) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004787 case InputEventInjectionResult::SUCCEEDED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004788 ALOGV("Asynchronous input event injection succeeded.");
4789 break;
Prabir Pradhan5735a322022-04-11 17:23:34 +00004790 case InputEventInjectionResult::TARGET_MISMATCH:
4791 ALOGV("Asynchronous input event injection target mismatch.");
4792 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004793 case InputEventInjectionResult::FAILED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004794 ALOGW("Asynchronous input event injection failed.");
4795 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004796 case InputEventInjectionResult::TIMED_OUT:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004797 ALOGW("Asynchronous input event injection timed out.");
4798 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004799 case InputEventInjectionResult::PENDING:
4800 ALOGE("Setting result to 'PENDING' for asynchronous injection");
4801 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004802 }
4803 }
4804
4805 injectionState->injectionResult = injectionResult;
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004806 mInjectionResultAvailable.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004807 }
4808}
4809
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004810void InputDispatcher::transformMotionEntryForInjectionLocked(
4811 MotionEntry& entry, const ui::Transform& injectedTransform) const {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004812 // Input injection works in the logical display coordinate space, but the input pipeline works
4813 // display space, so we need to transform the injected events accordingly.
4814 const auto it = mDisplayInfos.find(entry.displayId);
4815 if (it == mDisplayInfos.end()) return;
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004816 const auto& transformToDisplay = it->second.transform.inverse() * injectedTransform;
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004817
Prabir Pradhand9a2ebe2022-07-20 19:25:13 +00004818 if (entry.xCursorPosition != AMOTION_EVENT_INVALID_CURSOR_POSITION &&
4819 entry.yCursorPosition != AMOTION_EVENT_INVALID_CURSOR_POSITION) {
4820 const vec2 cursor =
4821 MotionEvent::calculateTransformedXY(entry.source, transformToDisplay,
4822 {entry.xCursorPosition, entry.yCursorPosition});
4823 entry.xCursorPosition = cursor.x;
4824 entry.yCursorPosition = cursor.y;
4825 }
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004826 for (uint32_t i = 0; i < entry.pointerCount; i++) {
Prabir Pradhan8e6ce222022-02-24 09:08:54 -08004827 entry.pointerCoords[i] =
4828 MotionEvent::calculateTransformedCoords(entry.source, transformToDisplay,
4829 entry.pointerCoords[i]);
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004830 }
4831}
4832
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004833void InputDispatcher::incrementPendingForegroundDispatches(EventEntry& entry) {
4834 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004835 if (injectionState) {
4836 injectionState->pendingForegroundDispatches += 1;
4837 }
4838}
4839
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004840void InputDispatcher::decrementPendingForegroundDispatches(EventEntry& entry) {
4841 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004842 if (injectionState) {
4843 injectionState->pendingForegroundDispatches -= 1;
4844
4845 if (injectionState->pendingForegroundDispatches == 0) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004846 mInjectionSyncFinished.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004847 }
4848 }
4849}
4850
chaviw98318de2021-05-19 16:45:23 -05004851const std::vector<sp<WindowInfoHandle>>& InputDispatcher::getWindowHandlesLocked(
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004852 int32_t displayId) const {
chaviw98318de2021-05-19 16:45:23 -05004853 static const std::vector<sp<WindowInfoHandle>> EMPTY_WINDOW_HANDLES;
Vishnu Nairad321cd2020-08-20 16:40:21 -07004854 auto it = mWindowHandlesByDisplay.find(displayId);
4855 return it != mWindowHandlesByDisplay.end() ? it->second : EMPTY_WINDOW_HANDLES;
Arthur Hungb92218b2018-08-14 12:00:21 +08004856}
4857
chaviw98318de2021-05-19 16:45:23 -05004858sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(
chaviwfbe5d9c2018-12-26 12:23:37 -08004859 const sp<IBinder>& windowHandleToken) const {
arthurhungbe737672020-06-24 12:29:21 +08004860 if (windowHandleToken == nullptr) {
4861 return nullptr;
4862 }
4863
Arthur Hungb92218b2018-08-14 12:00:21 +08004864 for (auto& it : mWindowHandlesByDisplay) {
chaviw98318de2021-05-19 16:45:23 -05004865 const std::vector<sp<WindowInfoHandle>>& windowHandles = it.second;
4866 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
chaviwfbe5d9c2018-12-26 12:23:37 -08004867 if (windowHandle->getToken() == windowHandleToken) {
Arthur Hungb92218b2018-08-14 12:00:21 +08004868 return windowHandle;
4869 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004870 }
4871 }
Yi Kong9b14ac62018-07-17 13:48:38 -07004872 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004873}
4874
chaviw98318de2021-05-19 16:45:23 -05004875sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(const sp<IBinder>& windowHandleToken,
4876 int displayId) const {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004877 if (windowHandleToken == nullptr) {
4878 return nullptr;
4879 }
4880
chaviw98318de2021-05-19 16:45:23 -05004881 for (const sp<WindowInfoHandle>& windowHandle : getWindowHandlesLocked(displayId)) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004882 if (windowHandle->getToken() == windowHandleToken) {
4883 return windowHandle;
4884 }
4885 }
4886 return nullptr;
4887}
4888
chaviw98318de2021-05-19 16:45:23 -05004889sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(
4890 const sp<WindowInfoHandle>& windowHandle) const {
Mady Mellor017bcd12020-06-23 19:12:00 +00004891 for (auto& it : mWindowHandlesByDisplay) {
chaviw98318de2021-05-19 16:45:23 -05004892 const std::vector<sp<WindowInfoHandle>>& windowHandles = it.second;
4893 for (const sp<WindowInfoHandle>& handle : windowHandles) {
arthurhungbe737672020-06-24 12:29:21 +08004894 if (handle->getId() == windowHandle->getId() &&
4895 handle->getToken() == windowHandle->getToken()) {
Mady Mellor017bcd12020-06-23 19:12:00 +00004896 if (windowHandle->getInfo()->displayId != it.first) {
4897 ALOGE("Found window %s in display %" PRId32
4898 ", but it should belong to display %" PRId32,
4899 windowHandle->getName().c_str(), it.first,
4900 windowHandle->getInfo()->displayId);
4901 }
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004902 return handle;
Arthur Hungb92218b2018-08-14 12:00:21 +08004903 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004904 }
4905 }
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004906 return nullptr;
4907}
4908
chaviw98318de2021-05-19 16:45:23 -05004909sp<WindowInfoHandle> InputDispatcher::getFocusedWindowHandleLocked(int displayId) const {
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004910 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(displayId);
4911 return getWindowHandleLocked(focusedToken, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004912}
4913
Prabir Pradhan33e3baa2022-12-06 20:30:22 +00004914ui::Transform InputDispatcher::getTransformLocked(int32_t displayId) const {
4915 auto displayInfoIt = mDisplayInfos.find(displayId);
4916 return displayInfoIt != mDisplayInfos.end() ? displayInfoIt->second.transform
4917 : kIdentityTransform;
4918}
4919
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004920bool InputDispatcher::canWindowReceiveMotionLocked(const sp<WindowInfoHandle>& window,
4921 const MotionEntry& motionEntry) const {
4922 const WindowInfo& info = *window->getInfo();
4923
4924 // Skip spy window targets that are not valid for targeted injection.
4925 if (const auto err = verifyTargetedInjection(window, motionEntry); err) {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004926 return false;
4927 }
4928
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004929 if (info.inputConfig.test(WindowInfo::InputConfig::PAUSE_DISPATCHING)) {
4930 ALOGI("Not sending touch event to %s because it is paused", window->getName().c_str());
4931 return false;
4932 }
4933
4934 if (info.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL)) {
4935 ALOGW("Not sending touch gesture to %s because it has config NO_INPUT_CHANNEL",
4936 window->getName().c_str());
4937 return false;
4938 }
4939
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07004940 std::shared_ptr<Connection> connection = getConnectionLocked(window->getToken());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004941 if (connection == nullptr) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004942 ALOGW("Not sending touch to %s because there's no corresponding connection",
4943 window->getName().c_str());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004944 return false;
4945 }
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004946
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004947 if (!connection->responsive) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004948 ALOGW("Not sending touch to %s because it is not responsive", window->getName().c_str());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004949 return false;
4950 }
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004951
4952 // Drop events that can't be trusted due to occlusion
4953 const auto [x, y] = resolveTouchedPosition(motionEntry);
4954 TouchOcclusionInfo occlusionInfo = computeTouchOcclusionInfoLocked(window, x, y);
4955 if (!isTouchTrustedLocked(occlusionInfo)) {
4956 if (DEBUG_TOUCH_OCCLUSION) {
Prabir Pradhan82e081e2022-12-06 09:50:09 +00004957 ALOGD("Stack of obscuring windows during untrusted touch (%.1f, %.1f):", x, y);
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004958 for (const auto& log : occlusionInfo.debugInfo) {
4959 ALOGD("%s", log.c_str());
4960 }
4961 }
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00004962 ALOGW("Dropping untrusted touch event due to %s/%s", occlusionInfo.obscuringPackage.c_str(),
4963 occlusionInfo.obscuringUid.toString().c_str());
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004964 return false;
4965 }
4966
4967 // Drop touch events if requested by input feature
4968 if (shouldDropInput(motionEntry, window)) {
4969 return false;
4970 }
4971
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004972 return true;
4973}
4974
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004975std::shared_ptr<InputChannel> InputDispatcher::getInputChannelLocked(
4976 const sp<IBinder>& token) const {
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00004977 auto connectionIt = mConnectionsByToken.find(token);
4978 if (connectionIt == mConnectionsByToken.end()) {
Robert Carr5c8a0262018-10-03 16:30:44 -07004979 return nullptr;
4980 }
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00004981 return connectionIt->second->inputChannel;
Robert Carr5c8a0262018-10-03 16:30:44 -07004982}
4983
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004984void InputDispatcher::updateWindowHandlesForDisplayLocked(
chaviw98318de2021-05-19 16:45:23 -05004985 const std::vector<sp<WindowInfoHandle>>& windowInfoHandles, int32_t displayId) {
4986 if (windowInfoHandles.empty()) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004987 // Remove all handles on a display if there are no windows left.
4988 mWindowHandlesByDisplay.erase(displayId);
4989 return;
4990 }
4991
4992 // Since we compare the pointer of input window handles across window updates, we need
4993 // to make sure the handle object for the same window stays unchanged across updates.
chaviw98318de2021-05-19 16:45:23 -05004994 const std::vector<sp<WindowInfoHandle>>& oldHandles = getWindowHandlesLocked(displayId);
4995 std::unordered_map<int32_t /*id*/, sp<WindowInfoHandle>> oldHandlesById;
4996 for (const sp<WindowInfoHandle>& handle : oldHandles) {
chaviwaf87b3e2019-10-01 16:59:28 -07004997 oldHandlesById[handle->getId()] = handle;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004998 }
4999
chaviw98318de2021-05-19 16:45:23 -05005000 std::vector<sp<WindowInfoHandle>> newHandles;
5001 for (const sp<WindowInfoHandle>& handle : windowInfoHandles) {
chaviw98318de2021-05-19 16:45:23 -05005002 const WindowInfo* info = handle->getInfo();
Siarhei Vishniakou64452932020-11-06 17:51:32 -06005003 if (getInputChannelLocked(handle->getToken()) == nullptr) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005004 const bool noInputChannel =
Prabir Pradhan51e7db02022-02-07 06:02:57 -08005005 info->inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005006 const bool canReceiveInput =
5007 !info->inputConfig.test(WindowInfo::InputConfig::NOT_TOUCHABLE) ||
5008 !info->inputConfig.test(WindowInfo::InputConfig::NOT_FOCUSABLE);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005009 if (canReceiveInput && !noInputChannel) {
John Recke0710582019-09-26 13:46:12 -07005010 ALOGV("Window handle %s has no registered input channel",
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005011 handle->getName().c_str());
Robert Carr2984b7a2020-04-13 17:06:45 -07005012 continue;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005013 }
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005014 }
5015
5016 if (info->displayId != displayId) {
5017 ALOGE("Window %s updated by wrong display %d, should belong to display %d",
5018 handle->getName().c_str(), displayId, info->displayId);
5019 continue;
5020 }
5021
Robert Carredd13602020-04-13 17:24:34 -07005022 if ((oldHandlesById.find(handle->getId()) != oldHandlesById.end()) &&
5023 (oldHandlesById.at(handle->getId())->getToken() == handle->getToken())) {
chaviw98318de2021-05-19 16:45:23 -05005024 const sp<WindowInfoHandle>& oldHandle = oldHandlesById.at(handle->getId());
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005025 oldHandle->updateFrom(handle);
5026 newHandles.push_back(oldHandle);
5027 } else {
5028 newHandles.push_back(handle);
5029 }
5030 }
5031
5032 // Insert or replace
5033 mWindowHandlesByDisplay[displayId] = newHandles;
5034}
5035
Arthur Hungb92218b2018-08-14 12:00:21 +08005036/**
5037 * Called from InputManagerService, update window handle list by displayId that can receive input.
5038 * A window handle contains information about InputChannel, Touch Region, Types, Focused,...
5039 * If set an empty list, remove all handles from the specific display.
5040 * For focused handle, check if need to change and send a cancel event to previous one.
5041 * For removed handle, check if need to send a cancel event if already in touch.
5042 */
Arthur Hung72d8dc32020-03-28 00:48:39 +00005043void InputDispatcher::setInputWindowsLocked(
chaviw98318de2021-05-19 16:45:23 -05005044 const std::vector<sp<WindowInfoHandle>>& windowInfoHandles, int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005045 if (DEBUG_FOCUS) {
5046 std::string windowList;
chaviw98318de2021-05-19 16:45:23 -05005047 for (const sp<WindowInfoHandle>& iwh : windowInfoHandles) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005048 windowList += iwh->getName() + " ";
5049 }
5050 ALOGD("setInputWindows displayId=%" PRId32 " %s", displayId, windowList.c_str());
5051 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005052
Prabir Pradhand65552b2021-10-07 11:23:50 -07005053 // Check preconditions for new input windows
chaviw98318de2021-05-19 16:45:23 -05005054 for (const sp<WindowInfoHandle>& window : windowInfoHandles) {
Prabir Pradhand65552b2021-10-07 11:23:50 -07005055 const WindowInfo& info = *window->getInfo();
5056
5057 // Ensure all tokens are null if the window has feature NO_INPUT_CHANNEL
Prabir Pradhan51e7db02022-02-07 06:02:57 -08005058 const bool noInputWindow = info.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005059 if (noInputWindow && window->getToken() != nullptr) {
5060 ALOGE("%s has feature NO_INPUT_WINDOW, but a non-null token. Clearing",
5061 window->getName().c_str());
5062 window->releaseChannel();
5063 }
Prabir Pradhand65552b2021-10-07 11:23:50 -07005064
Prabir Pradhan5c85e052021-12-22 02:27:12 -08005065 // Ensure all spy windows are trusted overlays
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005066 LOG_ALWAYS_FATAL_IF(info.isSpy() &&
5067 !info.inputConfig.test(
5068 WindowInfo::InputConfig::TRUSTED_OVERLAY),
Prabir Pradhan5c85e052021-12-22 02:27:12 -08005069 "%s has feature SPY, but is not a trusted overlay.",
5070 window->getName().c_str());
5071
Prabir Pradhand65552b2021-10-07 11:23:50 -07005072 // Ensure all stylus interceptors are trusted overlays
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005073 LOG_ALWAYS_FATAL_IF(info.interceptsStylus() &&
5074 !info.inputConfig.test(
5075 WindowInfo::InputConfig::TRUSTED_OVERLAY),
Prabir Pradhand65552b2021-10-07 11:23:50 -07005076 "%s has feature INTERCEPTS_STYLUS, but is not a trusted overlay.",
5077 window->getName().c_str());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005078 }
5079
Arthur Hung72d8dc32020-03-28 00:48:39 +00005080 // Copy old handles for release if they are no longer present.
chaviw98318de2021-05-19 16:45:23 -05005081 const std::vector<sp<WindowInfoHandle>> oldWindowHandles = getWindowHandlesLocked(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005082
chaviw98318de2021-05-19 16:45:23 -05005083 updateWindowHandlesForDisplayLocked(windowInfoHandles, displayId);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005084
chaviw98318de2021-05-19 16:45:23 -05005085 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Arthur Hung72d8dc32020-03-28 00:48:39 +00005086
Vishnu Nairc519ff72021-01-21 08:23:08 -08005087 std::optional<FocusResolver::FocusChanges> changes =
5088 mFocusResolver.setInputWindows(displayId, windowHandles);
5089 if (changes) {
5090 onFocusChangedLocked(*changes);
Arthur Hung72d8dc32020-03-28 00:48:39 +00005091 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005092
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005093 std::unordered_map<int32_t, TouchState>::iterator stateIt =
5094 mTouchStatesByDisplay.find(displayId);
5095 if (stateIt != mTouchStatesByDisplay.end()) {
5096 TouchState& state = stateIt->second;
Arthur Hung72d8dc32020-03-28 00:48:39 +00005097 for (size_t i = 0; i < state.windows.size();) {
5098 TouchedWindow& touchedWindow = state.windows[i];
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07005099 if (getWindowHandleLocked(touchedWindow.windowHandle) == nullptr) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005100 if (DEBUG_FOCUS) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00005101 ALOGD("Touched window was removed: %s in display %" PRId32,
5102 touchedWindow.windowHandle->getName().c_str(), displayId);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005103 }
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005104 std::shared_ptr<InputChannel> touchedInputChannel =
Arthur Hung72d8dc32020-03-28 00:48:39 +00005105 getInputChannelLocked(touchedWindow.windowHandle->getToken());
5106 if (touchedInputChannel != nullptr) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00005107 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
Arthur Hung72d8dc32020-03-28 00:48:39 +00005108 "touched window was removed");
5109 synthesizeCancelationEventsForInputChannelLocked(touchedInputChannel, options);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00005110 // Since we are about to drop the touch, cancel the events for the wallpaper as
5111 // well.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005112 if (touchedWindow.targetFlags.test(InputTarget::Flags::FOREGROUND) &&
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005113 touchedWindow.windowHandle->getInfo()->inputConfig.test(
5114 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER)) {
Siarhei Vishniakouca205502021-07-16 21:31:58 +00005115 sp<WindowInfoHandle> wallpaper = state.getWallpaperWindow();
Arthur Hungc539dbb2022-12-08 07:45:36 +00005116 synthesizeCancelationEventsForWindowLocked(wallpaper, options);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00005117 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005118 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00005119 state.windows.erase(state.windows.begin() + i);
5120 } else {
5121 ++i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005122 }
5123 }
arthurhungb89ccb02020-12-30 16:19:01 +08005124
arthurhung6d4bed92021-03-17 11:59:33 +08005125 // If drag window is gone, it would receive a cancel event and broadcast the DRAG_END. We
arthurhungb89ccb02020-12-30 16:19:01 +08005126 // could just clear the state here.
Arthur Hung3915c1f2022-05-31 07:17:17 +00005127 if (mDragState && mDragState->dragWindow->getInfo()->displayId == displayId &&
arthurhung6d4bed92021-03-17 11:59:33 +08005128 std::find(windowHandles.begin(), windowHandles.end(), mDragState->dragWindow) ==
arthurhungb89ccb02020-12-30 16:19:01 +08005129 windowHandles.end()) {
Arthur Hung3915c1f2022-05-31 07:17:17 +00005130 ALOGI("Drag window went away: %s", mDragState->dragWindow->getName().c_str());
5131 sendDropWindowCommandLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08005132 mDragState.reset();
arthurhungb89ccb02020-12-30 16:19:01 +08005133 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00005134 }
Arthur Hung25e2af12020-03-26 12:58:37 +00005135
Arthur Hung72d8dc32020-03-28 00:48:39 +00005136 // Release information for windows that are no longer present.
5137 // This ensures that unused input channels are released promptly.
5138 // Otherwise, they might stick around until the window handle is destroyed
5139 // which might not happen until the next GC.
chaviw98318de2021-05-19 16:45:23 -05005140 for (const sp<WindowInfoHandle>& oldWindowHandle : oldWindowHandles) {
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07005141 if (getWindowHandleLocked(oldWindowHandle) == nullptr) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00005142 if (DEBUG_FOCUS) {
5143 ALOGD("Window went away: %s", oldWindowHandle->getName().c_str());
Arthur Hung25e2af12020-03-26 12:58:37 +00005144 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00005145 oldWindowHandle->releaseChannel();
Arthur Hung25e2af12020-03-26 12:58:37 +00005146 }
chaviw291d88a2019-02-14 10:33:58 -08005147 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005148}
5149
5150void InputDispatcher::setFocusedApplication(
Chris Yea209fde2020-07-22 13:54:51 -07005151 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005152 if (DEBUG_FOCUS) {
5153 ALOGD("setFocusedApplication displayId=%" PRId32 " %s", displayId,
5154 inputApplicationHandle ? inputApplicationHandle->getName().c_str() : "<nullptr>");
5155 }
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05005156 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005157 std::scoped_lock _l(mLock);
Vishnu Nair599f1412021-06-21 10:39:58 -07005158 setFocusedApplicationLocked(displayId, inputApplicationHandle);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005159 } // release lock
5160
5161 // Wake up poll loop since it may need to make new input dispatching choices.
5162 mLooper->wake();
5163}
5164
Vishnu Nair599f1412021-06-21 10:39:58 -07005165void InputDispatcher::setFocusedApplicationLocked(
5166 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
5167 std::shared_ptr<InputApplicationHandle> oldFocusedApplicationHandle =
5168 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
5169
5170 if (sharedPointersEqual(oldFocusedApplicationHandle, inputApplicationHandle)) {
5171 return; // This application is already focused. No need to wake up or change anything.
5172 }
5173
5174 // Set the new application handle.
5175 if (inputApplicationHandle != nullptr) {
5176 mFocusedApplicationHandlesByDisplay[displayId] = inputApplicationHandle;
5177 } else {
5178 mFocusedApplicationHandlesByDisplay.erase(displayId);
5179 }
5180
5181 // No matter what the old focused application was, stop waiting on it because it is
5182 // no longer focused.
5183 resetNoFocusedWindowTimeoutLocked();
5184}
5185
Tiger Huang721e26f2018-07-24 22:26:19 +08005186/**
5187 * Sets the focused display, which is responsible for receiving focus-dispatched input events where
5188 * the display not specified.
5189 *
5190 * We track any unreleased events for each window. If a window loses the ability to receive the
5191 * released event, we will send a cancel event to it. So when the focused display is changed, we
5192 * cancel all the unreleased display-unspecified events for the focused window on the old focused
5193 * display. The display-specified events won't be affected.
5194 */
5195void InputDispatcher::setFocusedDisplay(int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005196 if (DEBUG_FOCUS) {
5197 ALOGD("setFocusedDisplay displayId=%" PRId32, displayId);
5198 }
Tiger Huang721e26f2018-07-24 22:26:19 +08005199 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005200 std::scoped_lock _l(mLock);
Tiger Huang721e26f2018-07-24 22:26:19 +08005201
5202 if (mFocusedDisplayId != displayId) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07005203 sp<IBinder> oldFocusedWindowToken =
Vishnu Nairc519ff72021-01-21 08:23:08 -08005204 mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07005205 if (oldFocusedWindowToken != nullptr) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005206 std::shared_ptr<InputChannel> inputChannel =
Vishnu Nairad321cd2020-08-20 16:40:21 -07005207 getInputChannelLocked(oldFocusedWindowToken);
Tiger Huang721e26f2018-07-24 22:26:19 +08005208 if (inputChannel != nullptr) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005209 CancelationOptions
Michael Wrightfb04fd52022-11-24 22:31:11 +00005210 options(CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005211 "The display which contains this window no longer has focus.");
Michael Wright3dd60e22019-03-27 22:06:44 +00005212 options.displayId = ADISPLAY_ID_NONE;
Tiger Huang721e26f2018-07-24 22:26:19 +08005213 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
5214 }
5215 }
5216 mFocusedDisplayId = displayId;
5217
Chris Ye3c2d6f52020-08-09 10:39:48 -07005218 // Find new focused window and validate
Vishnu Nairc519ff72021-01-21 08:23:08 -08005219 sp<IBinder> newFocusedWindowToken = mFocusResolver.getFocusedWindowToken(displayId);
Prabir Pradhancef936d2021-07-21 16:17:52 +00005220 sendFocusChangedCommandLocked(oldFocusedWindowToken, newFocusedWindowToken);
Robert Carrf759f162018-11-13 12:57:11 -08005221
Vishnu Nairad321cd2020-08-20 16:40:21 -07005222 if (newFocusedWindowToken == nullptr) {
Tiger Huang721e26f2018-07-24 22:26:19 +08005223 ALOGW("Focused display #%" PRId32 " does not have a focused window.", displayId);
Vishnu Nairc519ff72021-01-21 08:23:08 -08005224 if (mFocusResolver.hasFocusedWindowTokens()) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07005225 ALOGE("But another display has a focused window\n%s",
Vishnu Nairc519ff72021-01-21 08:23:08 -08005226 mFocusResolver.dumpFocusedWindows().c_str());
Tiger Huang721e26f2018-07-24 22:26:19 +08005227 }
5228 }
5229 }
Tiger Huang721e26f2018-07-24 22:26:19 +08005230 } // release lock
5231
5232 // Wake up poll loop since it may need to make new input dispatching choices.
5233 mLooper->wake();
5234}
5235
Michael Wrightd02c5b62014-02-10 15:10:22 -08005236void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005237 if (DEBUG_FOCUS) {
5238 ALOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
5239 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005240
5241 bool changed;
5242 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005243 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005244
5245 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
5246 if (mDispatchFrozen && !frozen) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005247 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005248 }
5249
5250 if (mDispatchEnabled && !enabled) {
5251 resetAndDropEverythingLocked("dispatcher is being disabled");
5252 }
5253
5254 mDispatchEnabled = enabled;
5255 mDispatchFrozen = frozen;
5256 changed = true;
5257 } else {
5258 changed = false;
5259 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005260 } // release lock
5261
5262 if (changed) {
5263 // Wake up poll loop since it may need to make new input dispatching choices.
5264 mLooper->wake();
5265 }
5266}
5267
5268void InputDispatcher::setInputFilterEnabled(bool enabled) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005269 if (DEBUG_FOCUS) {
5270 ALOGD("setInputFilterEnabled: enabled=%d", enabled);
5271 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005272
5273 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005274 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005275
5276 if (mInputFilterEnabled == enabled) {
5277 return;
5278 }
5279
5280 mInputFilterEnabled = enabled;
5281 resetAndDropEverythingLocked("input filter is being enabled or disabled");
5282 } // release lock
5283
5284 // Wake up poll loop since there might be work to do to drop everything.
5285 mLooper->wake();
5286}
5287
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005288bool InputDispatcher::setInTouchMode(bool inTouchMode, gui::Pid pid, gui::Uid uid,
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00005289 bool hasPermission, int32_t displayId) {
Antonio Kantekf16f2832021-09-28 04:39:20 +00005290 bool needWake = false;
5291 {
5292 std::scoped_lock lock(mLock);
Antonio Kantek15beb512022-06-13 22:35:41 +00005293 ALOGD_IF(DEBUG_TOUCH_MODE,
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005294 "Request to change touch mode to %s (calling pid=%s, uid=%s, "
Antonio Kantek15beb512022-06-13 22:35:41 +00005295 "hasPermission=%s, target displayId=%d, mTouchModePerDisplay[displayId]=%s)",
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005296 toString(inTouchMode), pid.toString().c_str(), uid.toString().c_str(),
5297 toString(hasPermission), displayId,
Antonio Kantek15beb512022-06-13 22:35:41 +00005298 mTouchModePerDisplay.count(displayId) == 0
5299 ? "not set"
5300 : std::to_string(mTouchModePerDisplay[displayId]).c_str());
5301
Antonio Kantek15beb512022-06-13 22:35:41 +00005302 auto touchModeIt = mTouchModePerDisplay.find(displayId);
5303 if (touchModeIt != mTouchModePerDisplay.end() && touchModeIt->second == inTouchMode) {
Antonio Kantekea47acb2021-12-23 12:41:25 -08005304 return false;
Antonio Kantekf16f2832021-09-28 04:39:20 +00005305 }
Antonio Kantekea47acb2021-12-23 12:41:25 -08005306 if (!hasPermission) {
Antonio Kantek48710e42022-03-24 14:19:30 -07005307 if (!focusedWindowIsOwnedByLocked(pid, uid) &&
5308 !recentWindowsAreOwnedByLocked(pid, uid)) {
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005309 ALOGD("Touch mode switch rejected, caller (pid=%s, uid=%s) doesn't own the focused "
Antonio Kantek48710e42022-03-24 14:19:30 -07005310 "window nor none of the previously interacted window",
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005311 pid.toString().c_str(), uid.toString().c_str());
Antonio Kantekea47acb2021-12-23 12:41:25 -08005312 return false;
5313 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00005314 }
Antonio Kantek15beb512022-06-13 22:35:41 +00005315 mTouchModePerDisplay[displayId] = inTouchMode;
5316 auto entry = std::make_unique<TouchModeEntry>(mIdGenerator.nextId(), now(), inTouchMode,
5317 displayId);
Antonio Kantekf16f2832021-09-28 04:39:20 +00005318 needWake = enqueueInboundEventLocked(std::move(entry));
5319 } // release lock
5320
5321 if (needWake) {
5322 mLooper->wake();
5323 }
Antonio Kantekea47acb2021-12-23 12:41:25 -08005324 return true;
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -08005325}
5326
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005327bool InputDispatcher::focusedWindowIsOwnedByLocked(gui::Pid pid, gui::Uid uid) {
Antonio Kantek48710e42022-03-24 14:19:30 -07005328 const sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
5329 if (focusedToken == nullptr) {
5330 return false;
5331 }
5332 sp<WindowInfoHandle> windowHandle = getWindowHandleLocked(focusedToken);
5333 return isWindowOwnedBy(windowHandle, pid, uid);
5334}
5335
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005336bool InputDispatcher::recentWindowsAreOwnedByLocked(gui::Pid pid, gui::Uid uid) {
Antonio Kantek48710e42022-03-24 14:19:30 -07005337 return std::find_if(mInteractionConnectionTokens.begin(), mInteractionConnectionTokens.end(),
5338 [&](const sp<IBinder>& connectionToken) REQUIRES(mLock) {
5339 const sp<WindowInfoHandle> windowHandle =
5340 getWindowHandleLocked(connectionToken);
5341 return isWindowOwnedBy(windowHandle, pid, uid);
5342 }) != mInteractionConnectionTokens.end();
5343}
5344
Bernardo Rufinoea97d182020-08-19 14:43:14 +01005345void InputDispatcher::setMaximumObscuringOpacityForTouch(float opacity) {
5346 if (opacity < 0 || opacity > 1) {
5347 LOG_ALWAYS_FATAL("Maximum obscuring opacity for touch should be >= 0 and <= 1");
5348 return;
5349 }
5350
5351 std::scoped_lock lock(mLock);
5352 mMaximumObscuringOpacityForTouch = opacity;
5353}
5354
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005355std::tuple<TouchState*, TouchedWindow*, int32_t /*displayId*/>
5356InputDispatcher::findTouchStateWindowAndDisplayLocked(const sp<IBinder>& token) {
Arthur Hungabbb9d82021-09-01 14:52:30 +00005357 for (auto& [displayId, state] : mTouchStatesByDisplay) {
5358 for (TouchedWindow& w : state.windows) {
5359 if (w.windowHandle->getToken() == token) {
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005360 return std::make_tuple(&state, &w, displayId);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005361 }
5362 }
5363 }
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005364 return std::make_tuple(nullptr, nullptr, ADISPLAY_ID_DEFAULT);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005365}
5366
arthurhungb89ccb02020-12-30 16:19:01 +08005367bool InputDispatcher::transferTouchFocus(const sp<IBinder>& fromToken, const sp<IBinder>& toToken,
5368 bool isDragDrop) {
chaviwfbe5d9c2018-12-26 12:23:37 -08005369 if (fromToken == toToken) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005370 if (DEBUG_FOCUS) {
5371 ALOGD("Trivial transfer to same window.");
5372 }
chaviwfbe5d9c2018-12-26 12:23:37 -08005373 return true;
5374 }
5375
Michael Wrightd02c5b62014-02-10 15:10:22 -08005376 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005377 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005378
Arthur Hungabbb9d82021-09-01 14:52:30 +00005379 // Find the target touch state and touched window by fromToken.
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005380 auto [state, touchedWindow, displayId] = findTouchStateWindowAndDisplayLocked(fromToken);
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005381
Arthur Hungabbb9d82021-09-01 14:52:30 +00005382 if (state == nullptr || touchedWindow == nullptr) {
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005383 ALOGD("Touch transfer failed because from window is not being touched.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005384 return false;
5385 }
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005386 std::set<int32_t> deviceIds = touchedWindow->getTouchingDeviceIds();
5387 if (deviceIds.size() != 1) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07005388 LOG(INFO) << "Can't transfer touch. Currently touching devices: " << dumpSet(deviceIds)
5389 << " for window: " << touchedWindow->dump();
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005390 return false;
5391 }
5392 const int32_t deviceId = *deviceIds.begin();
Arthur Hungabbb9d82021-09-01 14:52:30 +00005393
Arthur Hungabbb9d82021-09-01 14:52:30 +00005394 sp<WindowInfoHandle> toWindowHandle = getWindowHandleLocked(toToken, displayId);
5395 if (toWindowHandle == nullptr) {
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005396 ALOGW("Cannot transfer touch because to window not found.");
Arthur Hungabbb9d82021-09-01 14:52:30 +00005397 return false;
5398 }
5399
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005400 if (DEBUG_FOCUS) {
5401 ALOGD("transferTouchFocus: fromWindowHandle=%s, toWindowHandle=%s",
Arthur Hungabbb9d82021-09-01 14:52:30 +00005402 touchedWindow->windowHandle->getName().c_str(),
5403 toWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005404 }
5405
Arthur Hungabbb9d82021-09-01 14:52:30 +00005406 // Erase old window.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005407 ftl::Flags<InputTarget::Flags> oldTargetFlags = touchedWindow->targetFlags;
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005408 std::bitset<MAX_POINTER_ID + 1> pointerIds = touchedWindow->getTouchingPointers(deviceId);
Arthur Hungc539dbb2022-12-08 07:45:36 +00005409 sp<WindowInfoHandle> fromWindowHandle = touchedWindow->windowHandle;
Arthur Hungabbb9d82021-09-01 14:52:30 +00005410 state->removeWindowByToken(fromToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005411
Arthur Hungabbb9d82021-09-01 14:52:30 +00005412 // Add new window.
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00005413 nsecs_t downTimeInTarget = now();
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005414 ftl::Flags<InputTarget::Flags> newTargetFlags =
5415 oldTargetFlags & (InputTarget::Flags::SPLIT | InputTarget::Flags::DISPATCH_AS_IS);
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00005416 if (canReceiveForegroundTouches(*toWindowHandle->getInfo())) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005417 newTargetFlags |= InputTarget::Flags::FOREGROUND;
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00005418 }
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005419 state->addOrUpdateWindow(toWindowHandle, newTargetFlags, deviceId, pointerIds,
5420 downTimeInTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005421
Arthur Hungabbb9d82021-09-01 14:52:30 +00005422 // Store the dragging window.
5423 if (isDragDrop) {
Arthur Hungb75c2aa2022-07-15 09:35:36 +00005424 if (pointerIds.count() != 1) {
5425 ALOGW("The drag and drop cannot be started when there is no pointer or more than 1"
5426 " pointer on the window.");
Arthur Hung54745652022-04-20 07:17:41 +00005427 return false;
5428 }
Arthur Hungb75c2aa2022-07-15 09:35:36 +00005429 // Track the pointer id for drag window and generate the drag state.
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08005430 const size_t id = firstMarkedBit(pointerIds);
Arthur Hung54745652022-04-20 07:17:41 +00005431 mDragState = std::make_unique<DragState>(toWindowHandle, id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005432 }
5433
Arthur Hungabbb9d82021-09-01 14:52:30 +00005434 // Synthesize cancel for old window and down for new window.
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07005435 std::shared_ptr<Connection> fromConnection = getConnectionLocked(fromToken);
5436 std::shared_ptr<Connection> toConnection = getConnectionLocked(toToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005437 if (fromConnection != nullptr && toConnection != nullptr) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08005438 fromConnection->inputState.mergePointerStateTo(toConnection->inputState);
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005439 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
5440 "transferring touch from this window to another window");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005441 synthesizeCancelationEventsForConnectionLocked(fromConnection, options);
Arthur Hungc539dbb2022-12-08 07:45:36 +00005442 synthesizePointerDownEventsForConnectionLocked(downTimeInTarget, toConnection,
5443 newTargetFlags);
5444
5445 // Check if the wallpaper window should deliver the corresponding event.
5446 transferWallpaperTouch(oldTargetFlags, newTargetFlags, fromWindowHandle, toWindowHandle,
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005447 *state, deviceId, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005448 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005449 } // release lock
5450
5451 // Wake up poll loop since it may need to make new input dispatching choices.
5452 mLooper->wake();
5453 return true;
5454}
5455
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005456/**
5457 * Get the touched foreground window on the given display.
5458 * Return null if there are no windows touched on that display, or if more than one foreground
5459 * window is being touched.
5460 */
5461sp<WindowInfoHandle> InputDispatcher::findTouchedForegroundWindowLocked(int32_t displayId) const {
5462 auto stateIt = mTouchStatesByDisplay.find(displayId);
5463 if (stateIt == mTouchStatesByDisplay.end()) {
5464 ALOGI("No touch state on display %" PRId32, displayId);
5465 return nullptr;
5466 }
5467
5468 const TouchState& state = stateIt->second;
5469 sp<WindowInfoHandle> touchedForegroundWindow;
5470 // If multiple foreground windows are touched, return nullptr
5471 for (const TouchedWindow& window : state.windows) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005472 if (window.targetFlags.test(InputTarget::Flags::FOREGROUND)) {
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005473 if (touchedForegroundWindow != nullptr) {
5474 ALOGI("Two or more foreground windows: %s and %s",
5475 touchedForegroundWindow->getName().c_str(),
5476 window.windowHandle->getName().c_str());
5477 return nullptr;
5478 }
5479 touchedForegroundWindow = window.windowHandle;
5480 }
5481 }
5482 return touchedForegroundWindow;
5483}
5484
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005485// Binder call
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005486bool InputDispatcher::transferTouch(const sp<IBinder>& destChannelToken, int32_t displayId) {
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005487 sp<IBinder> fromToken;
5488 { // acquire lock
5489 std::scoped_lock _l(mLock);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005490 sp<WindowInfoHandle> toWindowHandle = getWindowHandleLocked(destChannelToken, displayId);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005491 if (toWindowHandle == nullptr) {
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005492 ALOGW("Could not find window associated with token=%p on display %" PRId32,
5493 destChannelToken.get(), displayId);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005494 return false;
5495 }
5496
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005497 sp<WindowInfoHandle> from = findTouchedForegroundWindowLocked(displayId);
5498 if (from == nullptr) {
5499 ALOGE("Could not find a source window in %s for %p", __func__, destChannelToken.get());
5500 return false;
5501 }
5502
5503 fromToken = from->getToken();
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005504 } // release lock
5505
5506 return transferTouchFocus(fromToken, destChannelToken);
5507}
5508
Michael Wrightd02c5b62014-02-10 15:10:22 -08005509void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005510 if (DEBUG_FOCUS) {
5511 ALOGD("Resetting and dropping all events (%s).", reason);
5512 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005513
Michael Wrightfb04fd52022-11-24 22:31:11 +00005514 CancelationOptions options(CancelationOptions::Mode::CANCEL_ALL_EVENTS, reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005515 synthesizeCancelationEventsForAllConnectionsLocked(options);
5516
5517 resetKeyRepeatLocked();
5518 releasePendingEventLocked();
5519 drainInboundQueueLocked();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005520 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005521
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005522 mAnrTracker.clear();
Jeff Brownf086ddb2014-02-11 14:28:48 -08005523 mTouchStatesByDisplay.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005524}
5525
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005526void InputDispatcher::logDispatchStateLocked() const {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005527 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005528 dumpDispatchStateLocked(dump);
5529
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005530 std::istringstream stream(dump);
5531 std::string line;
5532
5533 while (std::getline(stream, line, '\n')) {
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07005534 ALOGI("%s", line.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005535 }
5536}
5537
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005538std::string InputDispatcher::dumpPointerCaptureStateLocked() const {
Prabir Pradhan99987712020-11-10 18:43:05 -08005539 std::string dump;
5540
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005541 dump += StringPrintf(INDENT "Pointer Capture Requested: %s\n",
5542 toString(mCurrentPointerCaptureRequest.enable));
Prabir Pradhan99987712020-11-10 18:43:05 -08005543
5544 std::string windowName = "None";
5545 if (mWindowTokenWithPointerCapture) {
chaviw98318de2021-05-19 16:45:23 -05005546 const sp<WindowInfoHandle> captureWindowHandle =
Prabir Pradhan99987712020-11-10 18:43:05 -08005547 getWindowHandleLocked(mWindowTokenWithPointerCapture);
5548 windowName = captureWindowHandle ? captureWindowHandle->getName().c_str()
5549 : "token has capture without window";
5550 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005551 dump += StringPrintf(INDENT "Current Window with Pointer Capture: %s\n", windowName.c_str());
Prabir Pradhan99987712020-11-10 18:43:05 -08005552
5553 return dump;
5554}
5555
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005556void InputDispatcher::dumpDispatchStateLocked(std::string& dump) const {
Siarhei Vishniakou043a3ec2019-05-01 11:30:46 -07005557 dump += StringPrintf(INDENT "DispatchEnabled: %s\n", toString(mDispatchEnabled));
5558 dump += StringPrintf(INDENT "DispatchFrozen: %s\n", toString(mDispatchFrozen));
5559 dump += StringPrintf(INDENT "InputFilterEnabled: %s\n", toString(mInputFilterEnabled));
Tiger Huang721e26f2018-07-24 22:26:19 +08005560 dump += StringPrintf(INDENT "FocusedDisplayId: %" PRId32 "\n", mFocusedDisplayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005561
Tiger Huang721e26f2018-07-24 22:26:19 +08005562 if (!mFocusedApplicationHandlesByDisplay.empty()) {
5563 dump += StringPrintf(INDENT "FocusedApplications:\n");
5564 for (auto& it : mFocusedApplicationHandlesByDisplay) {
5565 const int32_t displayId = it.first;
Chris Yea209fde2020-07-22 13:54:51 -07005566 const std::shared_ptr<InputApplicationHandle>& applicationHandle = it.second;
Siarhei Vishniakou70622952020-07-30 11:17:23 -05005567 const std::chrono::duration timeout =
5568 applicationHandle->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005569 dump += StringPrintf(INDENT2 "displayId=%" PRId32
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005570 ", name='%s', dispatchingTimeout=%" PRId64 "ms\n",
Siarhei Vishniakou70622952020-07-30 11:17:23 -05005571 displayId, applicationHandle->getName().c_str(), millis(timeout));
Tiger Huang721e26f2018-07-24 22:26:19 +08005572 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005573 } else {
Tiger Huang721e26f2018-07-24 22:26:19 +08005574 dump += StringPrintf(INDENT "FocusedApplications: <none>\n");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005575 }
Tiger Huang721e26f2018-07-24 22:26:19 +08005576
Vishnu Nairc519ff72021-01-21 08:23:08 -08005577 dump += mFocusResolver.dump();
Prabir Pradhan99987712020-11-10 18:43:05 -08005578 dump += dumpPointerCaptureStateLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005579
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005580 if (!mTouchStatesByDisplay.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005581 dump += StringPrintf(INDENT "TouchStatesByDisplay:\n");
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005582 for (const auto& [displayId, state] : mTouchStatesByDisplay) {
Siarhei Vishniakou6e1e9872022-11-08 17:51:35 -08005583 std::string touchStateDump = addLinePrefix(state.dump(), INDENT2);
5584 dump += INDENT2 + std::to_string(displayId) + " : " + touchStateDump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005585 }
5586 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005587 dump += INDENT "TouchStates: <no displays touched>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005588 }
5589
arthurhung6d4bed92021-03-17 11:59:33 +08005590 if (mDragState) {
5591 dump += StringPrintf(INDENT "DragState:\n");
5592 mDragState->dump(dump, INDENT2);
5593 }
5594
Arthur Hungb92218b2018-08-14 12:00:21 +08005595 if (!mWindowHandlesByDisplay.empty()) {
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005596 for (const auto& [displayId, windowHandles] : mWindowHandlesByDisplay) {
5597 dump += StringPrintf(INDENT "Display: %" PRId32 "\n", displayId);
5598 if (const auto& it = mDisplayInfos.find(displayId); it != mDisplayInfos.end()) {
5599 const auto& displayInfo = it->second;
5600 dump += StringPrintf(INDENT2 "logicalSize=%dx%d\n", displayInfo.logicalWidth,
5601 displayInfo.logicalHeight);
5602 displayInfo.transform.dump(dump, "transform", INDENT4);
5603 } else {
5604 dump += INDENT2 "No DisplayInfo found!\n";
5605 }
5606
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08005607 if (!windowHandles.empty()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08005608 dump += INDENT2 "Windows:\n";
5609 for (size_t i = 0; i < windowHandles.size(); i++) {
chaviw98318de2021-05-19 16:45:23 -05005610 const sp<WindowInfoHandle>& windowHandle = windowHandles[i];
5611 const WindowInfo* windowInfo = windowHandle->getInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005612
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00005613 dump += StringPrintf(INDENT3 "%zu: name='%s', id=%" PRId32 ", displayId=%d, "
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005614 "inputConfig=%s, alpha=%.2f, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005615 "frame=[%d,%d][%d,%d], globalScale=%f, "
Bernardo Rufino49d99e42021-01-18 15:16:59 +00005616 "applicationInfo.name=%s, "
5617 "applicationInfo.token=%s, "
chaviw1ff3d1e2020-07-01 15:53:47 -07005618 "touchableRegion=",
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00005619 i, windowInfo->name.c_str(), windowInfo->id,
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005620 windowInfo->displayId,
5621 windowInfo->inputConfig.string().c_str(),
Chavi Weingarten7f019192023-08-08 20:39:01 +00005622 windowInfo->alpha, windowInfo->frame.left,
5623 windowInfo->frame.top, windowInfo->frame.right,
5624 windowInfo->frame.bottom, windowInfo->globalScaleFactor,
Bernardo Rufino49d99e42021-01-18 15:16:59 +00005625 windowInfo->applicationInfo.name.c_str(),
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07005626 binderToString(windowInfo->applicationInfo.token).c_str());
Bernardo Rufino53fc31e2020-11-03 11:01:07 +00005627 dump += dumpRegion(windowInfo->touchableRegion);
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005628 dump += StringPrintf(", ownerPid=%s, ownerUid=%s, dispatchingTimeout=%" PRId64
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005629 "ms, hasToken=%s, "
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005630 "touchOcclusionMode=%s\n",
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005631 windowInfo->ownerPid.toString().c_str(),
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00005632 windowInfo->ownerUid.toString().c_str(),
Bernardo Rufinoc2f1fad2020-11-04 17:30:57 +00005633 millis(windowInfo->dispatchingTimeout),
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07005634 binderToString(windowInfo->token).c_str(),
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005635 toString(windowInfo->touchOcclusionMode).c_str());
chaviw85b44202020-07-24 11:46:21 -07005636 windowInfo->transform.dump(dump, "transform", INDENT4);
Arthur Hungb92218b2018-08-14 12:00:21 +08005637 }
5638 } else {
5639 dump += INDENT2 "Windows: <none>\n";
5640 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005641 }
5642 } else {
Arthur Hungb92218b2018-08-14 12:00:21 +08005643 dump += INDENT "Displays: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005644 }
5645
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005646 if (!mGlobalMonitorsByDisplay.empty()) {
5647 for (const auto& [displayId, monitors] : mGlobalMonitorsByDisplay) {
5648 dump += StringPrintf(INDENT "Global monitors on display %d:\n", displayId);
Michael Wright3dd60e22019-03-27 22:06:44 +00005649 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005650 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005651 } else {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005652 dump += INDENT "Global Monitors: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005653 }
5654
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005655 const nsecs_t currentTime = now();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005656
5657 // Dump recently dispatched or dropped events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005658 if (!mRecentQueue.empty()) {
5659 dump += StringPrintf(INDENT "RecentQueue: length=%zu\n", mRecentQueue.size());
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005660 for (const std::shared_ptr<EventEntry>& entry : mRecentQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005661 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005662 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005663 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005664 }
5665 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005666 dump += INDENT "RecentQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005667 }
5668
5669 // Dump event currently being dispatched.
5670 if (mPendingEvent) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005671 dump += INDENT "PendingEvent:\n";
5672 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005673 dump += mPendingEvent->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005674 dump += StringPrintf(", age=%" PRId64 "ms\n",
5675 ns2ms(currentTime - mPendingEvent->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005676 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005677 dump += INDENT "PendingEvent: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005678 }
5679
5680 // Dump inbound events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005681 if (!mInboundQueue.empty()) {
5682 dump += StringPrintf(INDENT "InboundQueue: length=%zu\n", mInboundQueue.size());
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005683 for (const std::shared_ptr<EventEntry>& entry : mInboundQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005684 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005685 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005686 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005687 }
5688 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005689 dump += INDENT "InboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005690 }
5691
Prabir Pradhancef936d2021-07-21 16:17:52 +00005692 if (!mCommandQueue.empty()) {
5693 dump += StringPrintf(INDENT "CommandQueue: size=%zu\n", mCommandQueue.size());
5694 } else {
5695 dump += INDENT "CommandQueue: <empty>\n";
5696 }
5697
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005698 if (!mConnectionsByToken.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005699 dump += INDENT "Connections:\n";
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005700 for (const auto& [token, connection] : mConnectionsByToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005701 dump += StringPrintf(INDENT2 "%i: channelName='%s', windowName='%s', "
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005702 "status=%s, monitor=%s, responsive=%s\n",
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005703 connection->inputChannel->getFd().get(),
5704 connection->getInputChannelName().c_str(),
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08005705 connection->getWindowName().c_str(),
5706 ftl::enum_string(connection->status).c_str(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005707 toString(connection->monitor), toString(connection->responsive));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005708
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005709 if (!connection->outboundQueue.empty()) {
5710 dump += StringPrintf(INDENT3 "OutboundQueue: length=%zu\n",
5711 connection->outboundQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005712 dump += dumpQueue(connection->outboundQueue, currentTime);
5713
Michael Wrightd02c5b62014-02-10 15:10:22 -08005714 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005715 dump += INDENT3 "OutboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005716 }
5717
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005718 if (!connection->waitQueue.empty()) {
5719 dump += StringPrintf(INDENT3 "WaitQueue: length=%zu\n",
5720 connection->waitQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005721 dump += dumpQueue(connection->waitQueue, currentTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005722 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005723 dump += INDENT3 "WaitQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005724 }
Siarhei Vishniakoud38a1e02023-07-18 11:55:17 -07005725 std::stringstream inputStateDump;
5726 inputStateDump << connection->inputState;
5727 if (!isEmpty(inputStateDump)) {
5728 dump += INDENT3 "InputState: ";
5729 dump += inputStateDump.str() + "\n";
5730 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005731 }
5732 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005733 dump += INDENT "Connections: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005734 }
5735
5736 if (isAppSwitchPendingLocked()) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005737 dump += StringPrintf(INDENT "AppSwitch: pending, due in %" PRId64 "ms\n",
5738 ns2ms(mAppSwitchDueTime - now()));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005739 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005740 dump += INDENT "AppSwitch: not pending\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005741 }
5742
Antonio Kantek15beb512022-06-13 22:35:41 +00005743 if (!mTouchModePerDisplay.empty()) {
5744 dump += INDENT "TouchModePerDisplay:\n";
5745 for (const auto& [displayId, touchMode] : mTouchModePerDisplay) {
5746 dump += StringPrintf(INDENT2 "Display: %" PRId32 " TouchMode: %s\n", displayId,
5747 std::to_string(touchMode).c_str());
5748 }
5749 } else {
5750 dump += INDENT "TouchModePerDisplay: <none>\n";
5751 }
5752
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005753 dump += INDENT "Configuration:\n";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005754 dump += StringPrintf(INDENT2 "KeyRepeatDelay: %" PRId64 "ms\n", ns2ms(mConfig.keyRepeatDelay));
5755 dump += StringPrintf(INDENT2 "KeyRepeatTimeout: %" PRId64 "ms\n",
5756 ns2ms(mConfig.keyRepeatTimeout));
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00005757 dump += mLatencyTracker.dump(INDENT2);
Siarhei Vishniakoua04181f2021-03-26 05:56:49 +00005758 dump += mLatencyAggregator.dump(INDENT2);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005759}
5760
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005761void InputDispatcher::dumpMonitors(std::string& dump, const std::vector<Monitor>& monitors) const {
Michael Wright3dd60e22019-03-27 22:06:44 +00005762 const size_t numMonitors = monitors.size();
5763 for (size_t i = 0; i < numMonitors; i++) {
5764 const Monitor& monitor = monitors[i];
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005765 const std::shared_ptr<InputChannel>& channel = monitor.inputChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005766 dump += StringPrintf(INDENT2 "%zu: '%s', ", i, channel->getName().c_str());
5767 dump += "\n";
5768 }
5769}
5770
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005771class LooperEventCallback : public LooperCallback {
5772public:
5773 LooperEventCallback(std::function<int(int events)> callback) : mCallback(callback) {}
5774 int handleEvent(int /*fd*/, int events, void* /*data*/) override { return mCallback(events); }
5775
5776private:
5777 std::function<int(int events)> mCallback;
5778};
5779
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005780Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputChannel(const std::string& name) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00005781 if (DEBUG_CHANNEL_CREATION) {
5782 ALOGD("channel '%s' ~ createInputChannel", name.c_str());
5783 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005784
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005785 std::unique_ptr<InputChannel> serverChannel;
Garfield Tan15601662020-09-22 15:32:38 -07005786 std::unique_ptr<InputChannel> clientChannel;
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005787 status_t result = InputChannel::openInputChannelPair(name, serverChannel, clientChannel);
Garfield Tan15601662020-09-22 15:32:38 -07005788
5789 if (result) {
5790 return base::Error(result) << "Failed to open input channel pair with name " << name;
5791 }
5792
Michael Wrightd02c5b62014-02-10 15:10:22 -08005793 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005794 std::scoped_lock _l(mLock);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005795 const sp<IBinder>& token = serverChannel->getConnectionToken();
Garfield Tan15601662020-09-22 15:32:38 -07005796 int fd = serverChannel->getFd();
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07005797 std::shared_ptr<Connection> connection =
5798 std::make_shared<Connection>(std::move(serverChannel), /*monitor=*/false,
5799 mIdGenerator);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005800
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005801 if (mConnectionsByToken.find(token) != mConnectionsByToken.end()) {
5802 ALOGE("Created a new connection, but the token %p is already known", token.get());
5803 }
5804 mConnectionsByToken.emplace(token, connection);
5805
5806 std::function<int(int events)> callback = std::bind(&InputDispatcher::handleReceiveCallback,
5807 this, std::placeholders::_1, token);
5808
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005809 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, sp<LooperEventCallback>::make(callback),
5810 nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005811 } // release lock
5812
5813 // Wake the looper because some connections have changed.
5814 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07005815 return clientChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005816}
5817
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005818Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputMonitor(int32_t displayId,
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005819 const std::string& name,
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005820 gui::Pid pid) {
Garfield Tan15601662020-09-22 15:32:38 -07005821 std::shared_ptr<InputChannel> serverChannel;
5822 std::unique_ptr<InputChannel> clientChannel;
5823 status_t result = openInputChannelPair(name, serverChannel, clientChannel);
5824 if (result) {
5825 return base::Error(result) << "Failed to open input channel pair with name " << name;
5826 }
5827
Michael Wright3dd60e22019-03-27 22:06:44 +00005828 { // acquire lock
5829 std::scoped_lock _l(mLock);
5830
5831 if (displayId < 0) {
Garfield Tan15601662020-09-22 15:32:38 -07005832 return base::Error(BAD_VALUE) << "Attempted to create input monitor with name " << name
5833 << " without a specified display.";
Michael Wright3dd60e22019-03-27 22:06:44 +00005834 }
5835
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07005836 std::shared_ptr<Connection> connection =
5837 std::make_shared<Connection>(serverChannel, /*monitor=*/true, mIdGenerator);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005838 const sp<IBinder>& token = serverChannel->getConnectionToken();
Garfield Tan15601662020-09-22 15:32:38 -07005839 const int fd = serverChannel->getFd();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005840
5841 if (mConnectionsByToken.find(token) != mConnectionsByToken.end()) {
5842 ALOGE("Created a new connection, but the token %p is already known", token.get());
5843 }
5844 mConnectionsByToken.emplace(token, connection);
5845 std::function<int(int events)> callback = std::bind(&InputDispatcher::handleReceiveCallback,
5846 this, std::placeholders::_1, token);
Michael Wright3dd60e22019-03-27 22:06:44 +00005847
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005848 mGlobalMonitorsByDisplay[displayId].emplace_back(serverChannel, pid);
Michael Wright3dd60e22019-03-27 22:06:44 +00005849
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005850 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, sp<LooperEventCallback>::make(callback),
5851 nullptr);
Michael Wright3dd60e22019-03-27 22:06:44 +00005852 }
Garfield Tan15601662020-09-22 15:32:38 -07005853
Michael Wright3dd60e22019-03-27 22:06:44 +00005854 // Wake the looper because some connections have changed.
5855 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07005856 return clientChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005857}
5858
Garfield Tan15601662020-09-22 15:32:38 -07005859status_t InputDispatcher::removeInputChannel(const sp<IBinder>& connectionToken) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005860 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005861 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005862
Harry Cutts33476232023-01-30 19:57:29 +00005863 status_t status = removeInputChannelLocked(connectionToken, /*notify=*/false);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005864 if (status) {
5865 return status;
5866 }
5867 } // release lock
5868
5869 // Wake the poll loop because removing the connection may have changed the current
5870 // synchronization state.
5871 mLooper->wake();
5872 return OK;
5873}
5874
Garfield Tan15601662020-09-22 15:32:38 -07005875status_t InputDispatcher::removeInputChannelLocked(const sp<IBinder>& connectionToken,
5876 bool notify) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07005877 std::shared_ptr<Connection> connection = getConnectionLocked(connectionToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005878 if (connection == nullptr) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005879 // Connection can be removed via socket hang up or an explicit call to 'removeInputChannel'
Michael Wrightd02c5b62014-02-10 15:10:22 -08005880 return BAD_VALUE;
5881 }
5882
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005883 removeConnectionLocked(connection);
Robert Carr5c8a0262018-10-03 16:30:44 -07005884
Michael Wrightd02c5b62014-02-10 15:10:22 -08005885 if (connection->monitor) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005886 removeMonitorChannelLocked(connectionToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005887 }
5888
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005889 mLooper->removeFd(connection->inputChannel->getFd());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005890
5891 nsecs_t currentTime = now();
5892 abortBrokenDispatchCycleLocked(currentTime, connection, notify);
5893
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08005894 connection->status = Connection::Status::ZOMBIE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005895 return OK;
5896}
5897
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005898void InputDispatcher::removeMonitorChannelLocked(const sp<IBinder>& connectionToken) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005899 for (auto it = mGlobalMonitorsByDisplay.begin(); it != mGlobalMonitorsByDisplay.end();) {
5900 auto& [displayId, monitors] = *it;
5901 std::erase_if(monitors, [connectionToken](const Monitor& monitor) {
5902 return monitor.inputChannel->getConnectionToken() == connectionToken;
5903 });
Michael Wright3dd60e22019-03-27 22:06:44 +00005904
Michael Wright3dd60e22019-03-27 22:06:44 +00005905 if (monitors.empty()) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005906 it = mGlobalMonitorsByDisplay.erase(it);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005907 } else {
5908 ++it;
5909 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005910 }
5911}
5912
Michael Wright3dd60e22019-03-27 22:06:44 +00005913status_t InputDispatcher::pilferPointers(const sp<IBinder>& token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005914 std::scoped_lock _l(mLock);
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00005915 return pilferPointersLocked(token);
5916}
Michael Wright3dd60e22019-03-27 22:06:44 +00005917
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00005918status_t InputDispatcher::pilferPointersLocked(const sp<IBinder>& token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005919 const std::shared_ptr<InputChannel> requestingChannel = getInputChannelLocked(token);
5920 if (!requestingChannel) {
5921 ALOGW("Attempted to pilfer pointers from an un-registered channel or invalid token");
5922 return BAD_VALUE;
Michael Wright3dd60e22019-03-27 22:06:44 +00005923 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005924
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005925 auto [statePtr, windowPtr, displayId] = findTouchStateWindowAndDisplayLocked(token);
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005926 if (statePtr == nullptr || windowPtr == nullptr) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005927 ALOGW("Attempted to pilfer points from a channel without any on-going pointer streams."
5928 " Ignoring.");
5929 return BAD_VALUE;
5930 }
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005931 std::set<int32_t> deviceIds = windowPtr->getTouchingDeviceIds();
5932 if (deviceIds.size() != 1) {
5933 LOG(WARNING) << "Can't pilfer. Currently touching devices: " << dumpSet(deviceIds)
5934 << " in window: " << windowPtr->dump();
5935 return BAD_VALUE;
5936 }
5937 const int32_t deviceId = *deviceIds.begin();
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005938
5939 TouchState& state = *statePtr;
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00005940 TouchedWindow& window = *windowPtr;
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005941 // Send cancel events to all the input channels we're stealing from.
Michael Wrightfb04fd52022-11-24 22:31:11 +00005942 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005943 "input channel stole pointer stream");
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005944 options.deviceId = deviceId;
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005945 options.displayId = displayId;
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005946 std::bitset<MAX_POINTER_ID + 1> pointerIds = window.getTouchingPointers(deviceId);
5947 options.pointerIds = pointerIds;
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005948 std::string canceledWindows;
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00005949 for (const TouchedWindow& w : state.windows) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005950 const std::shared_ptr<InputChannel> channel =
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00005951 getInputChannelLocked(w.windowHandle->getToken());
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005952 if (channel != nullptr && channel->getConnectionToken() != token) {
5953 synthesizeCancelationEventsForInputChannelLocked(channel, options);
5954 canceledWindows += canceledWindows.empty() ? "[" : ", ";
5955 canceledWindows += channel->getName();
5956 }
5957 }
5958 canceledWindows += canceledWindows.empty() ? "[]" : "]";
5959 ALOGI("Channel %s is stealing touch from %s", requestingChannel->getName().c_str(),
5960 canceledWindows.c_str());
5961
Prabir Pradhane680f9b2022-02-04 04:24:00 -08005962 // Prevent the gesture from being sent to any other windows.
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00005963 // This only blocks relevant pointers to be sent to other windows
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005964 window.addPilferingPointers(deviceId, pointerIds);
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00005965
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005966 state.cancelPointersForWindowsExcept(deviceId, pointerIds, token);
Michael Wright3dd60e22019-03-27 22:06:44 +00005967 return OK;
5968}
5969
Prabir Pradhan99987712020-11-10 18:43:05 -08005970void InputDispatcher::requestPointerCapture(const sp<IBinder>& windowToken, bool enabled) {
5971 { // acquire lock
5972 std::scoped_lock _l(mLock);
5973 if (DEBUG_FOCUS) {
chaviw98318de2021-05-19 16:45:23 -05005974 const sp<WindowInfoHandle> windowHandle = getWindowHandleLocked(windowToken);
Prabir Pradhan99987712020-11-10 18:43:05 -08005975 ALOGI("Request to %s Pointer Capture from: %s.", enabled ? "enable" : "disable",
5976 windowHandle != nullptr ? windowHandle->getName().c_str()
5977 : "token without window");
5978 }
5979
Vishnu Nairc519ff72021-01-21 08:23:08 -08005980 const sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Prabir Pradhan99987712020-11-10 18:43:05 -08005981 if (focusedToken != windowToken) {
5982 ALOGW("Ignoring request to %s Pointer Capture: window does not have focus.",
5983 enabled ? "enable" : "disable");
5984 return;
5985 }
5986
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005987 if (enabled == mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08005988 ALOGW("Ignoring request to %s Pointer Capture: "
5989 "window has %s requested pointer capture.",
5990 enabled ? "enable" : "disable", enabled ? "already" : "not");
5991 return;
5992 }
5993
Christine Franksb768bb42021-11-29 12:11:31 -08005994 if (enabled) {
5995 if (std::find(mIneligibleDisplaysForPointerCapture.begin(),
5996 mIneligibleDisplaysForPointerCapture.end(),
5997 mFocusedDisplayId) != mIneligibleDisplaysForPointerCapture.end()) {
5998 ALOGW("Ignoring request to enable Pointer Capture: display is not eligible");
5999 return;
6000 }
6001 }
6002
Prabir Pradhan99987712020-11-10 18:43:05 -08006003 setPointerCaptureLocked(enabled);
6004 } // release lock
6005
6006 // Wake the thread to process command entries.
6007 mLooper->wake();
6008}
6009
Christine Franksb768bb42021-11-29 12:11:31 -08006010void InputDispatcher::setDisplayEligibilityForPointerCapture(int32_t displayId, bool isEligible) {
6011 { // acquire lock
6012 std::scoped_lock _l(mLock);
6013 std::erase(mIneligibleDisplaysForPointerCapture, displayId);
6014 if (!isEligible) {
6015 mIneligibleDisplaysForPointerCapture.push_back(displayId);
6016 }
6017 } // release lock
6018}
6019
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00006020std::optional<gui::Pid> InputDispatcher::findMonitorPidByTokenLocked(const sp<IBinder>& token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006021 for (const auto& [_, monitors] : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00006022 for (const Monitor& monitor : monitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07006023 if (monitor.inputChannel->getConnectionToken() == token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006024 return monitor.pid;
Michael Wright3dd60e22019-03-27 22:06:44 +00006025 }
6026 }
6027 }
6028 return std::nullopt;
6029}
6030
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006031std::shared_ptr<Connection> InputDispatcher::getConnectionLocked(
6032 const sp<IBinder>& inputConnectionToken) const {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07006033 if (inputConnectionToken == nullptr) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07006034 return nullptr;
Arthur Hung3b413f22018-10-26 18:05:34 +08006035 }
6036
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00006037 for (const auto& [token, connection] : mConnectionsByToken) {
6038 if (token == inputConnectionToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07006039 return connection;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006040 }
6041 }
Robert Carr4e670e52018-08-15 13:26:12 -07006042
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07006043 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006044}
6045
Siarhei Vishniakouad991402020-10-28 11:40:09 -05006046std::string InputDispatcher::getConnectionNameLocked(const sp<IBinder>& connectionToken) const {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006047 std::shared_ptr<Connection> connection = getConnectionLocked(connectionToken);
Siarhei Vishniakouad991402020-10-28 11:40:09 -05006048 if (connection == nullptr) {
6049 return "<nullptr>";
6050 }
6051 return connection->getInputChannelName();
6052}
6053
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006054void InputDispatcher::removeConnectionLocked(const std::shared_ptr<Connection>& connection) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006055 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00006056 mConnectionsByToken.erase(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07006057}
6058
Prabir Pradhancef936d2021-07-21 16:17:52 +00006059void InputDispatcher::doDispatchCycleFinishedCommand(nsecs_t finishTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006060 const std::shared_ptr<Connection>& connection,
6061 uint32_t seq, bool handled,
6062 nsecs_t consumeTime) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006063 // Handle post-event policy actions.
6064 std::deque<DispatchEntry*>::iterator dispatchEntryIt = connection->findWaitQueueEntry(seq);
6065 if (dispatchEntryIt == connection->waitQueue.end()) {
6066 return;
6067 }
6068 DispatchEntry* dispatchEntry = *dispatchEntryIt;
6069 const nsecs_t eventDuration = finishTime - dispatchEntry->deliveryTime;
6070 if (eventDuration > SLOW_EVENT_PROCESSING_WARNING_TIMEOUT) {
6071 ALOGI("%s spent %" PRId64 "ms processing %s", connection->getWindowName().c_str(),
6072 ns2ms(eventDuration), dispatchEntry->eventEntry->getDescription().c_str());
6073 }
6074 if (shouldReportFinishedEvent(*dispatchEntry, *connection)) {
6075 mLatencyTracker.trackFinishedEvent(dispatchEntry->eventEntry->id,
6076 connection->inputChannel->getConnectionToken(),
6077 dispatchEntry->deliveryTime, consumeTime, finishTime);
6078 }
6079
6080 bool restartEvent;
6081 if (dispatchEntry->eventEntry->type == EventEntry::Type::KEY) {
6082 KeyEntry& keyEntry = static_cast<KeyEntry&>(*(dispatchEntry->eventEntry));
6083 restartEvent =
6084 afterKeyEventLockedInterruptable(connection, dispatchEntry, keyEntry, handled);
6085 } else if (dispatchEntry->eventEntry->type == EventEntry::Type::MOTION) {
6086 MotionEntry& motionEntry = static_cast<MotionEntry&>(*(dispatchEntry->eventEntry));
6087 restartEvent = afterMotionEventLockedInterruptable(connection, dispatchEntry, motionEntry,
6088 handled);
6089 } else {
6090 restartEvent = false;
6091 }
6092
6093 // Dequeue the event and start the next cycle.
6094 // Because the lock might have been released, it is possible that the
6095 // contents of the wait queue to have been drained, so we need to double-check
6096 // a few things.
6097 dispatchEntryIt = connection->findWaitQueueEntry(seq);
6098 if (dispatchEntryIt != connection->waitQueue.end()) {
6099 dispatchEntry = *dispatchEntryIt;
6100 connection->waitQueue.erase(dispatchEntryIt);
6101 const sp<IBinder>& connectionToken = connection->inputChannel->getConnectionToken();
6102 mAnrTracker.erase(dispatchEntry->timeoutTime, connectionToken);
6103 if (!connection->responsive) {
6104 connection->responsive = isConnectionResponsive(*connection);
6105 if (connection->responsive) {
6106 // The connection was unresponsive, and now it's responsive.
6107 processConnectionResponsiveLocked(*connection);
6108 }
6109 }
6110 traceWaitQueueLength(*connection);
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08006111 if (restartEvent && connection->status == Connection::Status::NORMAL) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006112 connection->outboundQueue.push_front(dispatchEntry);
6113 traceOutboundQueueLength(*connection);
6114 } else {
6115 releaseDispatchEntry(dispatchEntry);
6116 }
6117 }
6118
6119 // Start the next dispatch cycle for this connection.
6120 startDispatchCycleLocked(now(), connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006121}
6122
Prabir Pradhancef936d2021-07-21 16:17:52 +00006123void InputDispatcher::sendFocusChangedCommandLocked(const sp<IBinder>& oldToken,
6124 const sp<IBinder>& newToken) {
6125 auto command = [this, oldToken, newToken]() REQUIRES(mLock) {
6126 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00006127 mPolicy.notifyFocusChanged(oldToken, newToken);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006128 };
6129 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08006130}
6131
Prabir Pradhancef936d2021-07-21 16:17:52 +00006132void InputDispatcher::sendDropWindowCommandLocked(const sp<IBinder>& token, float x, float y) {
6133 auto command = [this, token, x, y]() REQUIRES(mLock) {
6134 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00006135 mPolicy.notifyDropWindow(token, x, y);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006136 };
6137 postCommandLocked(std::move(command));
Robert Carrf759f162018-11-13 12:57:11 -08006138}
6139
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006140void InputDispatcher::onAnrLocked(const std::shared_ptr<Connection>& connection) {
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006141 if (connection == nullptr) {
6142 LOG_ALWAYS_FATAL("Caller must check for nullness");
6143 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006144 // Since we are allowing the policy to extend the timeout, maybe the waitQueue
6145 // is already healthy again. Don't raise ANR in this situation
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006146 if (connection->waitQueue.empty()) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006147 ALOGI("Not raising ANR because the connection %s has recovered",
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006148 connection->inputChannel->getName().c_str());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006149 return;
6150 }
6151 /**
6152 * The "oldestEntry" is the entry that was first sent to the application. That entry, however,
6153 * may not be the one that caused the timeout to occur. One possibility is that window timeout
6154 * has changed. This could cause newer entries to time out before the already dispatched
6155 * entries. In that situation, the newest entries caused ANR. But in all likelihood, the app
6156 * processes the events linearly. So providing information about the oldest entry seems to be
6157 * most useful.
6158 */
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006159 DispatchEntry* oldestEntry = *connection->waitQueue.begin();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006160 const nsecs_t currentWait = now() - oldestEntry->deliveryTime;
6161 std::string reason =
6162 android::base::StringPrintf("%s is not responding. Waited %" PRId64 "ms for %s",
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006163 connection->inputChannel->getName().c_str(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006164 ns2ms(currentWait),
6165 oldestEntry->eventEntry->getDescription().c_str());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006166 sp<IBinder> connectionToken = connection->inputChannel->getConnectionToken();
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -06006167 updateLastAnrStateLocked(getWindowHandleLocked(connectionToken), reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006168
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006169 processConnectionUnresponsiveLocked(*connection, std::move(reason));
6170
6171 // Stop waking up for events on this connection, it is already unresponsive
6172 cancelEventsForAnrLocked(connection);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006173}
6174
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05006175void InputDispatcher::onAnrLocked(std::shared_ptr<InputApplicationHandle> application) {
6176 std::string reason =
6177 StringPrintf("%s does not have a focused window", application->getName().c_str());
6178 updateLastAnrStateLocked(*application, reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006179
Yabin Cui8eb9c552023-06-08 18:05:07 +00006180 auto command = [this, app = std::move(application)]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006181 scoped_unlock unlock(mLock);
Yabin Cuiced952f2023-06-09 21:12:51 +00006182 mPolicy.notifyNoFocusedWindowAnr(app);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006183 };
6184 postCommandLocked(std::move(command));
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00006185}
6186
chaviw98318de2021-05-19 16:45:23 -05006187void InputDispatcher::updateLastAnrStateLocked(const sp<WindowInfoHandle>& window,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006188 const std::string& reason) {
6189 const std::string windowLabel = getApplicationWindowLabel(nullptr, window);
6190 updateLastAnrStateLocked(windowLabel, reason);
6191}
6192
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05006193void InputDispatcher::updateLastAnrStateLocked(const InputApplicationHandle& application,
6194 const std::string& reason) {
6195 const std::string windowLabel = getApplicationWindowLabel(&application, nullptr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006196 updateLastAnrStateLocked(windowLabel, reason);
6197}
6198
6199void InputDispatcher::updateLastAnrStateLocked(const std::string& windowLabel,
6200 const std::string& reason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006201 // Capture a record of the InputDispatcher state at the time of the ANR.
Yi Kong9b14ac62018-07-17 13:48:38 -07006202 time_t t = time(nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006203 struct tm tm;
6204 localtime_r(&t, &tm);
6205 char timestr[64];
6206 strftime(timestr, sizeof(timestr), "%F %T", &tm);
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006207 mLastAnrState.clear();
6208 mLastAnrState += INDENT "ANR:\n";
6209 mLastAnrState += StringPrintf(INDENT2 "Time: %s\n", timestr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006210 mLastAnrState += StringPrintf(INDENT2 "Reason: %s\n", reason.c_str());
6211 mLastAnrState += StringPrintf(INDENT2 "Window: %s\n", windowLabel.c_str());
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006212 dumpDispatchStateLocked(mLastAnrState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006213}
6214
Prabir Pradhancef936d2021-07-21 16:17:52 +00006215void InputDispatcher::doInterceptKeyBeforeDispatchingCommand(const sp<IBinder>& focusedWindowToken,
6216 KeyEntry& entry) {
6217 const KeyEvent event = createKeyEvent(entry);
6218 nsecs_t delay = 0;
6219 { // release lock
6220 scoped_unlock unlock(mLock);
6221 android::base::Timer t;
Prabir Pradhana41d2442023-04-20 21:30:40 +00006222 delay = mPolicy.interceptKeyBeforeDispatching(focusedWindowToken, event, entry.policyFlags);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006223 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
6224 ALOGW("Excessive delay in interceptKeyBeforeDispatching; took %s ms",
6225 std::to_string(t.duration().count()).c_str());
6226 }
6227 } // acquire lock
Michael Wrightd02c5b62014-02-10 15:10:22 -08006228
6229 if (delay < 0) {
Michael Wright5caf55a2022-11-24 22:31:42 +00006230 entry.interceptKeyResult = KeyEntry::InterceptKeyResult::SKIP;
Prabir Pradhancef936d2021-07-21 16:17:52 +00006231 } else if (delay == 0) {
Michael Wright5caf55a2022-11-24 22:31:42 +00006232 entry.interceptKeyResult = KeyEntry::InterceptKeyResult::CONTINUE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006233 } else {
Michael Wright5caf55a2022-11-24 22:31:42 +00006234 entry.interceptKeyResult = KeyEntry::InterceptKeyResult::TRY_AGAIN_LATER;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006235 entry.interceptKeyWakeupTime = now() + delay;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006236 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006237}
6238
Prabir Pradhancef936d2021-07-21 16:17:52 +00006239void InputDispatcher::sendWindowUnresponsiveCommandLocked(const sp<IBinder>& token,
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00006240 std::optional<gui::Pid> pid,
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006241 std::string reason) {
Yabin Cui8eb9c552023-06-08 18:05:07 +00006242 auto command = [this, token, pid, r = std::move(reason)]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006243 scoped_unlock unlock(mLock);
Yabin Cuiced952f2023-06-09 21:12:51 +00006244 mPolicy.notifyWindowUnresponsive(token, pid, r);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006245 };
6246 postCommandLocked(std::move(command));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006247}
6248
Prabir Pradhanedd96402022-02-15 01:46:16 -08006249void InputDispatcher::sendWindowResponsiveCommandLocked(const sp<IBinder>& token,
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00006250 std::optional<gui::Pid> pid) {
Prabir Pradhanedd96402022-02-15 01:46:16 -08006251 auto command = [this, token, pid]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006252 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00006253 mPolicy.notifyWindowResponsive(token, pid);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006254 };
6255 postCommandLocked(std::move(command));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006256}
6257
6258/**
6259 * Tell the policy that a connection has become unresponsive so that it can start ANR.
6260 * Check whether the connection of interest is a monitor or a window, and add the corresponding
6261 * command entry to the command queue.
6262 */
6263void InputDispatcher::processConnectionUnresponsiveLocked(const Connection& connection,
6264 std::string reason) {
6265 const sp<IBinder>& connectionToken = connection.inputChannel->getConnectionToken();
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00006266 std::optional<gui::Pid> pid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006267 if (connection.monitor) {
6268 ALOGW("Monitor %s is unresponsive: %s", connection.inputChannel->getName().c_str(),
6269 reason.c_str());
Prabir Pradhanedd96402022-02-15 01:46:16 -08006270 pid = findMonitorPidByTokenLocked(connectionToken);
6271 } else {
6272 // The connection is a window
6273 ALOGW("Window %s is unresponsive: %s", connection.inputChannel->getName().c_str(),
6274 reason.c_str());
6275 const sp<WindowInfoHandle> handle = getWindowHandleLocked(connectionToken);
6276 if (handle != nullptr) {
6277 pid = handle->getInfo()->ownerPid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006278 }
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006279 }
Prabir Pradhanedd96402022-02-15 01:46:16 -08006280 sendWindowUnresponsiveCommandLocked(connectionToken, pid, std::move(reason));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006281}
6282
6283/**
6284 * Tell the policy that a connection has become responsive so that it can stop ANR.
6285 */
6286void InputDispatcher::processConnectionResponsiveLocked(const Connection& connection) {
6287 const sp<IBinder>& connectionToken = connection.inputChannel->getConnectionToken();
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00006288 std::optional<gui::Pid> pid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006289 if (connection.monitor) {
Prabir Pradhanedd96402022-02-15 01:46:16 -08006290 pid = findMonitorPidByTokenLocked(connectionToken);
6291 } else {
6292 // The connection is a window
6293 const sp<WindowInfoHandle> handle = getWindowHandleLocked(connectionToken);
6294 if (handle != nullptr) {
6295 pid = handle->getInfo()->ownerPid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006296 }
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006297 }
Prabir Pradhanedd96402022-02-15 01:46:16 -08006298 sendWindowResponsiveCommandLocked(connectionToken, pid);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006299}
6300
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006301bool InputDispatcher::afterKeyEventLockedInterruptable(
6302 const std::shared_ptr<Connection>& connection, DispatchEntry* dispatchEntry,
6303 KeyEntry& keyEntry, bool handled) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006304 if (keyEntry.flags & AKEY_EVENT_FLAG_FALLBACK) {
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006305 if (!handled) {
6306 // Report the key as unhandled, since the fallback was not handled.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006307 mReporter->reportUnhandledKey(keyEntry.id);
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006308 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006309 return false;
6310 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006311
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006312 // Get the fallback key state.
6313 // Clear it out after dispatching the UP.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006314 int32_t originalKeyCode = keyEntry.keyCode;
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006315 std::optional<int32_t> fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006316 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006317 connection->inputState.removeFallbackKey(originalKeyCode);
6318 }
6319
6320 if (handled || !dispatchEntry->hasForegroundTarget()) {
6321 // If the application handles the original key for which we previously
6322 // generated a fallback or if the window is not a foreground window,
6323 // then cancel the associated fallback key, if any.
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006324 if (fallbackKeyCode) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006325 // Dispatch the unhandled key to the policy with the cancel flag.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006326 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6327 ALOGD("Unhandled key event: Asking policy to cancel fallback action. "
6328 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6329 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount,
6330 keyEntry.policyFlags);
6331 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006332 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006333 event.setFlags(event.getFlags() | AKEY_EVENT_FLAG_CANCELED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006334
6335 mLock.unlock();
6336
Prabir Pradhana41d2442023-04-20 21:30:40 +00006337 if (const auto unhandledKeyFallback =
6338 mPolicy.dispatchUnhandledKey(connection->inputChannel->getConnectionToken(),
6339 event, keyEntry.policyFlags);
6340 unhandledKeyFallback) {
6341 event = *unhandledKeyFallback;
6342 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006343
6344 mLock.lock();
6345
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006346 // Cancel the fallback key.
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006347 if (*fallbackKeyCode != AKEYCODE_UNKNOWN) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00006348 CancelationOptions options(CancelationOptions::Mode::CANCEL_FALLBACK_EVENTS,
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006349 "application handled the original non-fallback key "
6350 "or is no longer a foreground target, "
6351 "canceling previously dispatched fallback key");
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006352 options.keyCode = *fallbackKeyCode;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006353 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006354 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006355 connection->inputState.removeFallbackKey(originalKeyCode);
6356 }
6357 } else {
6358 // If the application did not handle a non-fallback key, first check
6359 // that we are in a good state to perform unhandled key event processing
6360 // Then ask the policy what to do with it.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006361 bool initialDown = keyEntry.action == AKEY_EVENT_ACTION_DOWN && keyEntry.repeatCount == 0;
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006362 if (!fallbackKeyCode && !initialDown) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006363 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6364 ALOGD("Unhandled key event: Skipping unhandled key event processing "
6365 "since this is not an initial down. "
6366 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6367 originalKeyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
6368 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006369 return false;
6370 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006371
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006372 // Dispatch the unhandled key to the policy.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006373 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6374 ALOGD("Unhandled key event: Asking policy to perform fallback action. "
6375 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6376 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
6377 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006378 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006379
6380 mLock.unlock();
6381
Prabir Pradhana41d2442023-04-20 21:30:40 +00006382 bool fallback = false;
6383 if (auto fb = mPolicy.dispatchUnhandledKey(connection->inputChannel->getConnectionToken(),
6384 event, keyEntry.policyFlags);
6385 fb) {
6386 fallback = true;
6387 event = *fb;
6388 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006389
6390 mLock.lock();
6391
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08006392 if (connection->status != Connection::Status::NORMAL) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006393 connection->inputState.removeFallbackKey(originalKeyCode);
6394 return false;
6395 }
6396
6397 // Latch the fallback keycode for this key on an initial down.
6398 // The fallback keycode cannot change at any other point in the lifecycle.
6399 if (initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006400 if (fallback) {
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006401 *fallbackKeyCode = event.getKeyCode();
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006402 } else {
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006403 *fallbackKeyCode = AKEYCODE_UNKNOWN;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006404 }
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006405 connection->inputState.setFallbackKey(originalKeyCode, *fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006406 }
6407
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006408 ALOG_ASSERT(fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006409
6410 // Cancel the fallback key if the policy decides not to send it anymore.
6411 // We will continue to dispatch the key to the policy but we will no
6412 // longer dispatch a fallback key to the application.
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006413 if (*fallbackKeyCode != AKEYCODE_UNKNOWN &&
6414 (!fallback || *fallbackKeyCode != event.getKeyCode())) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006415 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6416 if (fallback) {
6417 ALOGD("Unhandled key event: Policy requested to send key %d"
6418 "as a fallback for %d, but on the DOWN it had requested "
6419 "to send %d instead. Fallback canceled.",
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006420 event.getKeyCode(), originalKeyCode, *fallbackKeyCode);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006421 } else {
6422 ALOGD("Unhandled key event: Policy did not request fallback for %d, "
6423 "but on the DOWN it had requested to send %d. "
6424 "Fallback canceled.",
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006425 originalKeyCode, *fallbackKeyCode);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006426 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006427 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006428
Michael Wrightfb04fd52022-11-24 22:31:11 +00006429 CancelationOptions options(CancelationOptions::Mode::CANCEL_FALLBACK_EVENTS,
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006430 "canceling fallback, policy no longer desires it");
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006431 options.keyCode = *fallbackKeyCode;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006432 synthesizeCancelationEventsForConnectionLocked(connection, options);
6433
6434 fallback = false;
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006435 *fallbackKeyCode = AKEYCODE_UNKNOWN;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006436 if (keyEntry.action != AKEY_EVENT_ACTION_UP) {
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006437 connection->inputState.setFallbackKey(originalKeyCode, *fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006438 }
6439 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006440
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006441 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6442 {
6443 std::string msg;
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006444 const std::map<int32_t, int32_t>& fallbackKeys =
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006445 connection->inputState.getFallbackKeys();
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006446 for (const auto& [key, value] : fallbackKeys) {
6447 msg += StringPrintf(", %d->%d", key, value);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006448 }
6449 ALOGD("Unhandled key event: %zu currently tracked fallback keys%s.",
6450 fallbackKeys.size(), msg.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006451 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006452 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006453
6454 if (fallback) {
6455 // Restart the dispatch cycle using the fallback key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006456 keyEntry.eventTime = event.getEventTime();
6457 keyEntry.deviceId = event.getDeviceId();
6458 keyEntry.source = event.getSource();
6459 keyEntry.displayId = event.getDisplayId();
6460 keyEntry.flags = event.getFlags() | AKEY_EVENT_FLAG_FALLBACK;
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006461 keyEntry.keyCode = *fallbackKeyCode;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006462 keyEntry.scanCode = event.getScanCode();
6463 keyEntry.metaState = event.getMetaState();
6464 keyEntry.repeatCount = event.getRepeatCount();
6465 keyEntry.downTime = event.getDownTime();
6466 keyEntry.syntheticRepeat = false;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006467
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006468 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6469 ALOGD("Unhandled key event: Dispatching fallback key. "
6470 "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006471 originalKeyCode, *fallbackKeyCode, keyEntry.metaState);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006472 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006473 return true; // restart the event
6474 } else {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006475 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6476 ALOGD("Unhandled key event: No fallback key.");
6477 }
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006478
6479 // Report the key as unhandled, since there is no fallback key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006480 mReporter->reportUnhandledKey(keyEntry.id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006481 }
6482 }
6483 return false;
6484}
6485
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006486bool InputDispatcher::afterMotionEventLockedInterruptable(
6487 const std::shared_ptr<Connection>& connection, DispatchEntry* dispatchEntry,
6488 MotionEntry& motionEntry, bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006489 return false;
6490}
6491
Michael Wrightd02c5b62014-02-10 15:10:22 -08006492void InputDispatcher::traceInboundQueueLengthLocked() {
6493 if (ATRACE_ENABLED()) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07006494 ATRACE_INT("iq", mInboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006495 }
6496}
6497
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006498void InputDispatcher::traceOutboundQueueLength(const Connection& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006499 if (ATRACE_ENABLED()) {
6500 char counterName[40];
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006501 snprintf(counterName, sizeof(counterName), "oq:%s", connection.getWindowName().c_str());
6502 ATRACE_INT(counterName, connection.outboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006503 }
6504}
6505
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006506void InputDispatcher::traceWaitQueueLength(const Connection& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006507 if (ATRACE_ENABLED()) {
6508 char counterName[40];
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006509 snprintf(counterName, sizeof(counterName), "wq:%s", connection.getWindowName().c_str());
6510 ATRACE_INT(counterName, connection.waitQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006511 }
6512}
6513
Siarhei Vishniakou5e20f272023-06-08 17:24:44 -07006514void InputDispatcher::dump(std::string& dump) const {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006515 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006516
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006517 dump += "Input Dispatcher State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08006518 dumpDispatchStateLocked(dump);
6519
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006520 if (!mLastAnrState.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006521 dump += "\nInput Dispatcher State at time of last ANR:\n";
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006522 dump += mLastAnrState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006523 }
6524}
6525
6526void InputDispatcher::monitor() {
6527 // Acquire and release the lock to ensure that the dispatcher has not deadlocked.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006528 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006529 mLooper->wake();
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006530 mDispatcherIsAlive.wait(_l);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006531}
6532
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08006533/**
6534 * Wake up the dispatcher and wait until it processes all events and commands.
6535 * The notification of mDispatcherEnteredIdle is guaranteed to happen after wake(), so
6536 * this method can be safely called from any thread, as long as you've ensured that
6537 * the work you are interested in completing has already been queued.
6538 */
Siarhei Vishniakoua66d65e2023-06-16 10:32:51 -07006539bool InputDispatcher::waitForIdle() const {
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08006540 /**
6541 * Timeout should represent the longest possible time that a device might spend processing
6542 * events and commands.
6543 */
6544 constexpr std::chrono::duration TIMEOUT = 100ms;
6545 std::unique_lock lock(mLock);
6546 mLooper->wake();
6547 std::cv_status result = mDispatcherEnteredIdle.wait_for(lock, TIMEOUT);
6548 return result == std::cv_status::no_timeout;
6549}
6550
Vishnu Naire798b472020-07-23 13:52:21 -07006551/**
6552 * Sets focus to the window identified by the token. This must be called
6553 * after updating any input window handles.
6554 *
6555 * Params:
6556 * request.token - input channel token used to identify the window that should gain focus.
6557 * request.focusedToken - the token that the caller expects currently to be focused. If the
6558 * specified token does not match the currently focused window, this request will be dropped.
6559 * If the specified focused token matches the currently focused window, the call will succeed.
6560 * Set this to "null" if this call should succeed no matter what the currently focused token is.
6561 * request.timestamp - SYSTEM_TIME_MONOTONIC timestamp in nanos set by the client (wm)
6562 * when requesting the focus change. This determines which request gets
6563 * precedence if there is a focus change request from another source such as pointer down.
6564 */
Vishnu Nair958da932020-08-21 17:12:37 -07006565void InputDispatcher::setFocusedWindow(const FocusRequest& request) {
6566 { // acquire lock
6567 std::scoped_lock _l(mLock);
Vishnu Nairc519ff72021-01-21 08:23:08 -08006568 std::optional<FocusResolver::FocusChanges> changes =
6569 mFocusResolver.setFocusedWindow(request, getWindowHandlesLocked(request.displayId));
6570 if (changes) {
6571 onFocusChangedLocked(*changes);
Vishnu Nair958da932020-08-21 17:12:37 -07006572 }
6573 } // release lock
6574 // Wake up poll loop since it may need to make new input dispatching choices.
6575 mLooper->wake();
6576}
6577
Vishnu Nairc519ff72021-01-21 08:23:08 -08006578void InputDispatcher::onFocusChangedLocked(const FocusResolver::FocusChanges& changes) {
6579 if (changes.oldFocus) {
6580 std::shared_ptr<InputChannel> focusedInputChannel = getInputChannelLocked(changes.oldFocus);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006581 if (focusedInputChannel) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00006582 CancelationOptions options(CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS,
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006583 "focus left window");
6584 synthesizeCancelationEventsForInputChannelLocked(focusedInputChannel, options);
Harry Cutts33476232023-01-30 19:57:29 +00006585 enqueueFocusEventLocked(changes.oldFocus, /*hasFocus=*/false, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006586 }
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006587 }
Vishnu Nairc519ff72021-01-21 08:23:08 -08006588 if (changes.newFocus) {
Harry Cutts33476232023-01-30 19:57:29 +00006589 enqueueFocusEventLocked(changes.newFocus, /*hasFocus=*/true, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006590 }
6591
Prabir Pradhan99987712020-11-10 18:43:05 -08006592 // If a window has pointer capture, then it must have focus. We need to ensure that this
6593 // contract is upheld when pointer capture is being disabled due to a loss of window focus.
6594 // If the window loses focus before it loses pointer capture, then the window can be in a state
6595 // where it has pointer capture but not focus, violating the contract. Therefore we must
6596 // dispatch the pointer capture event before the focus event. Since focus events are added to
6597 // the front of the queue (above), we add the pointer capture event to the front of the queue
6598 // after the focus events are added. This ensures the pointer capture event ends up at the
6599 // front.
6600 disablePointerCaptureForcedLocked();
6601
Vishnu Nairc519ff72021-01-21 08:23:08 -08006602 if (mFocusedDisplayId == changes.displayId) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006603 sendFocusChangedCommandLocked(changes.oldFocus, changes.newFocus);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006604 }
6605}
Vishnu Nair958da932020-08-21 17:12:37 -07006606
Prabir Pradhan99987712020-11-10 18:43:05 -08006607void InputDispatcher::disablePointerCaptureForcedLocked() {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006608 if (!mCurrentPointerCaptureRequest.enable && !mWindowTokenWithPointerCapture) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006609 return;
6610 }
6611
6612 ALOGD_IF(DEBUG_FOCUS, "Disabling Pointer Capture because the window lost focus.");
6613
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006614 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006615 setPointerCaptureLocked(false);
6616 }
6617
6618 if (!mWindowTokenWithPointerCapture) {
6619 // No need to send capture changes because no window has capture.
6620 return;
6621 }
6622
6623 if (mPendingEvent != nullptr) {
6624 // Move the pending event to the front of the queue. This will give the chance
6625 // for the pending event to be dropped if it is a captured event.
6626 mInboundQueue.push_front(mPendingEvent);
6627 mPendingEvent = nullptr;
6628 }
6629
6630 auto entry = std::make_unique<PointerCaptureChangedEntry>(mIdGenerator.nextId(), now(),
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006631 mCurrentPointerCaptureRequest);
Prabir Pradhan99987712020-11-10 18:43:05 -08006632 mInboundQueue.push_front(std::move(entry));
6633}
6634
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006635void InputDispatcher::setPointerCaptureLocked(bool enable) {
6636 mCurrentPointerCaptureRequest.enable = enable;
6637 mCurrentPointerCaptureRequest.seq++;
6638 auto command = [this, request = mCurrentPointerCaptureRequest]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006639 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00006640 mPolicy.setPointerCapture(request);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006641 };
6642 postCommandLocked(std::move(command));
Prabir Pradhan99987712020-11-10 18:43:05 -08006643}
6644
Vishnu Nair599f1412021-06-21 10:39:58 -07006645void InputDispatcher::displayRemoved(int32_t displayId) {
6646 { // acquire lock
6647 std::scoped_lock _l(mLock);
6648 // Set an empty list to remove all handles from the specific display.
Harry Cutts101ee9b2023-07-06 18:04:14 +00006649 setInputWindowsLocked(/*windowInfoHandles=*/{}, displayId);
Vishnu Nair599f1412021-06-21 10:39:58 -07006650 setFocusedApplicationLocked(displayId, nullptr);
6651 // Call focus resolver to clean up stale requests. This must be called after input windows
6652 // have been removed for the removed display.
6653 mFocusResolver.displayRemoved(displayId);
Christine Franksb768bb42021-11-29 12:11:31 -08006654 // Reset pointer capture eligibility, regardless of previous state.
6655 std::erase(mIneligibleDisplaysForPointerCapture, displayId);
Antonio Kantek15beb512022-06-13 22:35:41 +00006656 // Remove the associated touch mode state.
6657 mTouchModePerDisplay.erase(displayId);
Siarhei Vishniakou5c02a712023-05-15 15:45:02 -07006658 mVerifiersByDisplay.erase(displayId);
Vishnu Nair599f1412021-06-21 10:39:58 -07006659 } // release lock
6660
6661 // Wake up poll loop since it may need to make new input dispatching choices.
6662 mLooper->wake();
6663}
6664
Patrick Williamsd828f302023-04-28 17:52:08 -05006665void InputDispatcher::onWindowInfosChanged(const gui::WindowInfosUpdate& update) {
chaviw15fab6f2021-06-07 14:15:52 -05006666 // The listener sends the windows as a flattened array. Separate the windows by display for
6667 // more convenient parsing.
6668 std::unordered_map<int32_t, std::vector<sp<WindowInfoHandle>>> handlesPerDisplay;
Patrick Williamsd828f302023-04-28 17:52:08 -05006669 for (const auto& info : update.windowInfos) {
chaviw15fab6f2021-06-07 14:15:52 -05006670 handlesPerDisplay.emplace(info.displayId, std::vector<sp<WindowInfoHandle>>());
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07006671 handlesPerDisplay[info.displayId].push_back(sp<WindowInfoHandle>::make(info));
chaviw15fab6f2021-06-07 14:15:52 -05006672 }
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006673
6674 { // acquire lock
6675 std::scoped_lock _l(mLock);
Prabir Pradhan814fe082022-07-22 20:22:18 +00006676
6677 // Ensure that we have an entry created for all existing displays so that if a displayId has
6678 // no windows, we can tell that the windows were removed from the display.
6679 for (const auto& [displayId, _] : mWindowHandlesByDisplay) {
6680 handlesPerDisplay[displayId];
6681 }
6682
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006683 mDisplayInfos.clear();
Patrick Williamsd828f302023-04-28 17:52:08 -05006684 for (const auto& displayInfo : update.displayInfos) {
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006685 mDisplayInfos.emplace(displayInfo.displayId, displayInfo);
6686 }
6687
6688 for (const auto& [displayId, handles] : handlesPerDisplay) {
6689 setInputWindowsLocked(handles, displayId);
6690 }
Patrick Williams9464b2c2023-05-23 11:22:04 -05006691
6692 if (update.vsyncId < mWindowInfosVsyncId) {
6693 ALOGE("Received out of order window infos update. Last update vsync id: %" PRId64
6694 ", current update vsync id: %" PRId64,
6695 mWindowInfosVsyncId, update.vsyncId);
6696 }
6697 mWindowInfosVsyncId = update.vsyncId;
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006698 }
6699 // Wake up poll loop since it may need to make new input dispatching choices.
6700 mLooper->wake();
chaviw15fab6f2021-06-07 14:15:52 -05006701}
6702
Vishnu Nair062a8672021-09-03 16:07:44 -07006703bool InputDispatcher::shouldDropInput(
6704 const EventEntry& entry, const sp<android::gui::WindowInfoHandle>& windowHandle) const {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006705 if (windowHandle->getInfo()->inputConfig.test(WindowInfo::InputConfig::DROP_INPUT) ||
6706 (windowHandle->getInfo()->inputConfig.test(
6707 WindowInfo::InputConfig::DROP_INPUT_IF_OBSCURED) &&
Vishnu Nair062a8672021-09-03 16:07:44 -07006708 isWindowObscuredLocked(windowHandle))) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006709 ALOGW("Dropping %s event targeting %s as requested by the input configuration {%s} on "
6710 "display %" PRId32 ".",
Vishnu Nair062a8672021-09-03 16:07:44 -07006711 ftl::enum_string(entry.type).c_str(), windowHandle->getName().c_str(),
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006712 windowHandle->getInfo()->inputConfig.string().c_str(),
Vishnu Nair062a8672021-09-03 16:07:44 -07006713 windowHandle->getInfo()->displayId);
6714 return true;
6715 }
6716 return false;
6717}
6718
Siarhei Vishniakou18050092021-09-01 13:32:49 -07006719void InputDispatcher::DispatcherWindowListener::onWindowInfosChanged(
Patrick Williamsd828f302023-04-28 17:52:08 -05006720 const gui::WindowInfosUpdate& update) {
6721 mDispatcher.onWindowInfosChanged(update);
Siarhei Vishniakou18050092021-09-01 13:32:49 -07006722}
6723
Arthur Hungdfd528e2021-12-08 13:23:04 +00006724void InputDispatcher::cancelCurrentTouch() {
6725 {
6726 std::scoped_lock _l(mLock);
6727 ALOGD("Canceling all ongoing pointer gestures on all displays.");
Michael Wrightfb04fd52022-11-24 22:31:11 +00006728 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
Arthur Hungdfd528e2021-12-08 13:23:04 +00006729 "cancel current touch");
6730 synthesizeCancelationEventsForAllConnectionsLocked(options);
6731
6732 mTouchStatesByDisplay.clear();
Arthur Hungdfd528e2021-12-08 13:23:04 +00006733 }
6734 // Wake up poll loop since there might be work to do.
6735 mLooper->wake();
6736}
6737
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006738void InputDispatcher::setMonitorDispatchingTimeoutForTest(std::chrono::nanoseconds timeout) {
6739 std::scoped_lock _l(mLock);
6740 mMonitorDispatchingTimeout = timeout;
6741}
6742
Arthur Hungc539dbb2022-12-08 07:45:36 +00006743void InputDispatcher::slipWallpaperTouch(ftl::Flags<InputTarget::Flags> targetFlags,
6744 const sp<WindowInfoHandle>& oldWindowHandle,
6745 const sp<WindowInfoHandle>& newWindowHandle,
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07006746 TouchState& state, int32_t deviceId, int32_t pointerId,
Siarhei Vishniakoubf880522023-05-01 11:03:22 -07006747 std::vector<InputTarget>& targets) const {
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08006748 std::bitset<MAX_POINTER_ID + 1> pointerIds;
6749 pointerIds.set(pointerId);
Arthur Hungc539dbb2022-12-08 07:45:36 +00006750 const bool oldHasWallpaper = oldWindowHandle->getInfo()->inputConfig.test(
6751 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
6752 const bool newHasWallpaper = targetFlags.test(InputTarget::Flags::FOREGROUND) &&
6753 newWindowHandle->getInfo()->inputConfig.test(
6754 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
6755 const sp<WindowInfoHandle> oldWallpaper =
6756 oldHasWallpaper ? state.getWallpaperWindow() : nullptr;
6757 const sp<WindowInfoHandle> newWallpaper =
6758 newHasWallpaper ? findWallpaperWindowBelow(newWindowHandle) : nullptr;
6759 if (oldWallpaper == newWallpaper) {
6760 return;
6761 }
6762
6763 if (oldWallpaper != nullptr) {
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08006764 const TouchedWindow& oldTouchedWindow = state.getTouchedWindow(oldWallpaper);
6765 addWindowTargetLocked(oldWallpaper,
6766 oldTouchedWindow.targetFlags |
6767 InputTarget::Flags::DISPATCH_AS_SLIPPERY_EXIT,
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07006768 pointerIds, oldTouchedWindow.getDownTimeInTarget(deviceId), targets);
6769 state.removeTouchingPointerFromWindow(deviceId, pointerId, oldWallpaper);
Arthur Hungc539dbb2022-12-08 07:45:36 +00006770 }
6771
6772 if (newWallpaper != nullptr) {
6773 state.addOrUpdateWindow(newWallpaper,
6774 InputTarget::Flags::DISPATCH_AS_SLIPPERY_ENTER |
6775 InputTarget::Flags::WINDOW_IS_OBSCURED |
6776 InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED,
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07006777 deviceId, pointerIds);
Arthur Hungc539dbb2022-12-08 07:45:36 +00006778 }
6779}
6780
6781void InputDispatcher::transferWallpaperTouch(ftl::Flags<InputTarget::Flags> oldTargetFlags,
6782 ftl::Flags<InputTarget::Flags> newTargetFlags,
6783 const sp<WindowInfoHandle> fromWindowHandle,
6784 const sp<WindowInfoHandle> toWindowHandle,
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07006785 TouchState& state, int32_t deviceId,
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08006786 std::bitset<MAX_POINTER_ID + 1> pointerIds) {
Arthur Hungc539dbb2022-12-08 07:45:36 +00006787 const bool oldHasWallpaper = oldTargetFlags.test(InputTarget::Flags::FOREGROUND) &&
6788 fromWindowHandle->getInfo()->inputConfig.test(
6789 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
6790 const bool newHasWallpaper = newTargetFlags.test(InputTarget::Flags::FOREGROUND) &&
6791 toWindowHandle->getInfo()->inputConfig.test(
6792 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
6793
6794 const sp<WindowInfoHandle> oldWallpaper =
6795 oldHasWallpaper ? state.getWallpaperWindow() : nullptr;
6796 const sp<WindowInfoHandle> newWallpaper =
6797 newHasWallpaper ? findWallpaperWindowBelow(toWindowHandle) : nullptr;
6798 if (oldWallpaper == newWallpaper) {
6799 return;
6800 }
6801
6802 if (oldWallpaper != nullptr) {
6803 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
6804 "transferring touch focus to another window");
6805 state.removeWindowByToken(oldWallpaper->getToken());
6806 synthesizeCancelationEventsForWindowLocked(oldWallpaper, options);
6807 }
6808
6809 if (newWallpaper != nullptr) {
6810 nsecs_t downTimeInTarget = now();
6811 ftl::Flags<InputTarget::Flags> wallpaperFlags =
6812 oldTargetFlags & (InputTarget::Flags::SPLIT | InputTarget::Flags::DISPATCH_AS_IS);
6813 wallpaperFlags |= InputTarget::Flags::WINDOW_IS_OBSCURED |
6814 InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED;
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07006815 state.addOrUpdateWindow(newWallpaper, wallpaperFlags, deviceId, pointerIds,
6816 downTimeInTarget);
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006817 std::shared_ptr<Connection> wallpaperConnection =
6818 getConnectionLocked(newWallpaper->getToken());
Arthur Hungc539dbb2022-12-08 07:45:36 +00006819 if (wallpaperConnection != nullptr) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006820 std::shared_ptr<Connection> toConnection =
6821 getConnectionLocked(toWindowHandle->getToken());
Arthur Hungc539dbb2022-12-08 07:45:36 +00006822 toConnection->inputState.mergePointerStateTo(wallpaperConnection->inputState);
6823 synthesizePointerDownEventsForConnectionLocked(downTimeInTarget, wallpaperConnection,
6824 wallpaperFlags);
6825 }
6826 }
6827}
6828
6829sp<WindowInfoHandle> InputDispatcher::findWallpaperWindowBelow(
6830 const sp<WindowInfoHandle>& windowHandle) const {
6831 const std::vector<sp<WindowInfoHandle>>& windowHandles =
6832 getWindowHandlesLocked(windowHandle->getInfo()->displayId);
6833 bool foundWindow = false;
6834 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
6835 if (!foundWindow && otherHandle != windowHandle) {
6836 continue;
6837 }
6838 if (windowHandle == otherHandle) {
6839 foundWindow = true;
6840 continue;
6841 }
6842
6843 if (otherHandle->getInfo()->inputConfig.test(WindowInfo::InputConfig::IS_WALLPAPER)) {
6844 return otherHandle;
6845 }
6846 }
6847 return nullptr;
6848}
6849
Nergi Rahardi730cf3c2023-04-13 12:41:17 +09006850void InputDispatcher::setKeyRepeatConfiguration(nsecs_t timeout, nsecs_t delay) {
6851 std::scoped_lock _l(mLock);
6852
6853 mConfig.keyRepeatTimeout = timeout;
6854 mConfig.keyRepeatDelay = delay;
6855}
6856
Garfield Tane84e6f92019-08-29 17:28:41 -07006857} // namespace android::inputdispatcher