blob: 6226a19897c81eb1fcada26845f1242a9a91c8df [file] [log] [blame]
Michael Wrightd02c5b62014-02-10 15:10:22 -08001/*
2 * Copyright (C) 2010 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#define LOG_TAG "InputDispatcher"
18#define ATRACE_TAG ATRACE_TAG_INPUT
19
John Recke0710582019-09-26 13:46:12 -070020#define LOG_NDEBUG 1
Michael Wrightd02c5b62014-02-10 15:10:22 -080021
Michael Wright2b3c3302018-03-02 17:19:13 +000022#include <android-base/chrono_utils.h>
Siarhei Vishniakoud010b012023-01-18 15:00:53 -080023#include <android-base/logging.h>
Peter Collingbourneb04b9b82021-02-08 12:09:47 -080024#include <android-base/properties.h>
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080025#include <android-base/stringprintf.h>
Siarhei Vishniakou70622952020-07-30 11:17:23 -050026#include <android/os/IInputConstants.h>
Robert Carr4e670e52018-08-15 13:26:12 -070027#include <binder/Binder.h>
Dominik Laskowski75788452021-02-09 18:51:25 -080028#include <ftl/enum.h>
Siarhei Vishniakou5c02a712023-05-15 15:45:02 -070029#include <log/log_event_list.h>
Siarhei Vishniakou31977182022-09-30 08:51:23 -070030#if defined(__ANDROID__)
chaviw15fab6f2021-06-07 14:15:52 -050031#include <gui/SurfaceComposerClient.h>
Siarhei Vishniakou31977182022-09-30 08:51:23 -070032#endif
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -080033#include <input/InputDevice.h>
Siarhei Vishniakou6e1e9872022-11-08 17:51:35 -080034#include <input/PrintTools.h>
Prabir Pradhana37bad12023-08-18 15:55:32 +000035#include <input/TraceTools.h>
tyiu1573a672023-02-21 22:38:32 +000036#include <openssl/mem.h>
Garfield Tan0fc2fa72019-08-29 17:22:15 -070037#include <powermanager/PowerManager.h>
Michael Wright44753b12020-07-08 13:48:11 +010038#include <unistd.h>
Garfield Tan0fc2fa72019-08-29 17:22:15 -070039#include <utils/Trace.h>
Michael Wrightd02c5b62014-02-10 15:10:22 -080040
Michael Wright44753b12020-07-08 13:48:11 +010041#include <cerrno>
42#include <cinttypes>
43#include <climits>
44#include <cstddef>
45#include <ctime>
46#include <queue>
47#include <sstream>
48
49#include "Connection.h"
Arthur Hung1a1007b2022-05-11 07:15:01 +000050#include "DebugConfig.h"
Chris Yef59a2f42020-10-16 12:55:26 -070051#include "InputDispatcher.h"
Michael Wright44753b12020-07-08 13:48:11 +010052
Michael Wrightd02c5b62014-02-10 15:10:22 -080053#define INDENT " "
54#define INDENT2 " "
55#define INDENT3 " "
56#define INDENT4 " "
57
Siarhei Vishniakou253f4642022-11-09 13:42:06 -080058using namespace android::ftl::flag_operators;
Siarhei Vishniakou23740b92023-04-21 11:30:20 -070059using android::base::Error;
Peter Collingbourneb04b9b82021-02-08 12:09:47 -080060using android::base::HwTimeoutMultiplier;
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +000061using android::base::Result;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080062using android::base::StringPrintf;
Prabir Pradhan48f8cb92021-08-26 14:05:36 -070063using android::gui::DisplayInfo;
chaviw98318de2021-05-19 16:45:23 -050064using android::gui::FocusRequest;
65using android::gui::TouchOcclusionMode;
66using android::gui::WindowInfo;
67using android::gui::WindowInfoHandle;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -080068using android::os::InputEventInjectionResult;
69using android::os::InputEventInjectionSync;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080070
Garfield Tane84e6f92019-08-29 17:28:41 -070071namespace android::inputdispatcher {
Michael Wrightd02c5b62014-02-10 15:10:22 -080072
Prabir Pradhancef936d2021-07-21 16:17:52 +000073namespace {
Prabir Pradhancef936d2021-07-21 16:17:52 +000074// Temporarily releases a held mutex for the lifetime of the instance.
75// Named to match std::scoped_lock
76class scoped_unlock {
77public:
78 explicit scoped_unlock(std::mutex& mutex) : mMutex(mutex) { mMutex.unlock(); }
79 ~scoped_unlock() { mMutex.lock(); }
80
81private:
82 std::mutex& mMutex;
83};
84
Michael Wrightd02c5b62014-02-10 15:10:22 -080085// Default input dispatching timeout if there is no focused application or paused window
86// from which to determine an appropriate dispatching timeout.
Peter Collingbourneb04b9b82021-02-08 12:09:47 -080087const std::chrono::duration DEFAULT_INPUT_DISPATCHING_TIMEOUT = std::chrono::milliseconds(
88 android::os::IInputConstants::UNMULTIPLIED_DEFAULT_DISPATCHING_TIMEOUT_MILLIS *
89 HwTimeoutMultiplier());
Michael Wrightd02c5b62014-02-10 15:10:22 -080090
91// Amount of time to allow for all pending events to be processed when an app switch
92// key is on the way. This is used to preempt input dispatch and drop input events
93// when an application takes too long to respond and the user has pressed an app switch key.
Michael Wright2b3c3302018-03-02 17:19:13 +000094constexpr nsecs_t APP_SWITCH_TIMEOUT = 500 * 1000000LL; // 0.5sec
Michael Wrightd02c5b62014-02-10 15:10:22 -080095
Siarhei Vishniakou289e9242022-02-15 14:50:16 -080096const std::chrono::duration STALE_EVENT_TIMEOUT = std::chrono::seconds(10) * HwTimeoutMultiplier();
Michael Wrightd02c5b62014-02-10 15:10:22 -080097
Michael Wrightd02c5b62014-02-10 15:10:22 -080098// Log a warning when an event takes longer than this to process, even if an ANR does not occur.
Michael Wright2b3c3302018-03-02 17:19:13 +000099constexpr nsecs_t SLOW_EVENT_PROCESSING_WARNING_TIMEOUT = 2000 * 1000000LL; // 2sec
100
101// Log a warning when an interception call takes longer than this to process.
102constexpr std::chrono::milliseconds SLOW_INTERCEPTION_THRESHOLD = 50ms;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800103
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700104// Additional key latency in case a connection is still processing some motion events.
105// This will help with the case when a user touched a button that opens a new window,
106// and gives us the chance to dispatch the key to this new window.
107constexpr std::chrono::nanoseconds KEY_WAITING_FOR_EVENTS_TIMEOUT = 500ms;
108
Michael Wrightd02c5b62014-02-10 15:10:22 -0800109// Number of recent events to keep for debugging purposes.
Michael Wright2b3c3302018-03-02 17:19:13 +0000110constexpr size_t RECENT_QUEUE_MAX_SIZE = 10;
111
Antonio Kantekea47acb2021-12-23 12:41:25 -0800112// Event log tags. See EventLogTags.logtags for reference.
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +0000113constexpr int LOGTAG_INPUT_INTERACTION = 62000;
114constexpr int LOGTAG_INPUT_FOCUS = 62001;
Arthur Hungb3307ee2021-10-14 10:57:37 +0000115constexpr int LOGTAG_INPUT_CANCEL = 62003;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +0000116
Prabir Pradhan33e3baa2022-12-06 20:30:22 +0000117const ui::Transform kIdentityTransform;
118
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000119inline nsecs_t now() {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800120 return systemTime(SYSTEM_TIME_MONOTONIC);
121}
122
Siarhei Vishniakoud38a1e02023-07-18 11:55:17 -0700123bool isEmpty(const std::stringstream& ss) {
124 return ss.rdbuf()->in_avail() == 0;
125}
126
Siarhei Vishniakou63b63612023-04-12 11:00:23 -0700127inline const std::string binderToString(const sp<IBinder>& binder) {
Bernardo Rufino49d99e42021-01-18 15:16:59 +0000128 if (binder == nullptr) {
129 return "<null>";
130 }
131 return StringPrintf("%p", binder.get());
132}
133
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +0000134static std::string uidString(const gui::Uid& uid) {
135 return uid.toString();
136}
137
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700138Result<void> checkKeyAction(int32_t action) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800139 switch (action) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700140 case AKEY_EVENT_ACTION_DOWN:
141 case AKEY_EVENT_ACTION_UP:
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700142 return {};
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700143 default:
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700144 return Error() << "Key event has invalid action code " << action;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800145 }
146}
147
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700148Result<void> validateKeyEvent(int32_t action) {
149 return checkKeyAction(action);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800150}
151
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700152Result<void> checkMotionAction(int32_t action, int32_t actionButton, int32_t pointerCount) {
Siarhei Vishniakou2f61bdc2022-12-02 08:55:51 -0800153 switch (MotionEvent::getActionMasked(action)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700154 case AMOTION_EVENT_ACTION_DOWN:
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700155 case AMOTION_EVENT_ACTION_UP: {
156 if (pointerCount != 1) {
157 return Error() << "invalid pointer count " << pointerCount;
158 }
159 return {};
160 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700161 case AMOTION_EVENT_ACTION_MOVE:
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700162 case AMOTION_EVENT_ACTION_HOVER_ENTER:
163 case AMOTION_EVENT_ACTION_HOVER_MOVE:
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700164 case AMOTION_EVENT_ACTION_HOVER_EXIT: {
165 if (pointerCount < 1) {
166 return Error() << "invalid pointer count " << pointerCount;
167 }
168 return {};
169 }
Siarhei Vishniakou2f61bdc2022-12-02 08:55:51 -0800170 case AMOTION_EVENT_ACTION_CANCEL:
171 case AMOTION_EVENT_ACTION_OUTSIDE:
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700172 case AMOTION_EVENT_ACTION_SCROLL:
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700173 return {};
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700174 case AMOTION_EVENT_ACTION_POINTER_DOWN:
175 case AMOTION_EVENT_ACTION_POINTER_UP: {
Siarhei Vishniakou2f61bdc2022-12-02 08:55:51 -0800176 const int32_t index = MotionEvent::getActionIndex(action);
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700177 if (index < 0) {
178 return Error() << "invalid index " << index << " for "
179 << MotionEvent::actionToString(action);
180 }
181 if (index >= pointerCount) {
182 return Error() << "invalid index " << index << " for pointerCount " << pointerCount;
183 }
184 if (pointerCount <= 1) {
185 return Error() << "invalid pointer count " << pointerCount << " for "
186 << MotionEvent::actionToString(action);
187 }
188 return {};
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700189 }
190 case AMOTION_EVENT_ACTION_BUTTON_PRESS:
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700191 case AMOTION_EVENT_ACTION_BUTTON_RELEASE: {
192 if (actionButton == 0) {
193 return Error() << "action button should be nonzero for "
194 << MotionEvent::actionToString(action);
195 }
196 return {};
197 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700198 default:
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700199 return Error() << "invalid action " << action;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800200 }
201}
202
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000203int64_t millis(std::chrono::nanoseconds t) {
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -0500204 return std::chrono::duration_cast<std::chrono::milliseconds>(t).count();
205}
206
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700207Result<void> validateMotionEvent(int32_t action, int32_t actionButton, size_t pointerCount,
208 const PointerProperties* pointerProperties) {
209 Result<void> actionCheck = checkMotionAction(action, actionButton, pointerCount);
210 if (!actionCheck.ok()) {
211 return actionCheck;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800212 }
213 if (pointerCount < 1 || pointerCount > MAX_POINTERS) {
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700214 return Error() << "Motion event has invalid pointer count " << pointerCount
215 << "; value must be between 1 and " << MAX_POINTERS << ".";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800216 }
Siarhei Vishniakou8a878352023-01-30 14:05:01 -0800217 std::bitset<MAX_POINTER_ID + 1> pointerIdBits;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800218 for (size_t i = 0; i < pointerCount; i++) {
219 int32_t id = pointerProperties[i].id;
220 if (id < 0 || id > MAX_POINTER_ID) {
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700221 return Error() << "Motion event has invalid pointer id " << id
222 << "; value must be between 0 and " << MAX_POINTER_ID;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800223 }
Siarhei Vishniakou8a878352023-01-30 14:05:01 -0800224 if (pointerIdBits.test(id)) {
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700225 return Error() << "Motion event has duplicate pointer id " << id;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800226 }
Siarhei Vishniakou8a878352023-01-30 14:05:01 -0800227 pointerIdBits.set(id);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800228 }
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700229 return {};
230}
231
232Result<void> validateInputEvent(const InputEvent& event) {
233 switch (event.getType()) {
234 case InputEventType::KEY: {
235 const KeyEvent& key = static_cast<const KeyEvent&>(event);
236 const int32_t action = key.getAction();
237 return validateKeyEvent(action);
238 }
239 case InputEventType::MOTION: {
240 const MotionEvent& motion = static_cast<const MotionEvent&>(event);
241 const int32_t action = motion.getAction();
242 const size_t pointerCount = motion.getPointerCount();
243 const PointerProperties* pointerProperties = motion.getPointerProperties();
244 const int32_t actionButton = motion.getActionButton();
245 return validateMotionEvent(action, actionButton, pointerCount, pointerProperties);
246 }
247 default: {
248 return {};
249 }
250 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800251}
252
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000253std::string dumpRegion(const Region& region) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800254 if (region.isEmpty()) {
Bernardo Rufino53fc31e2020-11-03 11:01:07 +0000255 return "<empty>";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800256 }
257
Bernardo Rufino53fc31e2020-11-03 11:01:07 +0000258 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800259 bool first = true;
260 Region::const_iterator cur = region.begin();
261 Region::const_iterator const tail = region.end();
262 while (cur != tail) {
263 if (first) {
264 first = false;
265 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800266 dump += "|";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800267 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800268 dump += StringPrintf("[%d,%d][%d,%d]", cur->left, cur->top, cur->right, cur->bottom);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800269 cur++;
270 }
Bernardo Rufino53fc31e2020-11-03 11:01:07 +0000271 return dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800272}
273
Prabir Pradhan8c90d782023-09-15 21:16:44 +0000274std::string dumpQueue(const std::deque<std::unique_ptr<DispatchEntry>>& queue,
275 nsecs_t currentTime) {
Siarhei Vishniakou14411c92020-09-18 21:15:05 -0500276 constexpr size_t maxEntries = 50; // max events to print
277 constexpr size_t skipBegin = maxEntries / 2;
278 const size_t skipEnd = queue.size() - maxEntries / 2;
279 // skip from maxEntries / 2 ... size() - maxEntries/2
280 // only print from 0 .. skipBegin and then from skipEnd .. size()
281
282 std::string dump;
283 for (size_t i = 0; i < queue.size(); i++) {
284 const DispatchEntry& entry = *queue[i];
285 if (i >= skipBegin && i < skipEnd) {
286 dump += StringPrintf(INDENT4 "<skipped %zu entries>\n", skipEnd - skipBegin);
287 i = skipEnd - 1; // it will be incremented to "skipEnd" by 'continue'
288 continue;
289 }
290 dump.append(INDENT4);
291 dump += entry.eventEntry->getDescription();
Siarhei Vishniakou253f4642022-11-09 13:42:06 -0800292 dump += StringPrintf(", seq=%" PRIu32 ", targetFlags=%s, resolvedAction=%d, age=%" PRId64
293 "ms",
294 entry.seq, entry.targetFlags.string().c_str(), entry.resolvedAction,
Siarhei Vishniakou14411c92020-09-18 21:15:05 -0500295 ns2ms(currentTime - entry.eventEntry->eventTime));
296 if (entry.deliveryTime != 0) {
297 // This entry was delivered, so add information on how long we've been waiting
298 dump += StringPrintf(", wait=%" PRId64 "ms", ns2ms(currentTime - entry.deliveryTime));
299 }
300 dump.append("\n");
301 }
302 return dump;
303}
304
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -0700305/**
306 * Find the entry in std::unordered_map by key, and return it.
307 * If the entry is not found, return a default constructed entry.
308 *
309 * Useful when the entries are vectors, since an empty vector will be returned
310 * if the entry is not found.
311 * Also useful when the entries are sp<>. If an entry is not found, nullptr is returned.
312 */
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700313template <typename K, typename V>
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000314V getValueByKey(const std::unordered_map<K, V>& map, K key) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -0700315 auto it = map.find(key);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700316 return it != map.end() ? it->second : V{};
Tiger Huang721e26f2018-07-24 22:26:19 +0800317}
318
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000319bool haveSameToken(const sp<WindowInfoHandle>& first, const sp<WindowInfoHandle>& second) {
chaviwaf87b3e2019-10-01 16:59:28 -0700320 if (first == second) {
321 return true;
322 }
323
324 if (first == nullptr || second == nullptr) {
325 return false;
326 }
327
328 return first->getToken() == second->getToken();
329}
330
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000331bool haveSameApplicationToken(const WindowInfo* first, const WindowInfo* second) {
Bernardo Rufino1ff9d592021-01-18 16:58:57 +0000332 if (first == nullptr || second == nullptr) {
333 return false;
334 }
335 return first->applicationInfo.token != nullptr &&
336 first->applicationInfo.token == second->applicationInfo.token;
337}
338
Siarhei Vishniakou8a878352023-01-30 14:05:01 -0800339template <typename T>
340size_t firstMarkedBit(T set) {
341 // TODO: replace with std::countr_zero from <bit> when that's available
342 LOG_ALWAYS_FATAL_IF(set.none());
343 size_t i = 0;
344 while (!set.test(i)) {
345 i++;
346 }
347 return i;
348}
349
Siarhei Vishniakou253f4642022-11-09 13:42:06 -0800350std::unique_ptr<DispatchEntry> createDispatchEntry(
351 const InputTarget& inputTarget, std::shared_ptr<EventEntry> eventEntry,
352 ftl::Flags<InputTarget::Flags> inputTargetFlags) {
chaviw1ff3d1e2020-07-01 15:53:47 -0700353 if (inputTarget.useDefaultPointerTransform()) {
354 const ui::Transform& transform = inputTarget.getDefaultPointerTransform();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700355 return std::make_unique<DispatchEntry>(eventEntry, inputTargetFlags, transform,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700356 inputTarget.displayTransform,
357 inputTarget.globalScaleFactor);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000358 }
359
360 ALOG_ASSERT(eventEntry->type == EventEntry::Type::MOTION);
361 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(*eventEntry);
362
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700363 std::vector<PointerCoords> pointerCoords;
364 pointerCoords.resize(motionEntry.pointerCount);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000365
366 // Use the first pointer information to normalize all other pointers. This could be any pointer
367 // as long as all other pointers are normalized to the same value and the final DispatchEntry
chaviw1ff3d1e2020-07-01 15:53:47 -0700368 // uses the transform for the normalized pointer.
369 const ui::Transform& firstPointerTransform =
Siarhei Vishniakou8a878352023-01-30 14:05:01 -0800370 inputTarget.pointerTransforms[firstMarkedBit(inputTarget.pointerIds)];
chaviw1ff3d1e2020-07-01 15:53:47 -0700371 ui::Transform inverseFirstTransform = firstPointerTransform.inverse();
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000372
373 // Iterate through all pointers in the event to normalize against the first.
374 for (uint32_t pointerIndex = 0; pointerIndex < motionEntry.pointerCount; pointerIndex++) {
375 const PointerProperties& pointerProperties = motionEntry.pointerProperties[pointerIndex];
376 uint32_t pointerId = uint32_t(pointerProperties.id);
chaviw1ff3d1e2020-07-01 15:53:47 -0700377 const ui::Transform& currTransform = inputTarget.pointerTransforms[pointerId];
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000378
379 pointerCoords[pointerIndex].copyFrom(motionEntry.pointerCoords[pointerIndex]);
chaviw1ff3d1e2020-07-01 15:53:47 -0700380 // First, apply the current pointer's transform to update the coordinates into
381 // window space.
382 pointerCoords[pointerIndex].transform(currTransform);
383 // Next, apply the inverse transform of the normalized coordinates so the
384 // current coordinates are transformed into the normalized coordinate space.
385 pointerCoords[pointerIndex].transform(inverseFirstTransform);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000386 }
387
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700388 std::unique_ptr<MotionEntry> combinedMotionEntry =
389 std::make_unique<MotionEntry>(motionEntry.id, motionEntry.eventTime,
390 motionEntry.deviceId, motionEntry.source,
391 motionEntry.displayId, motionEntry.policyFlags,
392 motionEntry.action, motionEntry.actionButton,
393 motionEntry.flags, motionEntry.metaState,
394 motionEntry.buttonState, motionEntry.classification,
395 motionEntry.edgeFlags, motionEntry.xPrecision,
396 motionEntry.yPrecision, motionEntry.xCursorPosition,
397 motionEntry.yCursorPosition, motionEntry.downTime,
398 motionEntry.pointerCount, motionEntry.pointerProperties,
Prabir Pradhan5beda762021-12-10 09:30:08 +0000399 pointerCoords.data());
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000400
401 if (motionEntry.injectionState) {
402 combinedMotionEntry->injectionState = motionEntry.injectionState;
403 combinedMotionEntry->injectionState->refCount += 1;
404 }
405
406 std::unique_ptr<DispatchEntry> dispatchEntry =
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700407 std::make_unique<DispatchEntry>(std::move(combinedMotionEntry), inputTargetFlags,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700408 firstPointerTransform, inputTarget.displayTransform,
409 inputTarget.globalScaleFactor);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000410 return dispatchEntry;
411}
412
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000413status_t openInputChannelPair(const std::string& name, std::shared_ptr<InputChannel>& serverChannel,
414 std::unique_ptr<InputChannel>& clientChannel) {
Garfield Tan15601662020-09-22 15:32:38 -0700415 std::unique_ptr<InputChannel> uniqueServerChannel;
416 status_t result = InputChannel::openInputChannelPair(name, uniqueServerChannel, clientChannel);
417
418 serverChannel = std::move(uniqueServerChannel);
419 return result;
420}
421
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -0500422template <typename T>
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000423bool sharedPointersEqual(const std::shared_ptr<T>& lhs, const std::shared_ptr<T>& rhs) {
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -0500424 if (lhs == nullptr && rhs == nullptr) {
425 return true;
426 }
427 if (lhs == nullptr || rhs == nullptr) {
428 return false;
429 }
430 return *lhs == *rhs;
431}
432
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000433KeyEvent createKeyEvent(const KeyEntry& entry) {
Siarhei Vishniakou2e2ea992020-12-15 02:57:19 +0000434 KeyEvent event;
435 event.initialize(entry.id, entry.deviceId, entry.source, entry.displayId, INVALID_HMAC,
436 entry.action, entry.flags, entry.keyCode, entry.scanCode, entry.metaState,
437 entry.repeatCount, entry.downTime, entry.eventTime);
438 return event;
439}
440
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000441bool shouldReportMetricsForConnection(const Connection& connection) {
Siarhei Vishniakouf2652122021-03-05 21:39:46 +0000442 // Do not keep track of gesture monitors. They receive every event and would disproportionately
443 // affect the statistics.
444 if (connection.monitor) {
445 return false;
446 }
447 // If the connection is experiencing ANR, let's skip it. We have separate ANR metrics
448 if (!connection.responsive) {
449 return false;
450 }
451 return true;
452}
453
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000454bool shouldReportFinishedEvent(const DispatchEntry& dispatchEntry, const Connection& connection) {
Siarhei Vishniakouf2652122021-03-05 21:39:46 +0000455 const EventEntry& eventEntry = *dispatchEntry.eventEntry;
456 const int32_t& inputEventId = eventEntry.id;
457 if (inputEventId != dispatchEntry.resolvedEventId) {
458 // Event was transmuted
459 return false;
460 }
461 if (inputEventId == android::os::IInputConstants::INVALID_INPUT_EVENT_ID) {
462 return false;
463 }
464 // Only track latency for events that originated from hardware
465 if (eventEntry.isSynthesized()) {
466 return false;
467 }
468 const EventEntry::Type& inputEventEntryType = eventEntry.type;
469 if (inputEventEntryType == EventEntry::Type::KEY) {
470 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
471 if (keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) {
472 return false;
473 }
474 } else if (inputEventEntryType == EventEntry::Type::MOTION) {
475 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
476 if (motionEntry.action == AMOTION_EVENT_ACTION_CANCEL ||
477 motionEntry.action == AMOTION_EVENT_ACTION_HOVER_EXIT) {
478 return false;
479 }
480 } else {
481 // Not a key or a motion
482 return false;
483 }
484 if (!shouldReportMetricsForConnection(connection)) {
485 return false;
486 }
487 return true;
488}
489
Prabir Pradhancef936d2021-07-21 16:17:52 +0000490/**
491 * Connection is responsive if it has no events in the waitQueue that are older than the
492 * current time.
493 */
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000494bool isConnectionResponsive(const Connection& connection) {
Prabir Pradhancef936d2021-07-21 16:17:52 +0000495 const nsecs_t currentTime = now();
Prabir Pradhan8c90d782023-09-15 21:16:44 +0000496 for (const auto& dispatchEntry : connection.waitQueue) {
497 if (dispatchEntry->timeoutTime < currentTime) {
Prabir Pradhancef936d2021-07-21 16:17:52 +0000498 return false;
499 }
500 }
501 return true;
502}
503
Antonio Kantekf16f2832021-09-28 04:39:20 +0000504// Returns true if the event type passed as argument represents a user activity.
505bool isUserActivityEvent(const EventEntry& eventEntry) {
506 switch (eventEntry.type) {
Josep del Riob3981622023-04-18 15:49:45 +0000507 case EventEntry::Type::CONFIGURATION_CHANGED:
508 case EventEntry::Type::DEVICE_RESET:
509 case EventEntry::Type::DRAG:
Antonio Kantekf16f2832021-09-28 04:39:20 +0000510 case EventEntry::Type::FOCUS:
511 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
Antonio Kantekf16f2832021-09-28 04:39:20 +0000512 case EventEntry::Type::SENSOR:
Josep del Riob3981622023-04-18 15:49:45 +0000513 case EventEntry::Type::TOUCH_MODE_CHANGED:
Antonio Kantekf16f2832021-09-28 04:39:20 +0000514 return false;
Antonio Kantekf16f2832021-09-28 04:39:20 +0000515 case EventEntry::Type::KEY:
516 case EventEntry::Type::MOTION:
517 return true;
518 }
519}
520
Prabir Pradhan3f90d312021-11-19 03:57:24 -0800521// Returns true if the given window can accept pointer events at the given display location.
Prabir Pradhan82e081e2022-12-06 09:50:09 +0000522bool windowAcceptsTouchAt(const WindowInfo& windowInfo, int32_t displayId, float x, float y,
Prabir Pradhan33e3baa2022-12-06 20:30:22 +0000523 bool isStylus, const ui::Transform& displayTransform) {
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -0800524 const auto inputConfig = windowInfo.inputConfig;
525 if (windowInfo.displayId != displayId ||
526 inputConfig.test(WindowInfo::InputConfig::NOT_VISIBLE)) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -0800527 return false;
528 }
Prabir Pradhand65552b2021-10-07 11:23:50 -0700529 const bool windowCanInterceptTouch = isStylus && windowInfo.interceptsStylus();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -0800530 if (inputConfig.test(WindowInfo::InputConfig::NOT_TOUCHABLE) && !windowCanInterceptTouch) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -0800531 return false;
532 }
Prabir Pradhan33e3baa2022-12-06 20:30:22 +0000533
534 // Window Manager works in the logical display coordinate space. When it specifies bounds for a
535 // window as (l, t, r, b), the range of x in [l, r) and y in [t, b) are considered to be inside
536 // the window. Points on the right and bottom edges should not be inside the window, so we need
537 // to be careful about performing a hit test when the display is rotated, since the "right" and
538 // "bottom" of the window will be different in the display (un-rotated) space compared to in the
539 // logical display in which WM determined the bounds. Perform the hit test in the logical
540 // display space to ensure these edges are considered correctly in all orientations.
541 const auto touchableRegion = displayTransform.transform(windowInfo.touchableRegion);
542 const auto p = displayTransform.transform(x, y);
543 if (!touchableRegion.contains(std::floor(p.x), std::floor(p.y))) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -0800544 return false;
545 }
546 return true;
547}
548
Prabir Pradhand65552b2021-10-07 11:23:50 -0700549bool isPointerFromStylus(const MotionEntry& entry, int32_t pointerIndex) {
550 return isFromSource(entry.source, AINPUT_SOURCE_STYLUS) &&
Prabir Pradhane5626962022-10-27 20:30:53 +0000551 isStylusToolType(entry.pointerProperties[pointerIndex].toolType);
Prabir Pradhand65552b2021-10-07 11:23:50 -0700552}
553
Siarhei Vishniakou253f4642022-11-09 13:42:06 -0800554// Determines if the given window can be targeted as InputTarget::Flags::FOREGROUND.
Prabir Pradhan6dfbf262022-03-14 15:24:30 +0000555// Foreground events are only sent to "foreground targetable" windows, but not all gestures sent to
556// such window are necessarily targeted with the flag. For example, an event with ACTION_OUTSIDE can
557// be sent to such a window, but it is not a foreground event and doesn't use
Siarhei Vishniakou253f4642022-11-09 13:42:06 -0800558// InputTarget::Flags::FOREGROUND.
Prabir Pradhan6dfbf262022-03-14 15:24:30 +0000559bool canReceiveForegroundTouches(const WindowInfo& info) {
560 // A non-touchable window can still receive touch events (e.g. in the case of
561 // STYLUS_INTERCEPTOR), so prevent such windows from receiving foreground events for touches.
562 return !info.inputConfig.test(gui::WindowInfo::InputConfig::NOT_TOUCHABLE) && !info.isSpy();
563}
564
Prabir Pradhanaeebeb42023-06-13 19:53:03 +0000565bool isWindowOwnedBy(const sp<WindowInfoHandle>& windowHandle, gui::Pid pid, gui::Uid uid) {
Antonio Kantek48710e42022-03-24 14:19:30 -0700566 if (windowHandle == nullptr) {
567 return false;
568 }
569 const WindowInfo* windowInfo = windowHandle->getInfo();
570 if (pid == windowInfo->ownerPid && uid == windowInfo->ownerUid) {
571 return true;
572 }
573 return false;
574}
575
Prabir Pradhan5735a322022-04-11 17:23:34 +0000576// Checks targeted injection using the window's owner's uid.
577// Returns an empty string if an entry can be sent to the given window, or an error message if the
578// entry is a targeted injection whose uid target doesn't match the window owner.
579std::optional<std::string> verifyTargetedInjection(const sp<WindowInfoHandle>& window,
580 const EventEntry& entry) {
581 if (entry.injectionState == nullptr || !entry.injectionState->targetUid) {
582 // The event was not injected, or the injected event does not target a window.
583 return {};
584 }
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +0000585 const auto uid = *entry.injectionState->targetUid;
Prabir Pradhan5735a322022-04-11 17:23:34 +0000586 if (window == nullptr) {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +0000587 return StringPrintf("No valid window target for injection into uid %s.",
588 uid.toString().c_str());
Prabir Pradhan5735a322022-04-11 17:23:34 +0000589 }
590 if (entry.injectionState->targetUid != window->getInfo()->ownerUid) {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +0000591 return StringPrintf("Injected event targeted at uid %s would be dispatched to window '%s' "
592 "owned by uid %s.",
593 uid.toString().c_str(), window->getName().c_str(),
594 window->getInfo()->ownerUid.toString().c_str());
Prabir Pradhan5735a322022-04-11 17:23:34 +0000595 }
596 return {};
597}
598
Prabir Pradhan82e081e2022-12-06 09:50:09 +0000599std::pair<float, float> resolveTouchedPosition(const MotionEntry& entry) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -0700600 const bool isFromMouse = isFromSource(entry.source, AINPUT_SOURCE_MOUSE);
601 // Always dispatch mouse events to cursor position.
602 if (isFromMouse) {
Prabir Pradhan82e081e2022-12-06 09:50:09 +0000603 return {entry.xCursorPosition, entry.yCursorPosition};
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -0700604 }
605
Siarhei Vishniakou5b9766d2023-07-18 14:06:29 -0700606 const int32_t pointerIndex = MotionEvent::getActionIndex(entry.action);
Prabir Pradhan82e081e2022-12-06 09:50:09 +0000607 return {entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_X),
608 entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_Y)};
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -0700609}
610
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -0700611std::optional<nsecs_t> getDownTime(const EventEntry& eventEntry) {
612 if (eventEntry.type == EventEntry::Type::KEY) {
613 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
614 return keyEntry.downTime;
615 } else if (eventEntry.type == EventEntry::Type::MOTION) {
616 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
617 return motionEntry.downTime;
618 }
619 return std::nullopt;
620}
621
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000622/**
623 * Compare the old touch state to the new touch state, and generate the corresponding touched
624 * windows (== input targets).
625 * If a window had the hovering pointer, but now it doesn't, produce HOVER_EXIT for that window.
626 * If the pointer just entered the new window, produce HOVER_ENTER.
627 * For pointers remaining in the window, produce HOVER_MOVE.
628 */
629std::vector<TouchedWindow> getHoveringWindowsLocked(const TouchState* oldState,
630 const TouchState& newTouchState,
631 const MotionEntry& entry) {
632 std::vector<TouchedWindow> out;
633 const int32_t maskedAction = MotionEvent::getActionMasked(entry.action);
634 if (maskedAction != AMOTION_EVENT_ACTION_HOVER_ENTER &&
635 maskedAction != AMOTION_EVENT_ACTION_HOVER_MOVE &&
636 maskedAction != AMOTION_EVENT_ACTION_HOVER_EXIT) {
637 // Not a hover event - don't need to do anything
638 return out;
639 }
640
641 // We should consider all hovering pointers here. But for now, just use the first one
642 const int32_t pointerId = entry.pointerProperties[0].id;
643
644 std::set<sp<WindowInfoHandle>> oldWindows;
645 if (oldState != nullptr) {
646 oldWindows = oldState->getWindowsWithHoveringPointer(entry.deviceId, pointerId);
647 }
648
649 std::set<sp<WindowInfoHandle>> newWindows =
650 newTouchState.getWindowsWithHoveringPointer(entry.deviceId, pointerId);
651
652 // If the pointer is no longer in the new window set, send HOVER_EXIT.
653 for (const sp<WindowInfoHandle>& oldWindow : oldWindows) {
654 if (newWindows.find(oldWindow) == newWindows.end()) {
655 TouchedWindow touchedWindow;
656 touchedWindow.windowHandle = oldWindow;
657 touchedWindow.targetFlags = InputTarget::Flags::DISPATCH_AS_HOVER_EXIT;
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000658 out.push_back(touchedWindow);
659 }
660 }
661
662 for (const sp<WindowInfoHandle>& newWindow : newWindows) {
663 TouchedWindow touchedWindow;
664 touchedWindow.windowHandle = newWindow;
665 if (oldWindows.find(newWindow) == oldWindows.end()) {
666 // Any windows that have this pointer now, and didn't have it before, should get
667 // HOVER_ENTER
668 touchedWindow.targetFlags = InputTarget::Flags::DISPATCH_AS_HOVER_ENTER;
669 } else {
670 // This pointer was already sent to the window. Use ACTION_HOVER_MOVE.
Siarhei Vishniakouc2eb8502023-04-11 18:33:36 -0700671 if (CC_UNLIKELY(maskedAction != AMOTION_EVENT_ACTION_HOVER_MOVE)) {
Daniel Norman7487dfa2023-08-02 16:39:45 -0700672 android::base::LogSeverity severity = android::base::LogSeverity::FATAL;
673 if (entry.flags & AMOTION_EVENT_FLAG_IS_ACCESSIBILITY_EVENT) {
674 // The Accessibility injected touch exploration event stream
675 // has known inconsistencies, so log ERROR instead of
676 // crashing the device with FATAL.
677 // TODO(b/299977100): Move a11y severity back to FATAL.
678 severity = android::base::LogSeverity::ERROR;
679 }
680 LOG(severity) << "Expected ACTION_HOVER_MOVE instead of " << entry.getDescription();
Siarhei Vishniakouc2eb8502023-04-11 18:33:36 -0700681 }
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000682 touchedWindow.targetFlags = InputTarget::Flags::DISPATCH_AS_IS;
683 }
Siarhei Vishniakou0836a302023-05-03 13:54:30 -0700684 touchedWindow.addHoveringPointer(entry.deviceId, pointerId);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000685 if (canReceiveForegroundTouches(*newWindow->getInfo())) {
686 touchedWindow.targetFlags |= InputTarget::Flags::FOREGROUND;
687 }
688 out.push_back(touchedWindow);
689 }
690 return out;
691}
692
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -0800693template <typename T>
694std::vector<T>& operator+=(std::vector<T>& left, const std::vector<T>& right) {
695 left.insert(left.end(), right.begin(), right.end());
696 return left;
697}
698
Harry Cuttsb166c002023-05-09 13:06:05 +0000699// Filter windows in a TouchState and targets in a vector to remove untrusted windows/targets from
700// both.
701void filterUntrustedTargets(TouchState& touchState, std::vector<InputTarget>& targets) {
702 std::erase_if(touchState.windows, [&](const TouchedWindow& window) {
703 if (!window.windowHandle->getInfo()->inputConfig.test(
704 WindowInfo::InputConfig::TRUSTED_OVERLAY)) {
705 // In addition to TouchState, erase this window from the input targets! We don't have a
706 // good way to do this today except by adding a nested loop.
707 // TODO(b/282025641): simplify this code once InputTargets are being identified
708 // separately from TouchedWindows.
709 std::erase_if(targets, [&](const InputTarget& target) {
710 return target.inputChannel->getConnectionToken() == window.windowHandle->getToken();
711 });
712 return true;
713 }
714 return false;
715 });
716}
717
Siarhei Vishniakouce1fd472023-09-18 18:38:07 -0700718/**
719 * In general, touch should be always split between windows. Some exceptions:
720 * 1. Don't split touch if all of the below is true:
721 * (a) we have an active pointer down *and*
722 * (b) a new pointer is going down that's from the same device *and*
723 * (c) the window that's receiving the current pointer does not support split touch.
724 * 2. Don't split mouse events
725 */
726bool shouldSplitTouch(const TouchState& touchState, const MotionEntry& entry) {
727 if (isFromSource(entry.source, AINPUT_SOURCE_MOUSE)) {
728 // We should never split mouse events
729 return false;
730 }
731 for (const TouchedWindow& touchedWindow : touchState.windows) {
732 if (touchedWindow.windowHandle->getInfo()->isSpy()) {
733 // Spy windows should not affect whether or not touch is split.
734 continue;
735 }
736 if (touchedWindow.windowHandle->getInfo()->supportsSplitTouch()) {
737 continue;
738 }
739 if (touchedWindow.windowHandle->getInfo()->inputConfig.test(
740 gui::WindowInfo::InputConfig::IS_WALLPAPER)) {
741 // Wallpaper window should not affect whether or not touch is split
742 continue;
743 }
744
745 if (touchedWindow.hasTouchingPointers(entry.deviceId)) {
746 return false;
747 }
748 }
749 return true;
750}
751
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000752} // namespace
753
Michael Wrightd02c5b62014-02-10 15:10:22 -0800754// --- InputDispatcher ---
755
Prabir Pradhana41d2442023-04-20 21:30:40 +0000756InputDispatcher::InputDispatcher(InputDispatcherPolicyInterface& policy)
Siarhei Vishniakou289e9242022-02-15 14:50:16 -0800757 : InputDispatcher(policy, STALE_EVENT_TIMEOUT) {}
758
Prabir Pradhana41d2442023-04-20 21:30:40 +0000759InputDispatcher::InputDispatcher(InputDispatcherPolicyInterface& policy,
Siarhei Vishniakou289e9242022-02-15 14:50:16 -0800760 std::chrono::nanoseconds staleEventTimeout)
Garfield Tan00f511d2019-06-12 16:55:40 -0700761 : mPolicy(policy),
762 mPendingEvent(nullptr),
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700763 mLastDropReason(DropReason::NOT_DROPPED),
Garfield Tanff1f1bb2020-01-28 13:24:04 -0800764 mIdGenerator(IdGenerator::Source::INPUT_DISPATCHER),
Garfield Tan00f511d2019-06-12 16:55:40 -0700765 mAppSwitchSawKeyDown(false),
Colin Cross5b799302022-10-18 21:52:41 -0700766 mAppSwitchDueTime(LLONG_MAX),
Garfield Tan00f511d2019-06-12 16:55:40 -0700767 mNextUnblockedEvent(nullptr),
Prabir Pradhan1376fcd2022-01-21 09:56:35 -0800768 mMonitorDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT),
Garfield Tan00f511d2019-06-12 16:55:40 -0700769 mDispatchEnabled(false),
770 mDispatchFrozen(false),
771 mInputFilterEnabled(false),
Bernardo Rufinoea97d182020-08-19 14:43:14 +0100772 mMaximumObscuringOpacityForTouch(1.0f),
Siarhei Vishniakou2508b872020-12-03 16:33:53 -1000773 mFocusedDisplayId(ADISPLAY_ID_DEFAULT),
Prabir Pradhan99987712020-11-10 18:43:05 -0800774 mWindowTokenWithPointerCapture(nullptr),
Siarhei Vishniakou289e9242022-02-15 14:50:16 -0800775 mStaleEventTimeout(staleEventTimeout),
Siarhei Vishniakoua04181f2021-03-26 05:56:49 +0000776 mLatencyAggregator(),
Antonio Kantek15beb512022-06-13 22:35:41 +0000777 mLatencyTracker(&mLatencyAggregator) {
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -0700778 mLooper = sp<Looper>::make(false);
Prabir Pradhanf93562f2018-11-29 12:13:37 -0800779 mReporter = createInputReporter();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800780
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -0700781 mWindowInfoListener = sp<DispatcherWindowListener>::make(*this);
Siarhei Vishniakou31977182022-09-30 08:51:23 -0700782#if defined(__ANDROID__)
Siarhei Vishniakou18050092021-09-01 13:32:49 -0700783 SurfaceComposerClient::getDefault()->addWindowInfosListener(mWindowInfoListener);
Siarhei Vishniakou31977182022-09-30 08:51:23 -0700784#endif
Yi Kong9b14ac62018-07-17 13:48:38 -0700785 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800786}
787
788InputDispatcher::~InputDispatcher() {
Prabir Pradhancef936d2021-07-21 16:17:52 +0000789 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800790
Prabir Pradhancef936d2021-07-21 16:17:52 +0000791 resetKeyRepeatLocked();
792 releasePendingEventLocked();
793 drainInboundQueueLocked();
794 mCommandQueue.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800795
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +0000796 while (!mConnectionsByToken.empty()) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -0700797 std::shared_ptr<Connection> connection = mConnectionsByToken.begin()->second;
Harry Cutts33476232023-01-30 19:57:29 +0000798 removeInputChannelLocked(connection->inputChannel->getConnectionToken(), /*notify=*/false);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800799 }
800}
801
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700802status_t InputDispatcher::start() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700803 if (mThread) {
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700804 return ALREADY_EXISTS;
805 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700806 mThread = std::make_unique<InputThread>(
807 "InputDispatcher", [this]() { dispatchOnce(); }, [this]() { mLooper->wake(); });
808 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700809}
810
811status_t InputDispatcher::stop() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700812 if (mThread && mThread->isCallingThread()) {
813 ALOGE("InputDispatcher cannot be stopped from its own thread!");
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700814 return INVALID_OPERATION;
815 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700816 mThread.reset();
817 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700818}
819
Michael Wrightd02c5b62014-02-10 15:10:22 -0800820void InputDispatcher::dispatchOnce() {
Colin Cross5b799302022-10-18 21:52:41 -0700821 nsecs_t nextWakeupTime = LLONG_MAX;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800822 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -0800823 std::scoped_lock _l(mLock);
824 mDispatcherIsAlive.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800825
826 // Run a dispatch loop if there are no pending commands.
827 // The dispatch loop might enqueue commands to run afterwards.
828 if (!haveCommandsLocked()) {
829 dispatchOnceInnerLocked(&nextWakeupTime);
830 }
831
832 // Run all pending commands if there are any.
833 // If any commands were run then force the next poll to wake up immediately.
Prabir Pradhancef936d2021-07-21 16:17:52 +0000834 if (runCommandsLockedInterruptable()) {
Colin Cross5b799302022-10-18 21:52:41 -0700835 nextWakeupTime = LLONG_MIN;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800836 }
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800837
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700838 // If we are still waiting for ack on some events,
839 // we might have to wake up earlier to check if an app is anr'ing.
840 const nsecs_t nextAnrCheck = processAnrsLocked();
841 nextWakeupTime = std::min(nextWakeupTime, nextAnrCheck);
842
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800843 // We are about to enter an infinitely long sleep, because we have no commands or
844 // pending or queued events
Colin Cross5b799302022-10-18 21:52:41 -0700845 if (nextWakeupTime == LLONG_MAX) {
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800846 mDispatcherEnteredIdle.notify_all();
847 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800848 } // release lock
849
850 // Wait for callback or timeout or wake. (make sure we round up, not down)
851 nsecs_t currentTime = now();
852 int timeoutMillis = toMillisecondTimeoutDelay(currentTime, nextWakeupTime);
853 mLooper->pollOnce(timeoutMillis);
854}
855
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700856/**
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500857 * Raise ANR if there is no focused window.
858 * Before the ANR is raised, do a final state check:
859 * 1. The currently focused application must be the same one we are waiting for.
860 * 2. Ensure we still don't have a focused window.
861 */
862void InputDispatcher::processNoFocusedWindowAnrLocked() {
863 // Check if the application that we are waiting for is still focused.
864 std::shared_ptr<InputApplicationHandle> focusedApplication =
865 getValueByKey(mFocusedApplicationHandlesByDisplay, mAwaitedApplicationDisplayId);
866 if (focusedApplication == nullptr ||
867 focusedApplication->getApplicationToken() !=
868 mAwaitedFocusedApplication->getApplicationToken()) {
869 // Unexpected because we should have reset the ANR timer when focused application changed
870 ALOGE("Waited for a focused window, but focused application has already changed to %s",
871 focusedApplication->getName().c_str());
872 return; // The focused application has changed.
873 }
874
chaviw98318de2021-05-19 16:45:23 -0500875 const sp<WindowInfoHandle>& focusedWindowHandle =
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500876 getFocusedWindowHandleLocked(mAwaitedApplicationDisplayId);
877 if (focusedWindowHandle != nullptr) {
878 return; // We now have a focused window. No need for ANR.
879 }
880 onAnrLocked(mAwaitedFocusedApplication);
881}
882
883/**
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700884 * Check if any of the connections' wait queues have events that are too old.
885 * If we waited for events to be ack'ed for more than the window timeout, raise an ANR.
886 * Return the time at which we should wake up next.
887 */
888nsecs_t InputDispatcher::processAnrsLocked() {
889 const nsecs_t currentTime = now();
Colin Cross5b799302022-10-18 21:52:41 -0700890 nsecs_t nextAnrCheck = LLONG_MAX;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700891 // Check if we are waiting for a focused window to appear. Raise ANR if waited too long
892 if (mNoFocusedWindowTimeoutTime.has_value() && mAwaitedFocusedApplication != nullptr) {
893 if (currentTime >= *mNoFocusedWindowTimeoutTime) {
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500894 processNoFocusedWindowAnrLocked();
Chris Yea209fde2020-07-22 13:54:51 -0700895 mAwaitedFocusedApplication.reset();
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500896 mNoFocusedWindowTimeoutTime = std::nullopt;
Colin Cross5b799302022-10-18 21:52:41 -0700897 return LLONG_MIN;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700898 } else {
Siarhei Vishniakou38a6d272020-10-20 20:29:33 -0500899 // Keep waiting. We will drop the event when mNoFocusedWindowTimeoutTime comes.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700900 nextAnrCheck = *mNoFocusedWindowTimeoutTime;
901 }
902 }
903
904 // Check if any connection ANRs are due
905 nextAnrCheck = std::min(nextAnrCheck, mAnrTracker.firstTimeout());
906 if (currentTime < nextAnrCheck) { // most likely scenario
907 return nextAnrCheck; // everything is normal. Let's check again at nextAnrCheck
908 }
909
910 // If we reached here, we have an unresponsive connection.
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -0700911 std::shared_ptr<Connection> connection = getConnectionLocked(mAnrTracker.firstToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700912 if (connection == nullptr) {
913 ALOGE("Could not find connection for entry %" PRId64, mAnrTracker.firstTimeout());
914 return nextAnrCheck;
915 }
916 connection->responsive = false;
917 // Stop waking up for this unresponsive connection
918 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000919 onAnrLocked(connection);
Colin Cross5b799302022-10-18 21:52:41 -0700920 return LLONG_MIN;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700921}
922
Prabir Pradhan1376fcd2022-01-21 09:56:35 -0800923std::chrono::nanoseconds InputDispatcher::getDispatchingTimeoutLocked(
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -0700924 const std::shared_ptr<Connection>& connection) {
Prabir Pradhan1376fcd2022-01-21 09:56:35 -0800925 if (connection->monitor) {
926 return mMonitorDispatchingTimeout;
927 }
928 const sp<WindowInfoHandle> window =
929 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700930 if (window != nullptr) {
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500931 return window->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700932 }
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500933 return DEFAULT_INPUT_DISPATCHING_TIMEOUT;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700934}
935
Michael Wrightd02c5b62014-02-10 15:10:22 -0800936void InputDispatcher::dispatchOnceInnerLocked(nsecs_t* nextWakeupTime) {
937 nsecs_t currentTime = now();
938
Jeff Browndc5992e2014-04-11 01:27:26 -0700939 // Reset the key repeat timer whenever normal dispatch is suspended while the
940 // device is in a non-interactive state. This is to ensure that we abort a key
941 // repeat if the device is just coming out of sleep.
942 if (!mDispatchEnabled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800943 resetKeyRepeatLocked();
944 }
945
946 // If dispatching is frozen, do not process timeouts or try to deliver any new events.
947 if (mDispatchFrozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +0100948 if (DEBUG_FOCUS) {
949 ALOGD("Dispatch frozen. Waiting some more.");
950 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800951 return;
952 }
953
954 // Optimize latency of app switches.
955 // Essentially we start a short timeout when an app switch key (HOME / ENDCALL) has
956 // been pressed. When it expires, we preempt dispatch and drop all other pending events.
957 bool isAppSwitchDue = mAppSwitchDueTime <= currentTime;
958 if (mAppSwitchDueTime < *nextWakeupTime) {
959 *nextWakeupTime = mAppSwitchDueTime;
960 }
961
962 // Ready to start a new event.
963 // If we don't already have a pending event, go grab one.
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700964 if (!mPendingEvent) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700965 if (mInboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800966 if (isAppSwitchDue) {
967 // The inbound queue is empty so the app switch key we were waiting
968 // for will never arrive. Stop waiting for it.
969 resetPendingAppSwitchLocked(false);
970 isAppSwitchDue = false;
971 }
972
973 // Synthesize a key repeat if appropriate.
974 if (mKeyRepeatState.lastKeyEntry) {
975 if (currentTime >= mKeyRepeatState.nextRepeatTime) {
976 mPendingEvent = synthesizeKeyRepeatLocked(currentTime);
977 } else {
978 if (mKeyRepeatState.nextRepeatTime < *nextWakeupTime) {
979 *nextWakeupTime = mKeyRepeatState.nextRepeatTime;
980 }
981 }
982 }
983
984 // Nothing to do if there is no pending event.
985 if (!mPendingEvent) {
986 return;
987 }
988 } else {
989 // Inbound queue has at least one entry.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700990 mPendingEvent = mInboundQueue.front();
991 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800992 traceInboundQueueLengthLocked();
993 }
994
995 // Poke user activity for this event.
996 if (mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700997 pokeUserActivityLocked(*mPendingEvent);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800998 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800999 }
1000
1001 // Now we have an event to dispatch.
1002 // All events are eventually dequeued and processed this way, even if we intend to drop them.
Yi Kong9b14ac62018-07-17 13:48:38 -07001003 ALOG_ASSERT(mPendingEvent != nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001004 bool done = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001005 DropReason dropReason = DropReason::NOT_DROPPED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001006 if (!(mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001007 dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001008 } else if (!mDispatchEnabled) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001009 dropReason = DropReason::DISABLED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001010 }
1011
1012 if (mNextUnblockedEvent == mPendingEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001013 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001014 }
1015
1016 switch (mPendingEvent->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001017 case EventEntry::Type::CONFIGURATION_CHANGED: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001018 const ConfigurationChangedEntry& typedEntry =
1019 static_cast<const ConfigurationChangedEntry&>(*mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001020 done = dispatchConfigurationChangedLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001021 dropReason = DropReason::NOT_DROPPED; // configuration changes are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001022 break;
1023 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001024
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001025 case EventEntry::Type::DEVICE_RESET: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001026 const DeviceResetEntry& typedEntry =
1027 static_cast<const DeviceResetEntry&>(*mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001028 done = dispatchDeviceResetLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001029 dropReason = DropReason::NOT_DROPPED; // device resets are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001030 break;
1031 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001032
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001033 case EventEntry::Type::FOCUS: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001034 std::shared_ptr<FocusEntry> typedEntry =
1035 std::static_pointer_cast<FocusEntry>(mPendingEvent);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001036 dispatchFocusLocked(currentTime, typedEntry);
1037 done = true;
1038 dropReason = DropReason::NOT_DROPPED; // focus events are never dropped
1039 break;
1040 }
1041
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001042 case EventEntry::Type::TOUCH_MODE_CHANGED: {
1043 const auto typedEntry = std::static_pointer_cast<TouchModeEntry>(mPendingEvent);
1044 dispatchTouchModeChangeLocked(currentTime, typedEntry);
1045 done = true;
1046 dropReason = DropReason::NOT_DROPPED; // touch mode events are never dropped
1047 break;
1048 }
1049
Prabir Pradhan99987712020-11-10 18:43:05 -08001050 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
1051 const auto typedEntry =
1052 std::static_pointer_cast<PointerCaptureChangedEntry>(mPendingEvent);
1053 dispatchPointerCaptureChangedLocked(currentTime, typedEntry, dropReason);
1054 done = true;
1055 break;
1056 }
1057
arthurhungb89ccb02020-12-30 16:19:01 +08001058 case EventEntry::Type::DRAG: {
1059 std::shared_ptr<DragEntry> typedEntry =
1060 std::static_pointer_cast<DragEntry>(mPendingEvent);
1061 dispatchDragLocked(currentTime, typedEntry);
1062 done = true;
1063 break;
1064 }
1065
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001066 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001067 std::shared_ptr<KeyEntry> keyEntry = std::static_pointer_cast<KeyEntry>(mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001068 if (isAppSwitchDue) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001069 if (isAppSwitchKeyEvent(*keyEntry)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001070 resetPendingAppSwitchLocked(true);
1071 isAppSwitchDue = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001072 } else if (dropReason == DropReason::NOT_DROPPED) {
1073 dropReason = DropReason::APP_SWITCH;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001074 }
1075 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001076 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *keyEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001077 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001078 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001079 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
1080 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001081 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001082 done = dispatchKeyLocked(currentTime, keyEntry, &dropReason, nextWakeupTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001083 break;
1084 }
1085
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001086 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001087 std::shared_ptr<MotionEntry> motionEntry =
1088 std::static_pointer_cast<MotionEntry>(mPendingEvent);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001089 if (dropReason == DropReason::NOT_DROPPED && isAppSwitchDue) {
1090 dropReason = DropReason::APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001091 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001092 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *motionEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001093 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001094 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001095 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
1096 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001097 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001098 done = dispatchMotionLocked(currentTime, motionEntry, &dropReason, nextWakeupTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001099 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001100 }
Chris Yef59a2f42020-10-16 12:55:26 -07001101
1102 case EventEntry::Type::SENSOR: {
1103 std::shared_ptr<SensorEntry> sensorEntry =
1104 std::static_pointer_cast<SensorEntry>(mPendingEvent);
1105 if (dropReason == DropReason::NOT_DROPPED && isAppSwitchDue) {
1106 dropReason = DropReason::APP_SWITCH;
1107 }
1108 // Sensor timestamps use SYSTEM_TIME_BOOTTIME time base, so we can't use
1109 // 'currentTime' here, get SYSTEM_TIME_BOOTTIME instead.
1110 nsecs_t bootTime = systemTime(SYSTEM_TIME_BOOTTIME);
1111 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(bootTime, *sensorEntry)) {
1112 dropReason = DropReason::STALE;
1113 }
1114 dispatchSensorLocked(currentTime, sensorEntry, &dropReason, nextWakeupTime);
1115 done = true;
1116 break;
1117 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001118 }
1119
1120 if (done) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001121 if (dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001122 dropInboundEventLocked(*mPendingEvent, dropReason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001123 }
Michael Wright3a981722015-06-10 15:26:13 +01001124 mLastDropReason = dropReason;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001125
1126 releasePendingEventLocked();
Colin Cross5b799302022-10-18 21:52:41 -07001127 *nextWakeupTime = LLONG_MIN; // force next poll to wake up immediately
Michael Wrightd02c5b62014-02-10 15:10:22 -08001128 }
1129}
1130
Siarhei Vishniakou289e9242022-02-15 14:50:16 -08001131bool InputDispatcher::isStaleEvent(nsecs_t currentTime, const EventEntry& entry) {
1132 return std::chrono::nanoseconds(currentTime - entry.eventTime) >= mStaleEventTimeout;
1133}
1134
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001135/**
1136 * Return true if the events preceding this incoming motion event should be dropped
1137 * Return false otherwise (the default behaviour)
1138 */
1139bool InputDispatcher::shouldPruneInboundQueueLocked(const MotionEntry& motionEntry) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001140 const bool isPointerDownEvent = motionEntry.action == AMOTION_EVENT_ACTION_DOWN &&
Prabir Pradhanaa561d12021-09-24 06:57:33 -07001141 isFromSource(motionEntry.source, AINPUT_SOURCE_CLASS_POINTER);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001142
1143 // Optimize case where the current application is unresponsive and the user
1144 // decides to touch a window in a different application.
1145 // If the application takes too long to catch up then we drop all events preceding
1146 // the touch into the other window.
1147 if (isPointerDownEvent && mAwaitedFocusedApplication != nullptr) {
Siarhei Vishniakou9306c382022-09-30 15:30:31 -07001148 const int32_t displayId = motionEntry.displayId;
1149 const auto [x, y] = resolveTouchedPosition(motionEntry);
Harry Cutts33476232023-01-30 19:57:29 +00001150 const bool isStylus = isPointerFromStylus(motionEntry, /*pointerIndex=*/0);
Siarhei Vishniakou9306c382022-09-30 15:30:31 -07001151
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07001152 sp<WindowInfoHandle> touchedWindowHandle =
1153 findTouchedWindowAtLocked(displayId, x, y, isStylus);
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001154 if (touchedWindowHandle != nullptr &&
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001155 touchedWindowHandle->getApplicationToken() !=
1156 mAwaitedFocusedApplication->getApplicationToken()) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001157 // User touched a different application than the one we are waiting on.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001158 ALOGI("Pruning input queue because user touched a different application while waiting "
1159 "for %s",
1160 mAwaitedFocusedApplication->getName().c_str());
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001161 return true;
1162 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001163
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08001164 // Alternatively, maybe there's a spy window that could handle this event.
1165 const std::vector<sp<WindowInfoHandle>> touchedSpies =
1166 findTouchedSpyWindowsAtLocked(displayId, x, y, isStylus);
1167 for (const auto& windowHandle : touchedSpies) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07001168 const std::shared_ptr<Connection> connection =
1169 getConnectionLocked(windowHandle->getToken());
Siarhei Vishniakou34ed4d42020-06-18 00:43:02 +00001170 if (connection != nullptr && connection->responsive) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08001171 // This spy window could take more input. Drop all events preceding this
1172 // event, so that the spy window can get a chance to receive the stream.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001173 ALOGW("Pruning the input queue because %s is unresponsive, but we have a "
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08001174 "responsive spy window that may handle the event.",
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001175 mAwaitedFocusedApplication->getName().c_str());
1176 return true;
1177 }
1178 }
1179 }
1180
1181 // Prevent getting stuck: if we have a pending key event, and some motion events that have not
1182 // yet been processed by some connections, the dispatcher will wait for these motion
1183 // events to be processed before dispatching the key event. This is because these motion events
1184 // may cause a new window to be launched, which the user might expect to receive focus.
1185 // To prevent waiting forever for such events, just send the key to the currently focused window
1186 if (isPointerDownEvent && mKeyIsWaitingForEventsTimeout) {
1187 ALOGD("Received a new pointer down event, stop waiting for events to process and "
1188 "just send the pending key event to the focused window.");
1189 mKeyIsWaitingForEventsTimeout = now();
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001190 }
1191 return false;
1192}
1193
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001194bool InputDispatcher::enqueueInboundEventLocked(std::unique_ptr<EventEntry> newEntry) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001195 bool needWake = mInboundQueue.empty();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001196 mInboundQueue.push_back(std::move(newEntry));
1197 EventEntry& entry = *(mInboundQueue.back());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001198 traceInboundQueueLengthLocked();
1199
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001200 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001201 case EventEntry::Type::KEY: {
Prabir Pradhan5735a322022-04-11 17:23:34 +00001202 LOG_ALWAYS_FATAL_IF((entry.policyFlags & POLICY_FLAG_TRUSTED) == 0,
1203 "Unexpected untrusted event.");
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001204 // Optimize app switch latency.
1205 // If the application takes too long to catch up then we drop all events preceding
1206 // the app switch key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001207 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001208 if (isAppSwitchKeyEvent(keyEntry)) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001209 if (keyEntry.action == AKEY_EVENT_ACTION_DOWN) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001210 mAppSwitchSawKeyDown = true;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001211 } else if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001212 if (mAppSwitchSawKeyDown) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001213 if (DEBUG_APP_SWITCH) {
1214 ALOGD("App switch is pending!");
1215 }
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001216 mAppSwitchDueTime = keyEntry.eventTime + APP_SWITCH_TIMEOUT;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001217 mAppSwitchSawKeyDown = false;
1218 needWake = true;
1219 }
1220 }
1221 }
Arthur Hung2ee6d0b2022-03-03 20:19:38 +08001222
1223 // If a new up event comes in, and the pending event with same key code has been asked
1224 // to try again later because of the policy. We have to reset the intercept key wake up
1225 // time for it may have been handled in the policy and could be dropped.
1226 if (keyEntry.action == AKEY_EVENT_ACTION_UP && mPendingEvent &&
1227 mPendingEvent->type == EventEntry::Type::KEY) {
1228 KeyEntry& pendingKey = static_cast<KeyEntry&>(*mPendingEvent);
1229 if (pendingKey.keyCode == keyEntry.keyCode &&
1230 pendingKey.interceptKeyResult ==
Michael Wright5caf55a2022-11-24 22:31:42 +00001231 KeyEntry::InterceptKeyResult::TRY_AGAIN_LATER) {
1232 pendingKey.interceptKeyResult = KeyEntry::InterceptKeyResult::UNKNOWN;
Arthur Hung2ee6d0b2022-03-03 20:19:38 +08001233 pendingKey.interceptKeyWakeupTime = 0;
1234 needWake = true;
1235 }
1236 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001237 break;
1238 }
1239
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001240 case EventEntry::Type::MOTION: {
Prabir Pradhan5735a322022-04-11 17:23:34 +00001241 LOG_ALWAYS_FATAL_IF((entry.policyFlags & POLICY_FLAG_TRUSTED) == 0,
1242 "Unexpected untrusted event.");
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001243 if (shouldPruneInboundQueueLocked(static_cast<MotionEntry&>(entry))) {
1244 mNextUnblockedEvent = mInboundQueue.back();
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001245 needWake = true;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001246 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001247 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001248 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001249 case EventEntry::Type::FOCUS: {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001250 LOG_ALWAYS_FATAL("Focus events should be inserted using enqueueFocusEventLocked");
1251 break;
1252 }
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001253 case EventEntry::Type::TOUCH_MODE_CHANGED:
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001254 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08001255 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07001256 case EventEntry::Type::SENSOR:
arthurhungb89ccb02020-12-30 16:19:01 +08001257 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
1258 case EventEntry::Type::DRAG: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001259 // nothing to do
1260 break;
1261 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001262 }
1263
1264 return needWake;
1265}
1266
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001267void InputDispatcher::addRecentEventLocked(std::shared_ptr<EventEntry> entry) {
Chris Yef59a2f42020-10-16 12:55:26 -07001268 // Do not store sensor event in recent queue to avoid flooding the queue.
1269 if (entry->type != EventEntry::Type::SENSOR) {
1270 mRecentQueue.push_back(entry);
1271 }
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001272 if (mRecentQueue.size() > RECENT_QUEUE_MAX_SIZE) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001273 mRecentQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001274 }
1275}
1276
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07001277sp<WindowInfoHandle> InputDispatcher::findTouchedWindowAtLocked(int32_t displayId, float x, float y,
1278 bool isStylus,
1279 bool ignoreDragWindow) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001280 // Traverse windows from front to back to find touched window.
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001281 const auto& windowHandles = getWindowHandlesLocked(displayId);
chaviw98318de2021-05-19 16:45:23 -05001282 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
arthurhung6d4bed92021-03-17 11:59:33 +08001283 if (ignoreDragWindow && haveSameToken(windowHandle, mDragState->dragWindow)) {
arthurhungb89ccb02020-12-30 16:19:01 +08001284 continue;
1285 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001286
Prabir Pradhan3f90d312021-11-19 03:57:24 -08001287 const WindowInfo& info = *windowHandle->getInfo();
Prabir Pradhan33e3baa2022-12-06 20:30:22 +00001288 if (!info.isSpy() &&
1289 windowAcceptsTouchAt(info, displayId, x, y, isStylus, getTransformLocked(displayId))) {
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07001290 return windowHandle;
1291 }
1292 }
1293 return nullptr;
1294}
1295
1296std::vector<InputTarget> InputDispatcher::findOutsideTargetsLocked(
Siarhei Vishniakou70f3d8c2023-09-19 15:36:52 -07001297 int32_t displayId, const sp<WindowInfoHandle>& touchedWindow, int32_t pointerId) const {
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07001298 if (touchedWindow == nullptr) {
1299 return {};
1300 }
1301 // Traverse windows from front to back until we encounter the touched window.
1302 std::vector<InputTarget> outsideTargets;
1303 const auto& windowHandles = getWindowHandlesLocked(displayId);
1304 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
1305 if (windowHandle == touchedWindow) {
1306 // Stop iterating once we found a touched window. Any WATCH_OUTSIDE_TOUCH window
1307 // below the touched window will not get ACTION_OUTSIDE event.
1308 return outsideTargets;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08001309 }
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001310
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07001311 const WindowInfo& info = *windowHandle->getInfo();
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08001312 if (info.inputConfig.test(WindowInfo::InputConfig::WATCH_OUTSIDE_TOUCH)) {
Siarhei Vishniakou70f3d8c2023-09-19 15:36:52 -07001313 std::bitset<MAX_POINTER_ID + 1> pointerIds;
1314 pointerIds.set(pointerId);
1315 addWindowTargetLocked(windowHandle, InputTarget::Flags::DISPATCH_AS_OUTSIDE, pointerIds,
1316 /*firstDownTimeInTarget=*/std::nullopt, outsideTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001317 }
1318 }
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07001319 return outsideTargets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001320}
1321
Prabir Pradhand65552b2021-10-07 11:23:50 -07001322std::vector<sp<WindowInfoHandle>> InputDispatcher::findTouchedSpyWindowsAtLocked(
Prabir Pradhan82e081e2022-12-06 09:50:09 +00001323 int32_t displayId, float x, float y, bool isStylus) const {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001324 // Traverse windows from front to back and gather the touched spy windows.
1325 std::vector<sp<WindowInfoHandle>> spyWindows;
1326 const auto& windowHandles = getWindowHandlesLocked(displayId);
1327 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
1328 const WindowInfo& info = *windowHandle->getInfo();
1329
Prabir Pradhan33e3baa2022-12-06 20:30:22 +00001330 if (!windowAcceptsTouchAt(info, displayId, x, y, isStylus, getTransformLocked(displayId))) {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001331 continue;
1332 }
1333 if (!info.isSpy()) {
1334 // The first touched non-spy window was found, so return the spy windows touched so far.
1335 return spyWindows;
1336 }
1337 spyWindows.push_back(windowHandle);
1338 }
1339 return spyWindows;
1340}
1341
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001342void InputDispatcher::dropInboundEventLocked(const EventEntry& entry, DropReason dropReason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001343 const char* reason;
1344 switch (dropReason) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001345 case DropReason::POLICY:
Prabir Pradhan65613802023-02-22 23:36:58 +00001346 if (debugInboundEventDetails()) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001347 ALOGD("Dropped event because policy consumed it.");
1348 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001349 reason = "inbound event was dropped because the policy consumed it";
1350 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001351 case DropReason::DISABLED:
1352 if (mLastDropReason != DropReason::DISABLED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001353 ALOGI("Dropped event because input dispatch is disabled.");
1354 }
1355 reason = "inbound event was dropped because input dispatch is disabled";
1356 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001357 case DropReason::APP_SWITCH:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001358 ALOGI("Dropped event because of pending overdue app switch.");
1359 reason = "inbound event was dropped because of pending overdue app switch";
1360 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001361 case DropReason::BLOCKED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001362 ALOGI("Dropped event because the current application is not responding and the user "
1363 "has started interacting with a different application.");
1364 reason = "inbound event was dropped because the current application is not responding "
1365 "and the user has started interacting with a different application";
1366 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001367 case DropReason::STALE:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001368 ALOGI("Dropped event because it is stale.");
1369 reason = "inbound event was dropped because it is stale";
1370 break;
Prabir Pradhan99987712020-11-10 18:43:05 -08001371 case DropReason::NO_POINTER_CAPTURE:
1372 ALOGI("Dropped event because there is no window with Pointer Capture.");
1373 reason = "inbound event was dropped because there is no window with Pointer Capture";
1374 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001375 case DropReason::NOT_DROPPED: {
1376 LOG_ALWAYS_FATAL("Should not be dropping a NOT_DROPPED event");
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001377 return;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001378 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001379 }
1380
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001381 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001382 case EventEntry::Type::KEY: {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001383 CancelationOptions options(CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS, reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001384 synthesizeCancelationEventsForAllConnectionsLocked(options);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001385 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001386 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001387 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001388 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
1389 if (motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001390 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS, reason);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001391 synthesizeCancelationEventsForAllConnectionsLocked(options);
1392 } else {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001393 CancelationOptions options(CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS,
1394 reason);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001395 synthesizeCancelationEventsForAllConnectionsLocked(options);
1396 }
1397 break;
1398 }
Chris Yef59a2f42020-10-16 12:55:26 -07001399 case EventEntry::Type::SENSOR: {
1400 break;
1401 }
arthurhungb89ccb02020-12-30 16:19:01 +08001402 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
1403 case EventEntry::Type::DRAG: {
Prabir Pradhan99987712020-11-10 18:43:05 -08001404 break;
1405 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001406 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001407 case EventEntry::Type::TOUCH_MODE_CHANGED:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001408 case EventEntry::Type::CONFIGURATION_CHANGED:
1409 case EventEntry::Type::DEVICE_RESET: {
Dominik Laskowski75788452021-02-09 18:51:25 -08001410 LOG_ALWAYS_FATAL("Should not drop %s events", ftl::enum_string(entry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001411 break;
1412 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001413 }
1414}
1415
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08001416static bool isAppSwitchKeyCode(int32_t keyCode) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001417 return keyCode == AKEYCODE_HOME || keyCode == AKEYCODE_ENDCALL ||
1418 keyCode == AKEYCODE_APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001419}
1420
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001421bool InputDispatcher::isAppSwitchKeyEvent(const KeyEntry& keyEntry) {
1422 return !(keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) && isAppSwitchKeyCode(keyEntry.keyCode) &&
1423 (keyEntry.policyFlags & POLICY_FLAG_TRUSTED) &&
1424 (keyEntry.policyFlags & POLICY_FLAG_PASS_TO_USER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001425}
1426
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07001427bool InputDispatcher::isAppSwitchPendingLocked() const {
Colin Cross5b799302022-10-18 21:52:41 -07001428 return mAppSwitchDueTime != LLONG_MAX;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001429}
1430
1431void InputDispatcher::resetPendingAppSwitchLocked(bool handled) {
Colin Cross5b799302022-10-18 21:52:41 -07001432 mAppSwitchDueTime = LLONG_MAX;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001433
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001434 if (DEBUG_APP_SWITCH) {
1435 if (handled) {
1436 ALOGD("App switch has arrived.");
1437 } else {
1438 ALOGD("App switch was abandoned.");
1439 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001440 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001441}
1442
Michael Wrightd02c5b62014-02-10 15:10:22 -08001443bool InputDispatcher::haveCommandsLocked() const {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001444 return !mCommandQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001445}
1446
Prabir Pradhancef936d2021-07-21 16:17:52 +00001447bool InputDispatcher::runCommandsLockedInterruptable() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001448 if (mCommandQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001449 return false;
1450 }
1451
1452 do {
Prabir Pradhancef936d2021-07-21 16:17:52 +00001453 auto command = std::move(mCommandQueue.front());
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001454 mCommandQueue.pop_front();
Prabir Pradhancef936d2021-07-21 16:17:52 +00001455 // Commands are run with the lock held, but may release and re-acquire the lock from within.
1456 command();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001457 } while (!mCommandQueue.empty());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001458 return true;
1459}
1460
Prabir Pradhancef936d2021-07-21 16:17:52 +00001461void InputDispatcher::postCommandLocked(Command&& command) {
1462 mCommandQueue.push_back(command);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001463}
1464
1465void InputDispatcher::drainInboundQueueLocked() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001466 while (!mInboundQueue.empty()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001467 std::shared_ptr<EventEntry> entry = mInboundQueue.front();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001468 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001469 releaseInboundEventLocked(entry);
1470 }
1471 traceInboundQueueLengthLocked();
1472}
1473
1474void InputDispatcher::releasePendingEventLocked() {
1475 if (mPendingEvent) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001476 releaseInboundEventLocked(mPendingEvent);
Yi Kong9b14ac62018-07-17 13:48:38 -07001477 mPendingEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001478 }
1479}
1480
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001481void InputDispatcher::releaseInboundEventLocked(std::shared_ptr<EventEntry> entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001482 InjectionState* injectionState = entry->injectionState;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001483 if (injectionState && injectionState->injectionResult == InputEventInjectionResult::PENDING) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001484 if (DEBUG_DISPATCH_CYCLE) {
1485 ALOGD("Injected inbound event was dropped.");
1486 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001487 setInjectionResult(*entry, InputEventInjectionResult::FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001488 }
1489 if (entry == mNextUnblockedEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001490 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001491 }
1492 addRecentEventLocked(entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001493}
1494
1495void InputDispatcher::resetKeyRepeatLocked() {
1496 if (mKeyRepeatState.lastKeyEntry) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001497 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001498 }
1499}
1500
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001501std::shared_ptr<KeyEntry> InputDispatcher::synthesizeKeyRepeatLocked(nsecs_t currentTime) {
1502 std::shared_ptr<KeyEntry> entry = mKeyRepeatState.lastKeyEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001503
Michael Wright2e732952014-09-24 13:26:59 -07001504 uint32_t policyFlags = entry->policyFlags &
1505 (POLICY_FLAG_RAW_MASK | POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_TRUSTED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001506
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001507 std::shared_ptr<KeyEntry> newEntry =
1508 std::make_unique<KeyEntry>(mIdGenerator.nextId(), currentTime, entry->deviceId,
1509 entry->source, entry->displayId, policyFlags, entry->action,
1510 entry->flags, entry->keyCode, entry->scanCode,
1511 entry->metaState, entry->repeatCount + 1, entry->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001512
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001513 newEntry->syntheticRepeat = true;
1514 mKeyRepeatState.lastKeyEntry = newEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001515 mKeyRepeatState.nextRepeatTime = currentTime + mConfig.keyRepeatDelay;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001516 return newEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001517}
1518
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001519bool InputDispatcher::dispatchConfigurationChangedLocked(nsecs_t currentTime,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001520 const ConfigurationChangedEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001521 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1522 ALOGD("dispatchConfigurationChanged - eventTime=%" PRId64, entry.eventTime);
1523 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001524
1525 // Reset key repeating in case a keyboard device was added or removed or something.
1526 resetKeyRepeatLocked();
1527
1528 // Enqueue a command to run outside the lock to tell the policy that the configuration changed.
Prabir Pradhancef936d2021-07-21 16:17:52 +00001529 auto command = [this, eventTime = entry.eventTime]() REQUIRES(mLock) {
1530 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00001531 mPolicy.notifyConfigurationChanged(eventTime);
Prabir Pradhancef936d2021-07-21 16:17:52 +00001532 };
1533 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001534 return true;
1535}
1536
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001537bool InputDispatcher::dispatchDeviceResetLocked(nsecs_t currentTime,
1538 const DeviceResetEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001539 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1540 ALOGD("dispatchDeviceReset - eventTime=%" PRId64 ", deviceId=%d", entry.eventTime,
1541 entry.deviceId);
1542 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001543
liushenxiang42232912021-05-21 20:24:09 +08001544 // Reset key repeating in case a keyboard device was disabled or enabled.
1545 if (mKeyRepeatState.lastKeyEntry && mKeyRepeatState.lastKeyEntry->deviceId == entry.deviceId) {
1546 resetKeyRepeatLocked();
1547 }
1548
Michael Wrightfb04fd52022-11-24 22:31:11 +00001549 CancelationOptions options(CancelationOptions::Mode::CANCEL_ALL_EVENTS, "device was reset");
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001550 options.deviceId = entry.deviceId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001551 synthesizeCancelationEventsForAllConnectionsLocked(options);
Siarhei Vishniakou0686f0c2023-05-02 11:56:15 -07001552
1553 // Remove all active pointers from this device
1554 for (auto& [_, touchState] : mTouchStatesByDisplay) {
1555 touchState.removeAllPointersForDevice(entry.deviceId);
1556 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001557 return true;
1558}
1559
Vishnu Nairad321cd2020-08-20 16:40:21 -07001560void InputDispatcher::enqueueFocusEventLocked(const sp<IBinder>& windowToken, bool hasFocus,
Vishnu Nairc519ff72021-01-21 08:23:08 -08001561 const std::string& reason) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001562 if (mPendingEvent != nullptr) {
1563 // Move the pending event to the front of the queue. This will give the chance
1564 // for the pending event to get dispatched to the newly focused window
1565 mInboundQueue.push_front(mPendingEvent);
1566 mPendingEvent = nullptr;
1567 }
1568
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001569 std::unique_ptr<FocusEntry> focusEntry =
1570 std::make_unique<FocusEntry>(mIdGenerator.nextId(), now(), windowToken, hasFocus,
1571 reason);
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001572
1573 // This event should go to the front of the queue, but behind all other focus events
1574 // Find the last focus event, and insert right after it
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001575 std::deque<std::shared_ptr<EventEntry>>::reverse_iterator it =
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001576 std::find_if(mInboundQueue.rbegin(), mInboundQueue.rend(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001577 [](const std::shared_ptr<EventEntry>& event) {
1578 return event->type == EventEntry::Type::FOCUS;
1579 });
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001580
1581 // Maintain the order of focus events. Insert the entry after all other focus events.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001582 mInboundQueue.insert(it.base(), std::move(focusEntry));
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001583}
1584
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001585void InputDispatcher::dispatchFocusLocked(nsecs_t currentTime, std::shared_ptr<FocusEntry> entry) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05001586 std::shared_ptr<InputChannel> channel = getInputChannelLocked(entry->connectionToken);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001587 if (channel == nullptr) {
1588 return; // Window has gone away
1589 }
1590 InputTarget target;
1591 target.inputChannel = channel;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08001592 target.flags = InputTarget::Flags::DISPATCH_AS_IS;
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001593 entry->dispatchInProgress = true;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00001594 std::string message = std::string("Focus ") + (entry->hasFocus ? "entering " : "leaving ") +
1595 channel->getName();
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07001596 std::string reason = std::string("reason=").append(entry->reason);
1597 android_log_event_list(LOGTAG_INPUT_FOCUS) << message << reason << LOG_ID_EVENTS;
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001598 dispatchEventLocked(currentTime, entry, {target});
1599}
1600
Prabir Pradhan99987712020-11-10 18:43:05 -08001601void InputDispatcher::dispatchPointerCaptureChangedLocked(
1602 nsecs_t currentTime, const std::shared_ptr<PointerCaptureChangedEntry>& entry,
1603 DropReason& dropReason) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001604 dropReason = DropReason::NOT_DROPPED;
1605
Prabir Pradhan99987712020-11-10 18:43:05 -08001606 const bool haveWindowWithPointerCapture = mWindowTokenWithPointerCapture != nullptr;
Prabir Pradhan99987712020-11-10 18:43:05 -08001607 sp<IBinder> token;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001608
1609 if (entry->pointerCaptureRequest.enable) {
1610 // Enable Pointer Capture.
1611 if (haveWindowWithPointerCapture &&
1612 (entry->pointerCaptureRequest == mCurrentPointerCaptureRequest)) {
Prabir Pradhan7092e262022-05-03 16:51:09 +00001613 // This can happen if pointer capture is disabled and re-enabled before we notify the
1614 // app of the state change, so there is no need to notify the app.
1615 ALOGI("Skipping dispatch of Pointer Capture being enabled: no state change.");
1616 return;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001617 }
1618 if (!mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08001619 // This can happen if a window requests capture and immediately releases capture.
1620 ALOGW("No window requested Pointer Capture.");
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001621 dropReason = DropReason::NO_POINTER_CAPTURE;
Prabir Pradhan99987712020-11-10 18:43:05 -08001622 return;
1623 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001624 if (entry->pointerCaptureRequest.seq != mCurrentPointerCaptureRequest.seq) {
1625 ALOGI("Skipping dispatch of Pointer Capture being enabled: sequence number mismatch.");
1626 return;
1627 }
1628
Vishnu Nairc519ff72021-01-21 08:23:08 -08001629 token = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Prabir Pradhan99987712020-11-10 18:43:05 -08001630 LOG_ALWAYS_FATAL_IF(!token, "Cannot find focused window for Pointer Capture.");
1631 mWindowTokenWithPointerCapture = token;
1632 } else {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001633 // Disable Pointer Capture.
1634 // We do not check if the sequence number matches for requests to disable Pointer Capture
1635 // for two reasons:
1636 // 1. Pointer Capture can be disabled by a focus change, which means we can get two entries
1637 // to disable capture with the same sequence number: one generated by
1638 // disablePointerCaptureForcedLocked() and another as an acknowledgement of Pointer
1639 // Capture being disabled in InputReader.
1640 // 2. We respect any request to disable Pointer Capture generated by InputReader, since the
1641 // actual Pointer Capture state that affects events being generated by input devices is
1642 // in InputReader.
1643 if (!haveWindowWithPointerCapture) {
1644 // Pointer capture was already forcefully disabled because of focus change.
1645 dropReason = DropReason::NOT_DROPPED;
1646 return;
1647 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001648 token = mWindowTokenWithPointerCapture;
1649 mWindowTokenWithPointerCapture = nullptr;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001650 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan7d030382020-12-21 07:58:35 -08001651 setPointerCaptureLocked(false);
1652 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001653 }
1654
1655 auto channel = getInputChannelLocked(token);
1656 if (channel == nullptr) {
1657 // Window has gone away, clean up Pointer Capture state.
1658 mWindowTokenWithPointerCapture = nullptr;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001659 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan7d030382020-12-21 07:58:35 -08001660 setPointerCaptureLocked(false);
1661 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001662 return;
1663 }
1664 InputTarget target;
1665 target.inputChannel = channel;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08001666 target.flags = InputTarget::Flags::DISPATCH_AS_IS;
Prabir Pradhan99987712020-11-10 18:43:05 -08001667 entry->dispatchInProgress = true;
1668 dispatchEventLocked(currentTime, entry, {target});
1669
1670 dropReason = DropReason::NOT_DROPPED;
1671}
1672
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001673void InputDispatcher::dispatchTouchModeChangeLocked(nsecs_t currentTime,
1674 const std::shared_ptr<TouchModeEntry>& entry) {
1675 const std::vector<sp<WindowInfoHandle>>& windowHandles =
Antonio Kantek15beb512022-06-13 22:35:41 +00001676 getWindowHandlesLocked(entry->displayId);
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001677 if (windowHandles.empty()) {
1678 return;
1679 }
1680 const std::vector<InputTarget> inputTargets =
1681 getInputTargetsFromWindowHandlesLocked(windowHandles);
1682 if (inputTargets.empty()) {
1683 return;
1684 }
1685 entry->dispatchInProgress = true;
1686 dispatchEventLocked(currentTime, entry, inputTargets);
1687}
1688
1689std::vector<InputTarget> InputDispatcher::getInputTargetsFromWindowHandlesLocked(
1690 const std::vector<sp<WindowInfoHandle>>& windowHandles) const {
1691 std::vector<InputTarget> inputTargets;
1692 for (const sp<WindowInfoHandle>& handle : windowHandles) {
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001693 const sp<IBinder>& token = handle->getToken();
1694 if (token == nullptr) {
1695 continue;
1696 }
1697 std::shared_ptr<InputChannel> channel = getInputChannelLocked(token);
1698 if (channel == nullptr) {
1699 continue; // Window has gone away
1700 }
1701 InputTarget target;
1702 target.inputChannel = channel;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08001703 target.flags = InputTarget::Flags::DISPATCH_AS_IS;
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001704 inputTargets.push_back(target);
1705 }
1706 return inputTargets;
1707}
1708
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001709bool InputDispatcher::dispatchKeyLocked(nsecs_t currentTime, std::shared_ptr<KeyEntry> entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001710 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001711 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001712 if (!entry->dispatchInProgress) {
1713 if (entry->repeatCount == 0 && entry->action == AKEY_EVENT_ACTION_DOWN &&
1714 (entry->policyFlags & POLICY_FLAG_TRUSTED) &&
1715 (!(entry->policyFlags & POLICY_FLAG_DISABLE_KEY_REPEAT))) {
1716 if (mKeyRepeatState.lastKeyEntry &&
Chris Ye2ad95392020-09-01 13:44:44 -07001717 mKeyRepeatState.lastKeyEntry->keyCode == entry->keyCode &&
Michael Wrightd02c5b62014-02-10 15:10:22 -08001718 // We have seen two identical key downs in a row which indicates that the device
1719 // driver is automatically generating key repeats itself. We take note of the
1720 // repeat here, but we disable our own next key repeat timer since it is clear that
1721 // we will not need to synthesize key repeats ourselves.
Chris Ye2ad95392020-09-01 13:44:44 -07001722 mKeyRepeatState.lastKeyEntry->deviceId == entry->deviceId) {
1723 // Make sure we don't get key down from a different device. If a different
1724 // device Id has same key pressed down, the new device Id will replace the
1725 // current one to hold the key repeat with repeat count reset.
1726 // In the future when got a KEY_UP on the device id, drop it and do not
1727 // stop the key repeat on current device.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001728 entry->repeatCount = mKeyRepeatState.lastKeyEntry->repeatCount + 1;
1729 resetKeyRepeatLocked();
Colin Cross5b799302022-10-18 21:52:41 -07001730 mKeyRepeatState.nextRepeatTime = LLONG_MAX; // don't generate repeats ourselves
Michael Wrightd02c5b62014-02-10 15:10:22 -08001731 } else {
1732 // Not a repeat. Save key down state in case we do see a repeat later.
1733 resetKeyRepeatLocked();
1734 mKeyRepeatState.nextRepeatTime = entry->eventTime + mConfig.keyRepeatTimeout;
1735 }
1736 mKeyRepeatState.lastKeyEntry = entry;
Chris Ye2ad95392020-09-01 13:44:44 -07001737 } else if (entry->action == AKEY_EVENT_ACTION_UP && mKeyRepeatState.lastKeyEntry &&
1738 mKeyRepeatState.lastKeyEntry->deviceId != entry->deviceId) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001739 // The key on device 'deviceId' is still down, do not stop key repeat
Prabir Pradhan65613802023-02-22 23:36:58 +00001740 if (debugInboundEventDetails()) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001741 ALOGD("deviceId=%d got KEY_UP as stale", entry->deviceId);
1742 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001743 } else if (!entry->syntheticRepeat) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001744 resetKeyRepeatLocked();
1745 }
1746
1747 if (entry->repeatCount == 1) {
1748 entry->flags |= AKEY_EVENT_FLAG_LONG_PRESS;
1749 } else {
1750 entry->flags &= ~AKEY_EVENT_FLAG_LONG_PRESS;
1751 }
1752
1753 entry->dispatchInProgress = true;
1754
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001755 logOutboundKeyDetails("dispatchKey - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001756 }
1757
1758 // Handle case where the policy asked us to try again later last time.
Michael Wright5caf55a2022-11-24 22:31:42 +00001759 if (entry->interceptKeyResult == KeyEntry::InterceptKeyResult::TRY_AGAIN_LATER) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001760 if (currentTime < entry->interceptKeyWakeupTime) {
1761 if (entry->interceptKeyWakeupTime < *nextWakeupTime) {
1762 *nextWakeupTime = entry->interceptKeyWakeupTime;
1763 }
1764 return false; // wait until next wakeup
1765 }
Michael Wright5caf55a2022-11-24 22:31:42 +00001766 entry->interceptKeyResult = KeyEntry::InterceptKeyResult::UNKNOWN;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001767 entry->interceptKeyWakeupTime = 0;
1768 }
1769
1770 // Give the policy a chance to intercept the key.
Michael Wright5caf55a2022-11-24 22:31:42 +00001771 if (entry->interceptKeyResult == KeyEntry::InterceptKeyResult::UNKNOWN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001772 if (entry->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07001773 sp<IBinder> focusedWindowToken =
Vishnu Nairc519ff72021-01-21 08:23:08 -08001774 mFocusResolver.getFocusedWindowToken(getTargetDisplayId(*entry));
Prabir Pradhancef936d2021-07-21 16:17:52 +00001775
1776 auto command = [this, focusedWindowToken, entry]() REQUIRES(mLock) {
1777 doInterceptKeyBeforeDispatchingCommand(focusedWindowToken, *entry);
1778 };
1779 postCommandLocked(std::move(command));
Josep del Riob3981622023-04-18 15:49:45 +00001780 // Poke user activity for keys not passed to user
1781 pokeUserActivityLocked(*entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001782 return false; // wait for the command to run
1783 } else {
Michael Wright5caf55a2022-11-24 22:31:42 +00001784 entry->interceptKeyResult = KeyEntry::InterceptKeyResult::CONTINUE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001785 }
Michael Wright5caf55a2022-11-24 22:31:42 +00001786 } else if (entry->interceptKeyResult == KeyEntry::InterceptKeyResult::SKIP) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001787 if (*dropReason == DropReason::NOT_DROPPED) {
1788 *dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001789 }
1790 }
1791
1792 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001793 if (*dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001794 setInjectionResult(*entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001795 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
1796 : InputEventInjectionResult::FAILED);
Garfield Tan6a5a14e2020-01-28 13:24:04 -08001797 mReporter->reportDroppedKey(entry->id);
Josep del Riob3981622023-04-18 15:49:45 +00001798 // Poke user activity for undispatched keys
1799 pokeUserActivityLocked(*entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001800 return true;
1801 }
1802
1803 // Identify targets.
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001804 InputEventInjectionResult injectionResult;
1805 sp<WindowInfoHandle> focusedWindow =
1806 findFocusedWindowTargetLocked(currentTime, *entry, nextWakeupTime,
1807 /*byref*/ injectionResult);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001808 if (injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001809 return false;
1810 }
1811
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001812 setInjectionResult(*entry, injectionResult);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001813 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001814 return true;
1815 }
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001816 LOG_ALWAYS_FATAL_IF(focusedWindow == nullptr);
1817
1818 std::vector<InputTarget> inputTargets;
1819 addWindowTargetLocked(focusedWindow,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08001820 InputTarget::Flags::FOREGROUND | InputTarget::Flags::DISPATCH_AS_IS,
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08001821 /*pointerIds=*/{}, getDownTime(*entry), inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001822
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001823 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001824 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001825
1826 // Dispatch the key.
1827 dispatchEventLocked(currentTime, entry, inputTargets);
1828 return true;
1829}
1830
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001831void InputDispatcher::logOutboundKeyDetails(const char* prefix, const KeyEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001832 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1833 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32 ", "
1834 "policyFlags=0x%x, action=0x%x, flags=0x%x, keyCode=0x%x, scanCode=0x%x, "
1835 "metaState=0x%x, repeatCount=%d, downTime=%" PRId64,
1836 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId,
1837 entry.policyFlags, entry.action, entry.flags, entry.keyCode, entry.scanCode,
1838 entry.metaState, entry.repeatCount, entry.downTime);
1839 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001840}
1841
Prabir Pradhancef936d2021-07-21 16:17:52 +00001842void InputDispatcher::dispatchSensorLocked(nsecs_t currentTime,
1843 const std::shared_ptr<SensorEntry>& entry,
Chris Yef59a2f42020-10-16 12:55:26 -07001844 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001845 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1846 ALOGD("notifySensorEvent eventTime=%" PRId64 ", hwTimestamp=%" PRId64 ", deviceId=%d, "
1847 "source=0x%x, sensorType=%s",
1848 entry->eventTime, entry->hwTimestamp, entry->deviceId, entry->source,
Dominik Laskowski75788452021-02-09 18:51:25 -08001849 ftl::enum_string(entry->sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001850 }
Prabir Pradhancef936d2021-07-21 16:17:52 +00001851 auto command = [this, entry]() REQUIRES(mLock) {
1852 scoped_unlock unlock(mLock);
1853
1854 if (entry->accuracyChanged) {
Prabir Pradhana41d2442023-04-20 21:30:40 +00001855 mPolicy.notifySensorAccuracy(entry->deviceId, entry->sensorType, entry->accuracy);
Prabir Pradhancef936d2021-07-21 16:17:52 +00001856 }
Prabir Pradhana41d2442023-04-20 21:30:40 +00001857 mPolicy.notifySensorEvent(entry->deviceId, entry->sensorType, entry->accuracy,
1858 entry->hwTimestamp, entry->values);
Prabir Pradhancef936d2021-07-21 16:17:52 +00001859 };
1860 postCommandLocked(std::move(command));
Chris Yef59a2f42020-10-16 12:55:26 -07001861}
1862
1863bool InputDispatcher::flushSensor(int deviceId, InputDeviceSensorType sensorType) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001864 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1865 ALOGD("flushSensor deviceId=%d, sensorType=%s", deviceId,
Dominik Laskowski75788452021-02-09 18:51:25 -08001866 ftl::enum_string(sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001867 }
Chris Yef59a2f42020-10-16 12:55:26 -07001868 { // acquire lock
1869 std::scoped_lock _l(mLock);
1870
1871 for (auto it = mInboundQueue.begin(); it != mInboundQueue.end(); it++) {
1872 std::shared_ptr<EventEntry> entry = *it;
1873 if (entry->type == EventEntry::Type::SENSOR) {
1874 it = mInboundQueue.erase(it);
1875 releaseInboundEventLocked(entry);
1876 }
1877 }
1878 }
1879 return true;
1880}
1881
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001882bool InputDispatcher::dispatchMotionLocked(nsecs_t currentTime, std::shared_ptr<MotionEntry> entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001883 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001884 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001885 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001886 if (!entry->dispatchInProgress) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001887 entry->dispatchInProgress = true;
1888
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001889 logOutboundMotionDetails("dispatchMotion - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001890 }
1891
1892 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001893 if (*dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001894 setInjectionResult(*entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001895 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
1896 : InputEventInjectionResult::FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001897 return true;
1898 }
1899
Prabir Pradhanaa561d12021-09-24 06:57:33 -07001900 const bool isPointerEvent = isFromSource(entry->source, AINPUT_SOURCE_CLASS_POINTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001901
1902 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001903 std::vector<InputTarget> inputTargets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001904
1905 bool conflictingPointerActions = false;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001906 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001907 if (isPointerEvent) {
1908 // Pointer event. (eg. touchscreen)
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00001909
1910 if (mDragState &&
1911 (entry->action & AMOTION_EVENT_ACTION_MASK) == AMOTION_EVENT_ACTION_POINTER_DOWN) {
1912 // If drag and drop ongoing and pointer down occur: pilfer drag window pointers
1913 pilferPointersLocked(mDragState->dragWindow->getToken());
1914 }
1915
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08001916 inputTargets =
Siarhei Vishniakou4fe57392022-10-25 13:44:30 -07001917 findTouchedWindowTargetsLocked(currentTime, *entry, &conflictingPointerActions,
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001918 /*byref*/ injectionResult);
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08001919 LOG_ALWAYS_FATAL_IF(injectionResult != InputEventInjectionResult::SUCCEEDED &&
1920 !inputTargets.empty());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001921 } else {
1922 // Non touch event. (eg. trackball)
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001923 sp<WindowInfoHandle> focusedWindow =
1924 findFocusedWindowTargetLocked(currentTime, *entry, nextWakeupTime, injectionResult);
1925 if (injectionResult == InputEventInjectionResult::SUCCEEDED) {
1926 LOG_ALWAYS_FATAL_IF(focusedWindow == nullptr);
1927 addWindowTargetLocked(focusedWindow,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08001928 InputTarget::Flags::FOREGROUND |
1929 InputTarget::Flags::DISPATCH_AS_IS,
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08001930 /*pointerIds=*/{}, getDownTime(*entry), inputTargets);
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001931 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001932 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001933 if (injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001934 return false;
1935 }
1936
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001937 setInjectionResult(*entry, injectionResult);
Prabir Pradhan5735a322022-04-11 17:23:34 +00001938 if (injectionResult == InputEventInjectionResult::TARGET_MISMATCH) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001939 return true;
1940 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001941 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001942 CancelationOptions::Mode mode(
1943 isPointerEvent ? CancelationOptions::Mode::CANCEL_POINTER_EVENTS
1944 : CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS);
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001945 CancelationOptions options(mode, "input event injection failed");
1946 synthesizeCancelationEventsForMonitorsLocked(options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001947 return true;
1948 }
1949
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001950 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001951 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001952
1953 // Dispatch the motion.
1954 if (conflictingPointerActions) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001955 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001956 "conflicting pointer actions");
Michael Wrightd02c5b62014-02-10 15:10:22 -08001957 synthesizeCancelationEventsForAllConnectionsLocked(options);
1958 }
1959 dispatchEventLocked(currentTime, entry, inputTargets);
1960 return true;
1961}
1962
chaviw98318de2021-05-19 16:45:23 -05001963void InputDispatcher::enqueueDragEventLocked(const sp<WindowInfoHandle>& windowHandle,
Arthur Hung54745652022-04-20 07:17:41 +00001964 bool isExiting, const int32_t rawX,
1965 const int32_t rawY) {
1966 const vec2 xy = windowHandle->getInfo()->transform.transform(vec2(rawX, rawY));
arthurhungb89ccb02020-12-30 16:19:01 +08001967 std::unique_ptr<DragEntry> dragEntry =
Arthur Hung54745652022-04-20 07:17:41 +00001968 std::make_unique<DragEntry>(mIdGenerator.nextId(), now(), windowHandle->getToken(),
1969 isExiting, xy.x, xy.y);
arthurhungb89ccb02020-12-30 16:19:01 +08001970
1971 enqueueInboundEventLocked(std::move(dragEntry));
1972}
1973
1974void InputDispatcher::dispatchDragLocked(nsecs_t currentTime, std::shared_ptr<DragEntry> entry) {
1975 std::shared_ptr<InputChannel> channel = getInputChannelLocked(entry->connectionToken);
1976 if (channel == nullptr) {
1977 return; // Window has gone away
1978 }
1979 InputTarget target;
1980 target.inputChannel = channel;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08001981 target.flags = InputTarget::Flags::DISPATCH_AS_IS;
arthurhungb89ccb02020-12-30 16:19:01 +08001982 entry->dispatchInProgress = true;
1983 dispatchEventLocked(currentTime, entry, {target});
1984}
1985
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001986void InputDispatcher::logOutboundMotionDetails(const char* prefix, const MotionEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001987 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -08001988 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=%s, displayId=%" PRId32
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001989 ", policyFlags=0x%x, "
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001990 "action=%s, actionButton=0x%x, flags=0x%x, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001991 "metaState=0x%x, buttonState=0x%x,"
1992 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%" PRId64,
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -08001993 prefix, entry.eventTime, entry.deviceId,
1994 inputEventSourceToString(entry.source).c_str(), entry.displayId, entry.policyFlags,
1995 MotionEvent::actionToString(entry.action).c_str(), entry.actionButton, entry.flags,
1996 entry.metaState, entry.buttonState, entry.edgeFlags, entry.xPrecision,
1997 entry.yPrecision, entry.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001998
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001999 for (uint32_t i = 0; i < entry.pointerCount; i++) {
Siarhei Vishniakou09a8fe42022-07-21 17:27:03 -07002000 ALOGD(" Pointer %d: id=%d, toolType=%s, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002001 "x=%f, y=%f, pressure=%f, size=%f, "
2002 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
2003 "orientation=%f",
Siarhei Vishniakou09a8fe42022-07-21 17:27:03 -07002004 i, entry.pointerProperties[i].id,
2005 ftl::enum_string(entry.pointerProperties[i].toolType).c_str(),
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002006 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
2007 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
2008 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
2009 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
2010 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
2011 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
2012 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
2013 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
2014 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
2015 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002016 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002017}
2018
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002019void InputDispatcher::dispatchEventLocked(nsecs_t currentTime,
2020 std::shared_ptr<EventEntry> eventEntry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002021 const std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002022 ATRACE_CALL();
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002023 if (DEBUG_DISPATCH_CYCLE) {
2024 ALOGD("dispatchEventToCurrentInputTargets");
2025 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002026
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00002027 processInteractionsLocked(*eventEntry, inputTargets);
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00002028
Michael Wrightd02c5b62014-02-10 15:10:22 -08002029 ALOG_ASSERT(eventEntry->dispatchInProgress); // should already have been set to true
2030
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002031 pokeUserActivityLocked(*eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002032
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002033 for (const InputTarget& inputTarget : inputTargets) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07002034 std::shared_ptr<Connection> connection =
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07002035 getConnectionLocked(inputTarget.inputChannel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07002036 if (connection != nullptr) {
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002037 prepareDispatchCycleLocked(currentTime, connection, eventEntry, inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002038 } else {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002039 if (DEBUG_FOCUS) {
2040 ALOGD("Dropping event delivery to target with channel '%s' because it "
2041 "is no longer registered with the input dispatcher.",
2042 inputTarget.inputChannel->getName().c_str());
2043 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002044 }
2045 }
2046}
2047
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07002048void InputDispatcher::cancelEventsForAnrLocked(const std::shared_ptr<Connection>& connection) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002049 // We will not be breaking any connections here, even if the policy wants us to abort dispatch.
2050 // If the policy decides to close the app, we will get a channel removal event via
2051 // unregisterInputChannel, and will clean up the connection that way. We are already not
2052 // sending new pointers to the connection when it blocked, but focused events will continue to
2053 // pile up.
2054 ALOGW("Canceling events for %s because it is unresponsive",
2055 connection->inputChannel->getName().c_str());
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08002056 if (connection->status == Connection::Status::NORMAL) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00002057 CancelationOptions options(CancelationOptions::Mode::CANCEL_ALL_EVENTS,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002058 "application not responding");
2059 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002060 }
2061}
2062
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002063void InputDispatcher::resetNoFocusedWindowTimeoutLocked() {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002064 if (DEBUG_FOCUS) {
2065 ALOGD("Resetting ANR timeouts.");
2066 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002067
2068 // Reset input target wait timeout.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002069 mNoFocusedWindowTimeoutTime = std::nullopt;
Chris Yea209fde2020-07-22 13:54:51 -07002070 mAwaitedFocusedApplication.reset();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002071}
2072
Tiger Huang721e26f2018-07-24 22:26:19 +08002073/**
2074 * Get the display id that the given event should go to. If this event specifies a valid display id,
2075 * then it should be dispatched to that display. Otherwise, the event goes to the focused display.
2076 * Focused display is the display that the user most recently interacted with.
2077 */
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002078int32_t InputDispatcher::getTargetDisplayId(const EventEntry& entry) {
Tiger Huang721e26f2018-07-24 22:26:19 +08002079 int32_t displayId;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002080 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002081 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002082 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
2083 displayId = keyEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002084 break;
2085 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002086 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002087 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
2088 displayId = motionEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002089 break;
2090 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00002091 case EventEntry::Type::TOUCH_MODE_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08002092 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002093 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002094 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07002095 case EventEntry::Type::DEVICE_RESET:
arthurhungb89ccb02020-12-30 16:19:01 +08002096 case EventEntry::Type::SENSOR:
2097 case EventEntry::Type::DRAG: {
Dominik Laskowski75788452021-02-09 18:51:25 -08002098 ALOGE("%s events do not have a target display", ftl::enum_string(entry.type).c_str());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002099 return ADISPLAY_ID_NONE;
2100 }
Tiger Huang721e26f2018-07-24 22:26:19 +08002101 }
2102 return displayId == ADISPLAY_ID_NONE ? mFocusedDisplayId : displayId;
2103}
2104
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002105bool InputDispatcher::shouldWaitToSendKeyLocked(nsecs_t currentTime,
2106 const char* focusedWindowName) {
2107 if (mAnrTracker.empty()) {
2108 // already processed all events that we waited for
2109 mKeyIsWaitingForEventsTimeout = std::nullopt;
2110 return false;
2111 }
2112
2113 if (!mKeyIsWaitingForEventsTimeout.has_value()) {
2114 // Start the timer
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00002115 // Wait to send key because there are unprocessed events that may cause focus to change
Siarhei Vishniakou70622952020-07-30 11:17:23 -05002116 mKeyIsWaitingForEventsTimeout = currentTime +
2117 std::chrono::duration_cast<std::chrono::nanoseconds>(KEY_WAITING_FOR_EVENTS_TIMEOUT)
2118 .count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002119 return true;
2120 }
2121
2122 // We still have pending events, and already started the timer
2123 if (currentTime < *mKeyIsWaitingForEventsTimeout) {
2124 return true; // Still waiting
2125 }
2126
2127 // Waited too long, and some connection still hasn't processed all motions
2128 // Just send the key to the focused window
2129 ALOGW("Dispatching key to %s even though there are other unprocessed events",
2130 focusedWindowName);
2131 mKeyIsWaitingForEventsTimeout = std::nullopt;
2132 return false;
2133}
2134
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002135sp<WindowInfoHandle> InputDispatcher::findFocusedWindowTargetLocked(
2136 nsecs_t currentTime, const EventEntry& entry, nsecs_t* nextWakeupTime,
2137 InputEventInjectionResult& outInjectionResult) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002138 std::string reason;
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002139 outInjectionResult = InputEventInjectionResult::FAILED; // Default result
Michael Wrightd02c5b62014-02-10 15:10:22 -08002140
Tiger Huang721e26f2018-07-24 22:26:19 +08002141 int32_t displayId = getTargetDisplayId(entry);
chaviw98318de2021-05-19 16:45:23 -05002142 sp<WindowInfoHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Chris Yea209fde2020-07-22 13:54:51 -07002143 std::shared_ptr<InputApplicationHandle> focusedApplicationHandle =
Tiger Huang721e26f2018-07-24 22:26:19 +08002144 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
2145
Michael Wrightd02c5b62014-02-10 15:10:22 -08002146 // If there is no currently focused window and no focused application
2147 // then drop the event.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002148 if (focusedWindowHandle == nullptr && focusedApplicationHandle == nullptr) {
2149 ALOGI("Dropping %s event because there is no focused window or focused application in "
2150 "display %" PRId32 ".",
Dominik Laskowski75788452021-02-09 18:51:25 -08002151 ftl::enum_string(entry.type).c_str(), displayId);
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002152 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002153 }
2154
Vishnu Nair062a8672021-09-03 16:07:44 -07002155 // Drop key events if requested by input feature
2156 if (focusedWindowHandle != nullptr && shouldDropInput(entry, focusedWindowHandle)) {
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002157 return nullptr;
Vishnu Nair062a8672021-09-03 16:07:44 -07002158 }
2159
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002160 // Compatibility behavior: raise ANR if there is a focused application, but no focused window.
2161 // Only start counting when we have a focused event to dispatch. The ANR is canceled if we
2162 // start interacting with another application via touch (app switch). This code can be removed
2163 // if the "no focused window ANR" is moved to the policy. Input doesn't know whether
2164 // an app is expected to have a focused window.
2165 if (focusedWindowHandle == nullptr && focusedApplicationHandle != nullptr) {
2166 if (!mNoFocusedWindowTimeoutTime.has_value()) {
2167 // We just discovered that there's no focused window. Start the ANR timer
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05002168 std::chrono::nanoseconds timeout = focusedApplicationHandle->getDispatchingTimeout(
2169 DEFAULT_INPUT_DISPATCHING_TIMEOUT);
2170 mNoFocusedWindowTimeoutTime = currentTime + timeout.count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002171 mAwaitedFocusedApplication = focusedApplicationHandle;
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05002172 mAwaitedApplicationDisplayId = displayId;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002173 ALOGW("Waiting because no window has focus but %s may eventually add a "
2174 "window when it finishes starting up. Will wait for %" PRId64 "ms",
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05002175 mAwaitedFocusedApplication->getName().c_str(), millis(timeout));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002176 *nextWakeupTime = *mNoFocusedWindowTimeoutTime;
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002177 outInjectionResult = InputEventInjectionResult::PENDING;
2178 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002179 } else if (currentTime > *mNoFocusedWindowTimeoutTime) {
2180 // Already raised ANR. Drop the event
2181 ALOGE("Dropping %s event because there is no focused window",
Dominik Laskowski75788452021-02-09 18:51:25 -08002182 ftl::enum_string(entry.type).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002183 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002184 } else {
2185 // Still waiting for the focused window
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002186 outInjectionResult = InputEventInjectionResult::PENDING;
2187 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002188 }
2189 }
2190
2191 // we have a valid, non-null focused window
2192 resetNoFocusedWindowTimeoutLocked();
2193
Prabir Pradhan5735a322022-04-11 17:23:34 +00002194 // Verify targeted injection.
2195 if (const auto err = verifyTargetedInjection(focusedWindowHandle, entry); err) {
2196 ALOGW("Dropping injected event: %s", (*err).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002197 outInjectionResult = InputEventInjectionResult::TARGET_MISMATCH;
2198 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002199 }
2200
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002201 if (focusedWindowHandle->getInfo()->inputConfig.test(
2202 WindowInfo::InputConfig::PAUSE_DISPATCHING)) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002203 ALOGI("Waiting because %s is paused", focusedWindowHandle->getName().c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002204 outInjectionResult = InputEventInjectionResult::PENDING;
2205 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002206 }
2207
2208 // If the event is a key event, then we must wait for all previous events to
2209 // complete before delivering it because previous events may have the
2210 // side-effect of transferring focus to a different window and we want to
2211 // ensure that the following keys are sent to the new window.
2212 //
2213 // Suppose the user touches a button in a window then immediately presses "A".
2214 // If the button causes a pop-up window to appear then we want to ensure that
2215 // the "A" key is delivered to the new pop-up window. This is because users
2216 // often anticipate pending UI changes when typing on a keyboard.
2217 // To obtain this behavior, we must serialize key events with respect to all
2218 // prior input events.
2219 if (entry.type == EventEntry::Type::KEY) {
2220 if (shouldWaitToSendKeyLocked(currentTime, focusedWindowHandle->getName().c_str())) {
2221 *nextWakeupTime = *mKeyIsWaitingForEventsTimeout;
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002222 outInjectionResult = InputEventInjectionResult::PENDING;
2223 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002224 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002225 }
2226
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002227 outInjectionResult = InputEventInjectionResult::SUCCEEDED;
2228 return focusedWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002229}
2230
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002231/**
2232 * Given a list of monitors, remove the ones we cannot find a connection for, and the ones
2233 * that are currently unresponsive.
2234 */
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002235std::vector<Monitor> InputDispatcher::selectResponsiveMonitorsLocked(
2236 const std::vector<Monitor>& monitors) const {
2237 std::vector<Monitor> responsiveMonitors;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002238 std::copy_if(monitors.begin(), monitors.end(), std::back_inserter(responsiveMonitors),
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002239 [this](const Monitor& monitor) REQUIRES(mLock) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07002240 std::shared_ptr<Connection> connection =
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002241 getConnectionLocked(monitor.inputChannel->getConnectionToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002242 if (connection == nullptr) {
2243 ALOGE("Could not find connection for monitor %s",
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002244 monitor.inputChannel->getName().c_str());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002245 return false;
2246 }
2247 if (!connection->responsive) {
2248 ALOGW("Unresponsive monitor %s will not get the new gesture",
2249 connection->inputChannel->getName().c_str());
2250 return false;
2251 }
2252 return true;
2253 });
2254 return responsiveMonitors;
2255}
2256
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002257std::vector<InputTarget> InputDispatcher::findTouchedWindowTargetsLocked(
Siarhei Vishniakou4fe57392022-10-25 13:44:30 -07002258 nsecs_t currentTime, const MotionEntry& entry, bool* outConflictingPointerActions,
2259 InputEventInjectionResult& outInjectionResult) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002260 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002261
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002262 std::vector<InputTarget> targets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002263 // For security reasons, we defer updating the touch state until we are sure that
2264 // event injection will be allowed.
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002265 const int32_t displayId = entry.displayId;
2266 const int32_t action = entry.action;
Siarhei Vishniakoubf880522023-05-01 11:03:22 -07002267 const int32_t maskedAction = MotionEvent::getActionMasked(action);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002268
2269 // Update the touch state as needed based on the properties of the touch event.
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002270 outInjectionResult = InputEventInjectionResult::PENDING;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002271
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002272 // Copy current touch state into tempTouchState.
2273 // This state will be used to update mTouchStatesByDisplay at the end of this function.
2274 // If no state for the specified display exists, then our initial state will be empty.
Yi Kong9b14ac62018-07-17 13:48:38 -07002275 const TouchState* oldState = nullptr;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002276 TouchState tempTouchState;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002277 if (const auto it = mTouchStatesByDisplay.find(displayId); it != mTouchStatesByDisplay.end()) {
2278 oldState = &(it->second);
Prabir Pradhane680f9b2022-02-04 04:24:00 -08002279 tempTouchState = *oldState;
Jeff Brownf086ddb2014-02-11 14:28:48 -08002280 }
2281
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07002282 bool isSplit = shouldSplitTouch(tempTouchState, entry);
Siarhei Vishniakou45504fe2023-05-05 16:05:10 -07002283 bool switchedDevice = false;
2284 if (oldState != nullptr) {
2285 std::set<int32_t> oldActiveDevices = oldState->getActiveDeviceIds();
2286 const bool anotherDeviceIsActive =
2287 oldActiveDevices.count(entry.deviceId) == 0 && !oldActiveDevices.empty();
2288 switchedDevice |= anotherDeviceIsActive;
Siarhei Vishniakou45504fe2023-05-05 16:05:10 -07002289 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002290
2291 const bool isHoverAction = (maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE ||
2292 maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2293 maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT);
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002294 // A DOWN could be generated from POINTER_DOWN if the initial pointers did not land into any
2295 // touchable windows.
2296 const bool wasDown = oldState != nullptr && oldState->isDown();
2297 const bool isDown = (maskedAction == AMOTION_EVENT_ACTION_DOWN) ||
2298 (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN && !wasDown);
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07002299 const bool newGesture = isDown || maskedAction == AMOTION_EVENT_ACTION_SCROLL ||
2300 maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2301 maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE;
Prabir Pradhanaa561d12021-09-24 06:57:33 -07002302 const bool isFromMouse = isFromSource(entry.source, AINPUT_SOURCE_MOUSE);
Siarhei Vishniakou5cee1e32022-11-29 12:35:39 -08002303
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002304 // If pointers are already down, let's finish the current gesture and ignore the new events
2305 // from another device. However, if the new event is a down event, let's cancel the current
2306 // touch and let the new one take over.
2307 if (switchedDevice && wasDown && !isDown) {
Siarhei Vishniakou45504fe2023-05-05 16:05:10 -07002308 LOG(INFO) << "Dropping event because a pointer for another device "
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002309 << " is already down in display " << displayId << ": " << entry.getDescription();
2310 // TODO(b/211379801): test multiple simultaneous input streams.
2311 outInjectionResult = InputEventInjectionResult::FAILED;
2312 return {}; // wrong device
2313 }
2314
Michael Wrightd02c5b62014-02-10 15:10:22 -08002315 if (newGesture) {
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002316 // If a new gesture is starting, clear the touch state completely.
2317 tempTouchState.reset();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002318 isSplit = false;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04002319 } else if (switchedDevice && maskedAction == AMOTION_EVENT_ACTION_MOVE) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07002320 ALOGI("Dropping move event because a pointer for a different device is already active "
2321 "in display %" PRId32,
2322 displayId);
Siarhei Vishniakou16e4fa02023-02-16 17:48:56 -08002323 // TODO(b/211379801): test multiple simultaneous input streams.
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002324 outInjectionResult = InputEventInjectionResult::FAILED;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002325 return {}; // wrong device
Michael Wrightd02c5b62014-02-10 15:10:22 -08002326 }
2327
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002328 if (isHoverAction) {
2329 // For hover actions, we will treat 'tempTouchState' as a new state, so let's erase
2330 // all of the existing hovering pointers and recompute.
2331 tempTouchState.clearHoveringPointers();
2332 }
2333
Michael Wrightd02c5b62014-02-10 15:10:22 -08002334 if (newGesture || (isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN)) {
2335 /* Case 1: New splittable pointer going down, or need target for hover or scroll. */
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07002336 const auto [x, y] = resolveTouchedPosition(entry);
Siarhei Vishniakou5b9766d2023-07-18 14:06:29 -07002337 const int32_t pointerIndex = MotionEvent::getActionIndex(action);
Siarhei Vishniakou70f3d8c2023-09-19 15:36:52 -07002338 const int32_t pointerId = entry.pointerProperties[pointerIndex].id;
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002339 // Outside targets should be added upon first dispatched DOWN event. That means, this should
2340 // be a pointer that would generate ACTION_DOWN, *and* touch should not already be down.
Prabir Pradhand65552b2021-10-07 11:23:50 -07002341 const bool isStylus = isPointerFromStylus(entry, pointerIndex);
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07002342 sp<WindowInfoHandle> newTouchedWindowHandle =
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002343 findTouchedWindowAtLocked(displayId, x, y, isStylus);
Michael Wright3dd60e22019-03-27 22:06:44 +00002344
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002345 if (isDown) {
Siarhei Vishniakou70f3d8c2023-09-19 15:36:52 -07002346 targets += findOutsideTargetsLocked(displayId, newTouchedWindowHandle, pointerId);
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002347 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002348 // Handle the case where we did not find a window.
Yi Kong9b14ac62018-07-17 13:48:38 -07002349 if (newTouchedWindowHandle == nullptr) {
Prabir Pradhan82e081e2022-12-06 09:50:09 +00002350 ALOGD("No new touched window at (%.1f, %.1f) in display %" PRId32, x, y, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002351 // Try to assign the pointer to the first foreground window we find, if there is one.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002352 newTouchedWindowHandle = tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002353 }
2354
Prabir Pradhan5735a322022-04-11 17:23:34 +00002355 // Verify targeted injection.
2356 if (const auto err = verifyTargetedInjection(newTouchedWindowHandle, entry); err) {
2357 ALOGW("Dropping injected touch event: %s", (*err).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002358 outInjectionResult = os::InputEventInjectionResult::TARGET_MISMATCH;
Prabir Pradhan5735a322022-04-11 17:23:34 +00002359 newTouchedWindowHandle = nullptr;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002360 return {};
Prabir Pradhan5735a322022-04-11 17:23:34 +00002361 }
2362
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002363 // Figure out whether splitting will be allowed for this window.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002364 if (newTouchedWindowHandle != nullptr) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002365 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
2366 // New window supports splitting, but we should never split mouse events.
2367 isSplit = !isFromMouse;
2368 } else if (isSplit) {
2369 // New window does not support splitting but we have already split events.
2370 // Ignore the new window.
Siarhei Vishniakou25537f82023-07-18 14:35:47 -07002371 LOG(INFO) << "Skipping " << newTouchedWindowHandle->getName()
2372 << " because it doesn't support split touch";
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002373 newTouchedWindowHandle = nullptr;
2374 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002375 } else {
2376 // No window is touched, so set split to true. This will allow the next pointer down to
Prabir Pradhan713bb3e2021-12-20 02:07:40 -08002377 // be delivered to a new window which supports split touch. Pointers from a mouse device
2378 // should never be split.
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07002379 isSplit = !isFromMouse;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002380 }
2381
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002382 std::vector<sp<WindowInfoHandle>> newTouchedWindows =
Prabir Pradhand65552b2021-10-07 11:23:50 -07002383 findTouchedSpyWindowsAtLocked(displayId, x, y, isStylus);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002384 if (newTouchedWindowHandle != nullptr) {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002385 // Process the foreground window first so that it is the first to receive the event.
2386 newTouchedWindows.insert(newTouchedWindows.begin(), newTouchedWindowHandle);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002387 }
2388
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002389 if (newTouchedWindows.empty()) {
Prabir Pradhan82e081e2022-12-06 09:50:09 +00002390 ALOGI("Dropping event because there is no touchable window at (%.1f, %.1f) on display "
2391 "%d.",
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002392 x, y, displayId);
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002393 outInjectionResult = InputEventInjectionResult::FAILED;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002394 return {};
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002395 }
2396
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002397 for (const sp<WindowInfoHandle>& windowHandle : newTouchedWindows) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07002398 if (!canWindowReceiveMotionLocked(windowHandle, entry)) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002399 continue;
2400 }
2401
Siarhei Vishniakoub681c202023-05-01 11:22:33 -07002402 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2403 maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE) {
Siarhei Vishniakoub681c202023-05-01 11:22:33 -07002404 // The "windowHandle" is the target of this hovering pointer.
2405 tempTouchState.addHoveringPointerToWindow(windowHandle, entry.deviceId, pointerId);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002406 }
2407
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002408 // Set target flags.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002409 ftl::Flags<InputTarget::Flags> targetFlags = InputTarget::Flags::DISPATCH_AS_IS;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002410
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002411 if (canReceiveForegroundTouches(*windowHandle->getInfo())) {
2412 // There should only be one touched window that can be "foreground" for the pointer.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002413 targetFlags |= InputTarget::Flags::FOREGROUND;
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002414 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002415
2416 if (isSplit) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002417 targetFlags |= InputTarget::Flags::SPLIT;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002418 }
2419 if (isWindowObscuredAtPointLocked(windowHandle, x, y)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002420 targetFlags |= InputTarget::Flags::WINDOW_IS_OBSCURED;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002421 } else if (isWindowObscuredLocked(windowHandle)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002422 targetFlags |= InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002423 }
Michael Wright3dd60e22019-03-27 22:06:44 +00002424
2425 // Update the temporary touch state.
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08002426 std::bitset<MAX_POINTER_ID + 1> pointerIds;
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002427 if (!isHoverAction) {
Siarhei Vishniakou70f3d8c2023-09-19 15:36:52 -07002428 pointerIds.set(pointerId);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002429 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002430
Siarhei Vishniakoue0431e42023-01-28 17:01:39 -08002431 const bool isDownOrPointerDown = maskedAction == AMOTION_EVENT_ACTION_DOWN ||
2432 maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN;
2433
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002434 // TODO(b/211379801): Currently, even if pointerIds are empty (hover case), we would
2435 // still add a window to the touch state. We should avoid doing that, but some of the
2436 // later checks ("at least one foreground window") rely on this in order to dispatch
2437 // the event properly, so that needs to be updated, possibly by looking at InputTargets.
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002438 tempTouchState.addOrUpdateWindow(windowHandle, targetFlags, entry.deviceId, pointerIds,
Siarhei Vishniakoue0431e42023-01-28 17:01:39 -08002439 isDownOrPointerDown
2440 ? std::make_optional(entry.eventTime)
2441 : std::nullopt);
Arthur Hungc539dbb2022-12-08 07:45:36 +00002442
2443 // If this is the pointer going down and the touched window has a wallpaper
2444 // then also add the touched wallpaper windows so they are locked in for the duration
2445 // of the touch gesture.
2446 // We do not collect wallpapers during HOVER_MOVE or SCROLL because the wallpaper
2447 // engine only supports touch events. We would need to add a mechanism similar
2448 // to View.onGenericMotionEvent to enable wallpapers to handle these events.
Siarhei Vishniakoue0431e42023-01-28 17:01:39 -08002449 if (isDownOrPointerDown) {
Arthur Hungc539dbb2022-12-08 07:45:36 +00002450 if (targetFlags.test(InputTarget::Flags::FOREGROUND) &&
2451 windowHandle->getInfo()->inputConfig.test(
2452 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER)) {
2453 sp<WindowInfoHandle> wallpaper = findWallpaperWindowBelow(windowHandle);
2454 if (wallpaper != nullptr) {
2455 ftl::Flags<InputTarget::Flags> wallpaperFlags =
2456 InputTarget::Flags::WINDOW_IS_OBSCURED |
2457 InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED |
2458 InputTarget::Flags::DISPATCH_AS_IS;
2459 if (isSplit) {
2460 wallpaperFlags |= InputTarget::Flags::SPLIT;
2461 }
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002462 tempTouchState.addOrUpdateWindow(wallpaper, wallpaperFlags, entry.deviceId,
2463 pointerIds, entry.eventTime);
Arthur Hungc539dbb2022-12-08 07:45:36 +00002464 }
2465 }
2466 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002467 }
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00002468
Siarhei Vishniakou060f82b2023-01-27 06:39:14 -08002469 // If a window is already pilfering some pointers, give it this new pointer as well and
2470 // make it pilfering. This will prevent other non-spy windows from getting this pointer,
2471 // which is a specific behaviour that we want.
Siarhei Vishniakou060f82b2023-01-27 06:39:14 -08002472 for (TouchedWindow& touchedWindow : tempTouchState.windows) {
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002473 if (touchedWindow.hasTouchingPointer(entry.deviceId, pointerId) &&
2474 touchedWindow.hasPilferingPointers(entry.deviceId)) {
Siarhei Vishniakou060f82b2023-01-27 06:39:14 -08002475 // This window is already pilfering some pointers, and this new pointer is also
2476 // going to it. Therefore, take over this pointer and don't give it to anyone
2477 // else.
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002478 touchedWindow.addPilferingPointer(entry.deviceId, pointerId);
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00002479 }
2480 }
Siarhei Vishniakou060f82b2023-01-27 06:39:14 -08002481
2482 // Restrict all pilfered pointers to the pilfering windows.
2483 tempTouchState.cancelPointersForNonPilferingWindows();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002484 } else {
2485 /* Case 2: Pointer move, up, cancel or non-splittable pointer down. */
2486
2487 // If the pointer is not currently down, then ignore the event.
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07002488 if (!tempTouchState.isDown() && maskedAction != AMOTION_EVENT_ACTION_HOVER_EXIT) {
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002489 LOG(INFO) << "Dropping event because the pointer is not down or we previously "
2490 "dropped the pointer down event in display "
2491 << displayId << ": " << entry.getDescription();
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002492 outInjectionResult = InputEventInjectionResult::FAILED;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002493 return {};
Michael Wrightd02c5b62014-02-10 15:10:22 -08002494 }
2495
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07002496 // If the pointer is not currently hovering, then ignore the event.
2497 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT) {
2498 const int32_t pointerId = entry.pointerProperties[0].id;
2499 if (oldState == nullptr ||
2500 oldState->getWindowsWithHoveringPointer(entry.deviceId, pointerId).empty()) {
2501 LOG(INFO) << "Dropping event because the hovering pointer is not in any windows in "
2502 "display "
2503 << displayId << ": " << entry.getDescription();
2504 outInjectionResult = InputEventInjectionResult::FAILED;
2505 return {};
2506 }
2507 tempTouchState.removeHoveringPointer(entry.deviceId, pointerId);
2508 }
2509
arthurhung6d4bed92021-03-17 11:59:33 +08002510 addDragEventLocked(entry);
arthurhungb89ccb02020-12-30 16:19:01 +08002511
Michael Wrightd02c5b62014-02-10 15:10:22 -08002512 // Check whether touches should slip outside of the current foreground window.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002513 if (maskedAction == AMOTION_EVENT_ACTION_MOVE && entry.pointerCount == 1 &&
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002514 tempTouchState.isSlippery()) {
Siarhei Vishniakou9306c382022-09-30 15:30:31 -07002515 const auto [x, y] = resolveTouchedPosition(entry);
Harry Cutts33476232023-01-30 19:57:29 +00002516 const bool isStylus = isPointerFromStylus(entry, /*pointerIndex=*/0);
chaviw98318de2021-05-19 16:45:23 -05002517 sp<WindowInfoHandle> oldTouchedWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002518 tempTouchState.getFirstForegroundWindowHandle();
Siarhei Vishniakou0f6558d2023-04-21 12:05:13 -07002519 LOG_ALWAYS_FATAL_IF(oldTouchedWindowHandle == nullptr);
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07002520 sp<WindowInfoHandle> newTouchedWindowHandle =
2521 findTouchedWindowAtLocked(displayId, x, y, isStylus);
Vishnu Nair062a8672021-09-03 16:07:44 -07002522
Prabir Pradhan5735a322022-04-11 17:23:34 +00002523 // Verify targeted injection.
2524 if (const auto err = verifyTargetedInjection(newTouchedWindowHandle, entry); err) {
2525 ALOGW("Dropping injected event: %s", (*err).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002526 outInjectionResult = os::InputEventInjectionResult::TARGET_MISMATCH;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002527 return {};
Prabir Pradhan5735a322022-04-11 17:23:34 +00002528 }
2529
Vishnu Nair062a8672021-09-03 16:07:44 -07002530 // Drop touch events if requested by input feature
2531 if (newTouchedWindowHandle != nullptr &&
2532 shouldDropInput(entry, newTouchedWindowHandle)) {
2533 newTouchedWindowHandle = nullptr;
2534 }
2535
Siarhei Vishniakouafa08cc2023-05-08 22:35:50 -07002536 if (newTouchedWindowHandle != nullptr &&
2537 !haveSameToken(oldTouchedWindowHandle, newTouchedWindowHandle)) {
Siarhei Vishniakou0f6558d2023-04-21 12:05:13 -07002538 ALOGD("Touch is slipping out of window %s into window %s in display %" PRId32,
2539 oldTouchedWindowHandle->getName().c_str(),
2540 newTouchedWindowHandle->getName().c_str(), displayId);
2541
Michael Wrightd02c5b62014-02-10 15:10:22 -08002542 // Make a slippery exit from the old window.
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08002543 std::bitset<MAX_POINTER_ID + 1> pointerIds;
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002544 const int32_t pointerId = entry.pointerProperties[0].id;
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08002545 pointerIds.set(pointerId);
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002546
2547 const TouchedWindow& touchedWindow =
2548 tempTouchState.getTouchedWindow(oldTouchedWindowHandle);
2549 addWindowTargetLocked(oldTouchedWindowHandle,
2550 InputTarget::Flags::DISPATCH_AS_SLIPPERY_EXIT, pointerIds,
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002551 touchedWindow.getDownTimeInTarget(entry.deviceId), targets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002552
2553 // Make a slippery entrance into the new window.
2554 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
Prabir Pradhan713bb3e2021-12-20 02:07:40 -08002555 isSplit = !isFromMouse;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002556 }
2557
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002558 ftl::Flags<InputTarget::Flags> targetFlags =
2559 InputTarget::Flags::DISPATCH_AS_SLIPPERY_ENTER;
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002560 if (canReceiveForegroundTouches(*newTouchedWindowHandle->getInfo())) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002561 targetFlags |= InputTarget::Flags::FOREGROUND;
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002562 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002563 if (isSplit) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002564 targetFlags |= InputTarget::Flags::SPLIT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002565 }
2566 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002567 targetFlags |= InputTarget::Flags::WINDOW_IS_OBSCURED;
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002568 } else if (isWindowObscuredLocked(newTouchedWindowHandle)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002569 targetFlags |= InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002570 }
2571
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002572 tempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags,
2573 entry.deviceId, pointerIds, entry.eventTime);
Arthur Hungc539dbb2022-12-08 07:45:36 +00002574
2575 // Check if the wallpaper window should deliver the corresponding event.
2576 slipWallpaperTouch(targetFlags, oldTouchedWindowHandle, newTouchedWindowHandle,
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002577 tempTouchState, entry.deviceId, pointerId, targets);
2578 tempTouchState.removeTouchingPointerFromWindow(entry.deviceId, pointerId,
2579 oldTouchedWindowHandle);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002580 }
2581 }
Arthur Hung96483742022-11-15 03:30:48 +00002582
2583 // Update the pointerIds for non-splittable when it received pointer down.
2584 if (!isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN) {
2585 // If no split, we suppose all touched windows should receive pointer down.
Siarhei Vishniakou5b9766d2023-07-18 14:06:29 -07002586 const int32_t pointerIndex = MotionEvent::getActionIndex(action);
Arthur Hung96483742022-11-15 03:30:48 +00002587 for (size_t i = 0; i < tempTouchState.windows.size(); i++) {
2588 TouchedWindow& touchedWindow = tempTouchState.windows[i];
2589 // Ignore drag window for it should just track one pointer.
2590 if (mDragState && mDragState->dragWindow == touchedWindow.windowHandle) {
2591 continue;
2592 }
Siarhei Vishniakou5b9766d2023-07-18 14:06:29 -07002593 std::bitset<MAX_POINTER_ID + 1> touchingPointers;
2594 touchingPointers.set(entry.pointerProperties[pointerIndex].id);
2595 touchedWindow.addTouchingPointers(entry.deviceId, touchingPointers);
Arthur Hung96483742022-11-15 03:30:48 +00002596 }
2597 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002598 }
2599
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002600 // Update dispatching for hover enter and exit.
Sam Dubeyf886dec2023-01-27 13:28:19 +00002601 {
2602 std::vector<TouchedWindow> hoveringWindows =
2603 getHoveringWindowsLocked(oldState, tempTouchState, entry);
2604 for (const TouchedWindow& touchedWindow : hoveringWindows) {
Siarhei Vishniakoud5876ba2023-05-15 17:58:34 -07002605 std::optional<InputTarget> target =
2606 createInputTargetLocked(touchedWindow.windowHandle, touchedWindow.targetFlags,
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002607 touchedWindow.getDownTimeInTarget(entry.deviceId));
Siarhei Vishniakoud5876ba2023-05-15 17:58:34 -07002608 if (!target) {
2609 continue;
2610 }
2611 // Hardcode to single hovering pointer for now.
2612 std::bitset<MAX_POINTER_ID + 1> pointerIds;
2613 pointerIds.set(entry.pointerProperties[0].id);
2614 target->addPointers(pointerIds, touchedWindow.windowHandle->getInfo()->transform);
2615 targets.push_back(*target);
Sam Dubeyf886dec2023-01-27 13:28:19 +00002616 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002617 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002618
Prabir Pradhan5735a322022-04-11 17:23:34 +00002619 // Ensure that all touched windows are valid for injection.
2620 if (entry.injectionState != nullptr) {
2621 std::string errs;
2622 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Prabir Pradhan5735a322022-04-11 17:23:34 +00002623 const auto err = verifyTargetedInjection(touchedWindow.windowHandle, entry);
2624 if (err) errs += "\n - " + *err;
2625 }
2626 if (!errs.empty()) {
2627 ALOGW("Dropping targeted injection: At least one touched window is not owned by uid "
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00002628 "%s:%s",
2629 entry.injectionState->targetUid->toString().c_str(), errs.c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002630 outInjectionResult = InputEventInjectionResult::TARGET_MISMATCH;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002631 return {};
Prabir Pradhan5735a322022-04-11 17:23:34 +00002632 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002633 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002634
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002635 // Check whether windows listening for outside touches are owned by the same UID. If the owner
2636 // has a different UID, then we will not reveal coordinate information to this window.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002637 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
chaviw98318de2021-05-19 16:45:23 -05002638 sp<WindowInfoHandle> foregroundWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002639 tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002640 if (foregroundWindowHandle) {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00002641 const auto foregroundWindowUid = foregroundWindowHandle->getInfo()->ownerUid;
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002642 for (InputTarget& target : targets) {
2643 if (target.flags.test(InputTarget::Flags::DISPATCH_AS_OUTSIDE)) {
2644 sp<WindowInfoHandle> targetWindow =
2645 getWindowHandleLocked(target.inputChannel->getConnectionToken());
2646 if (targetWindow->getInfo()->ownerUid != foregroundWindowUid) {
2647 target.flags |= InputTarget::Flags::ZERO_COORDS;
Michael Wright3dd60e22019-03-27 22:06:44 +00002648 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002649 }
2650 }
2651 }
2652 }
2653
Harry Cuttsb166c002023-05-09 13:06:05 +00002654 // If this is a touchpad navigation gesture, it needs to only be sent to trusted targets, as we
2655 // only want the system UI to handle these gestures.
2656 const bool isTouchpadNavGesture = isFromSource(entry.source, AINPUT_SOURCE_MOUSE) &&
2657 entry.classification == MotionClassification::MULTI_FINGER_SWIPE;
2658 if (isTouchpadNavGesture) {
2659 filterUntrustedTargets(/* byref */ tempTouchState, /* byref */ targets);
2660 }
2661
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07002662 // Output targets from the touch state.
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002663 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002664 if (!touchedWindow.hasTouchingPointers(entry.deviceId) &&
2665 !touchedWindow.hasHoveringPointers(entry.deviceId)) {
Siarhei Vishniakoue0431e42023-01-28 17:01:39 -08002666 // Windows with hovering pointers are getting persisted inside TouchState.
2667 // Do not send this event to those windows.
2668 continue;
2669 }
Harry Cuttsb166c002023-05-09 13:06:05 +00002670
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002671 addWindowTargetLocked(touchedWindow.windowHandle, touchedWindow.targetFlags,
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002672 touchedWindow.getTouchingPointers(entry.deviceId),
2673 touchedWindow.getDownTimeInTarget(entry.deviceId), targets);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002674 }
Sam Dubey39d37cf2022-12-07 18:05:35 +00002675
Siarhei Vishniakou580fb3a2023-05-05 15:02:20 -07002676 // During targeted injection, only allow owned targets to receive events
2677 std::erase_if(targets, [&](const InputTarget& target) {
2678 LOG_ALWAYS_FATAL_IF(target.windowHandle == nullptr);
2679 const auto err = verifyTargetedInjection(target.windowHandle, entry);
2680 if (err) {
2681 LOG(WARNING) << "Dropping injected event from " << target.windowHandle->getName()
2682 << ": " << (*err);
2683 return true;
2684 }
2685 return false;
2686 });
2687
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07002688 if (targets.empty()) {
2689 LOG(INFO) << "Dropping event because no targets were found: " << entry.getDescription();
2690 outInjectionResult = InputEventInjectionResult::FAILED;
2691 return {};
2692 }
2693
2694 // If we only have windows getting ACTION_OUTSIDE, then drop the event, because there is no
2695 // window that is actually receiving the entire gesture.
2696 if (std::all_of(targets.begin(), targets.end(), [](const InputTarget& target) {
2697 return target.flags.test(InputTarget::Flags::DISPATCH_AS_OUTSIDE);
2698 })) {
2699 LOG(INFO) << "Dropping event because all windows would just receive ACTION_OUTSIDE: "
2700 << entry.getDescription();
2701 outInjectionResult = InputEventInjectionResult::FAILED;
2702 return {};
2703 }
2704
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002705 outInjectionResult = InputEventInjectionResult::SUCCEEDED;
Sam Dubeyf886dec2023-01-27 13:28:19 +00002706 // Drop the outside or hover touch windows since we will not care about them
2707 // in the next iteration.
2708 tempTouchState.filterNonAsIsTouchWindows();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002709
Michael Wrightd02c5b62014-02-10 15:10:22 -08002710 // Update final pieces of touch state if the injector had permission.
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002711 if (switchedDevice) {
2712 if (DEBUG_FOCUS) {
2713 ALOGD("Conflicting pointer actions: Switched to a different device.");
2714 }
2715 *outConflictingPointerActions = true;
2716 }
2717
2718 if (isHoverAction) {
2719 // Started hovering, therefore no longer down.
Siarhei Vishniakou3ad385b2022-11-04 10:09:53 -07002720 if (oldState && oldState->isDown()) {
Siarhei Vishniakou6e1e9872022-11-08 17:51:35 -08002721 ALOGD_IF(DEBUG_FOCUS,
2722 "Conflicting pointer actions: Hover received while pointer was down.");
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002723 *outConflictingPointerActions = true;
2724 }
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002725 } else if (maskedAction == AMOTION_EVENT_ACTION_UP) {
2726 // Pointer went up.
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002727 tempTouchState.removeTouchingPointer(entry.deviceId, entry.pointerProperties[0].id);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002728 } else if (maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002729 // All pointers up or canceled.
2730 tempTouchState.reset();
2731 } else if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
2732 // First pointer went down.
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002733 if (oldState && (oldState->isDown() || oldState->hasHoveringPointers())) {
2734 ALOGD("Conflicting pointer actions: Down received while already down or hovering.");
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002735 *outConflictingPointerActions = true;
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002736 }
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002737 } else if (maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
2738 // One pointer went up.
Siarhei Vishniakou5b9766d2023-07-18 14:06:29 -07002739 const int32_t pointerIndex = MotionEvent::getActionIndex(action);
2740 const uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
2741 tempTouchState.removeTouchingPointer(entry.deviceId, pointerId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002742 }
2743
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002744 // Save changes unless the action was scroll in which case the temporary touch
2745 // state was only valid for this one action.
2746 if (maskedAction != AMOTION_EVENT_ACTION_SCROLL) {
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07002747 if (displayId >= 0) {
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002748 tempTouchState.clearWindowsWithoutPointers();
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002749 mTouchStatesByDisplay[displayId] = tempTouchState;
2750 } else {
2751 mTouchStatesByDisplay.erase(displayId);
2752 }
2753 }
2754
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -08002755 if (tempTouchState.windows.empty()) {
2756 mTouchStatesByDisplay.erase(displayId);
2757 }
2758
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002759 return targets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002760}
2761
arthurhung6d4bed92021-03-17 11:59:33 +08002762void InputDispatcher::finishDragAndDrop(int32_t displayId, float x, float y) {
Prabir Pradhand65552b2021-10-07 11:23:50 -07002763 // Prevent stylus interceptor windows from affecting drag and drop behavior for now, until we
2764 // have an explicit reason to support it.
2765 constexpr bool isStylus = false;
2766
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07002767 sp<WindowInfoHandle> dropWindow =
Harry Cutts33476232023-01-30 19:57:29 +00002768 findTouchedWindowAtLocked(displayId, x, y, isStylus, /*ignoreDragWindow=*/true);
arthurhung6d4bed92021-03-17 11:59:33 +08002769 if (dropWindow) {
2770 vec2 local = dropWindow->getInfo()->transform.transform(x, y);
Prabir Pradhancef936d2021-07-21 16:17:52 +00002771 sendDropWindowCommandLocked(dropWindow->getToken(), local.x, local.y);
Arthur Hung6d0571e2021-04-09 20:18:16 +08002772 } else {
Arthur Hung54745652022-04-20 07:17:41 +00002773 ALOGW("No window found when drop.");
Prabir Pradhancef936d2021-07-21 16:17:52 +00002774 sendDropWindowCommandLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08002775 }
2776 mDragState.reset();
2777}
2778
2779void InputDispatcher::addDragEventLocked(const MotionEntry& entry) {
Arthur Hung3915c1f2022-05-31 07:17:17 +00002780 if (!mDragState || mDragState->dragWindow->getInfo()->displayId != entry.displayId) {
arthurhungb89ccb02020-12-30 16:19:01 +08002781 return;
2782 }
2783
arthurhung6d4bed92021-03-17 11:59:33 +08002784 if (!mDragState->isStartDrag) {
2785 mDragState->isStartDrag = true;
2786 mDragState->isStylusButtonDownAtStart =
2787 (entry.buttonState & AMOTION_EVENT_BUTTON_STYLUS_PRIMARY) != 0;
2788 }
2789
Arthur Hung54745652022-04-20 07:17:41 +00002790 // Find the pointer index by id.
2791 int32_t pointerIndex = 0;
2792 for (; static_cast<uint32_t>(pointerIndex) < entry.pointerCount; pointerIndex++) {
2793 const PointerProperties& pointerProperties = entry.pointerProperties[pointerIndex];
2794 if (pointerProperties.id == mDragState->pointerId) {
2795 break;
arthurhung6d4bed92021-03-17 11:59:33 +08002796 }
Arthur Hung54745652022-04-20 07:17:41 +00002797 }
arthurhung6d4bed92021-03-17 11:59:33 +08002798
Arthur Hung54745652022-04-20 07:17:41 +00002799 if (uint32_t(pointerIndex) == entry.pointerCount) {
2800 LOG_ALWAYS_FATAL("Should find a valid pointer index by id %d", mDragState->pointerId);
Arthur Hung54745652022-04-20 07:17:41 +00002801 }
2802
2803 const int32_t maskedAction = entry.action & AMOTION_EVENT_ACTION_MASK;
2804 const int32_t x = entry.pointerCoords[pointerIndex].getX();
2805 const int32_t y = entry.pointerCoords[pointerIndex].getY();
2806
2807 switch (maskedAction) {
2808 case AMOTION_EVENT_ACTION_MOVE: {
2809 // Handle the special case : stylus button no longer pressed.
2810 bool isStylusButtonDown =
2811 (entry.buttonState & AMOTION_EVENT_BUTTON_STYLUS_PRIMARY) != 0;
2812 if (mDragState->isStylusButtonDownAtStart && !isStylusButtonDown) {
2813 finishDragAndDrop(entry.displayId, x, y);
2814 return;
2815 }
2816
2817 // Prevent stylus interceptor windows from affecting drag and drop behavior for now,
2818 // until we have an explicit reason to support it.
2819 constexpr bool isStylus = false;
2820
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07002821 sp<WindowInfoHandle> hoverWindowHandle =
2822 findTouchedWindowAtLocked(entry.displayId, x, y, isStylus,
2823 /*ignoreDragWindow=*/true);
Arthur Hung54745652022-04-20 07:17:41 +00002824 // enqueue drag exit if needed.
2825 if (hoverWindowHandle != mDragState->dragHoverWindowHandle &&
2826 !haveSameToken(hoverWindowHandle, mDragState->dragHoverWindowHandle)) {
2827 if (mDragState->dragHoverWindowHandle != nullptr) {
Harry Cutts33476232023-01-30 19:57:29 +00002828 enqueueDragEventLocked(mDragState->dragHoverWindowHandle, /*isExiting=*/true, x,
Arthur Hung54745652022-04-20 07:17:41 +00002829 y);
2830 }
2831 mDragState->dragHoverWindowHandle = hoverWindowHandle;
2832 }
2833 // enqueue drag location if needed.
2834 if (hoverWindowHandle != nullptr) {
Harry Cutts33476232023-01-30 19:57:29 +00002835 enqueueDragEventLocked(hoverWindowHandle, /*isExiting=*/false, x, y);
Arthur Hung54745652022-04-20 07:17:41 +00002836 }
2837 break;
2838 }
2839
2840 case AMOTION_EVENT_ACTION_POINTER_UP:
Siarhei Vishniakou5b9766d2023-07-18 14:06:29 -07002841 if (MotionEvent::getActionIndex(entry.action) != pointerIndex) {
Arthur Hung54745652022-04-20 07:17:41 +00002842 break;
2843 }
2844 // The drag pointer is up.
2845 [[fallthrough]];
2846 case AMOTION_EVENT_ACTION_UP:
2847 finishDragAndDrop(entry.displayId, x, y);
2848 break;
2849 case AMOTION_EVENT_ACTION_CANCEL: {
2850 ALOGD("Receiving cancel when drag and drop.");
2851 sendDropWindowCommandLocked(nullptr, 0, 0);
2852 mDragState.reset();
2853 break;
2854 }
arthurhungb89ccb02020-12-30 16:19:01 +08002855 }
2856}
2857
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002858std::optional<InputTarget> InputDispatcher::createInputTargetLocked(
2859 const sp<android::gui::WindowInfoHandle>& windowHandle,
2860 ftl::Flags<InputTarget::Flags> targetFlags,
2861 std::optional<nsecs_t> firstDownTimeInTarget) const {
2862 std::shared_ptr<InputChannel> inputChannel = getInputChannelLocked(windowHandle->getToken());
2863 if (inputChannel == nullptr) {
2864 ALOGW("Not creating InputTarget for %s, no input channel", windowHandle->getName().c_str());
2865 return {};
2866 }
2867 InputTarget inputTarget;
2868 inputTarget.inputChannel = inputChannel;
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00002869 inputTarget.windowHandle = windowHandle;
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002870 inputTarget.flags = targetFlags;
2871 inputTarget.globalScaleFactor = windowHandle->getInfo()->globalScaleFactor;
2872 inputTarget.firstDownTimeInTarget = firstDownTimeInTarget;
2873 const auto& displayInfoIt = mDisplayInfos.find(windowHandle->getInfo()->displayId);
2874 if (displayInfoIt != mDisplayInfos.end()) {
2875 inputTarget.displayTransform = displayInfoIt->second.transform;
2876 } else {
Siarhei Vishniakou580fb3a2023-05-05 15:02:20 -07002877 // DisplayInfo not found for this window on display windowHandle->getInfo()->displayId.
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002878 // TODO(b/198444055): Make this an error message after 'setInputWindows' API is removed.
2879 }
2880 return inputTarget;
2881}
2882
chaviw98318de2021-05-19 16:45:23 -05002883void InputDispatcher::addWindowTargetLocked(const sp<WindowInfoHandle>& windowHandle,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002884 ftl::Flags<InputTarget::Flags> targetFlags,
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08002885 std::bitset<MAX_POINTER_ID + 1> pointerIds,
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002886 std::optional<nsecs_t> firstDownTimeInTarget,
Siarhei Vishniakouf75cddb2022-10-25 10:42:16 -07002887 std::vector<InputTarget>& inputTargets) const {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002888 std::vector<InputTarget>::iterator it =
2889 std::find_if(inputTargets.begin(), inputTargets.end(),
2890 [&windowHandle](const InputTarget& inputTarget) {
2891 return inputTarget.inputChannel->getConnectionToken() ==
2892 windowHandle->getToken();
2893 });
Chavi Weingarten97b8eec2020-01-09 18:09:08 +00002894
chaviw98318de2021-05-19 16:45:23 -05002895 const WindowInfo* windowInfo = windowHandle->getInfo();
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002896
2897 if (it == inputTargets.end()) {
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002898 std::optional<InputTarget> target =
2899 createInputTargetLocked(windowHandle, targetFlags, firstDownTimeInTarget);
2900 if (!target) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002901 return;
2902 }
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002903 inputTargets.push_back(*target);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002904 it = inputTargets.end() - 1;
2905 }
2906
2907 ALOG_ASSERT(it->flags == targetFlags);
2908 ALOG_ASSERT(it->globalScaleFactor == windowInfo->globalScaleFactor);
2909
chaviw1ff3d1e2020-07-01 15:53:47 -07002910 it->addPointers(pointerIds, windowInfo->transform);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002911}
2912
Michael Wright3dd60e22019-03-27 22:06:44 +00002913void InputDispatcher::addGlobalMonitoringTargetsLocked(std::vector<InputTarget>& inputTargets,
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002914 int32_t displayId) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002915 auto monitorsIt = mGlobalMonitorsByDisplay.find(displayId);
2916 if (monitorsIt == mGlobalMonitorsByDisplay.end()) return;
Michael Wright3dd60e22019-03-27 22:06:44 +00002917
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002918 for (const Monitor& monitor : selectResponsiveMonitorsLocked(monitorsIt->second)) {
2919 InputTarget target;
2920 target.inputChannel = monitor.inputChannel;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002921 target.flags = InputTarget::Flags::DISPATCH_AS_IS;
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002922 // target.firstDownTimeInTarget is not set for global monitors. It is only required in split
2923 // touch and global monitoring works as intended even without setting firstDownTimeInTarget
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002924 if (const auto& it = mDisplayInfos.find(displayId); it != mDisplayInfos.end()) {
2925 target.displayTransform = it->second.transform;
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002926 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002927 target.setDefaultPointerTransform(target.displayTransform);
2928 inputTargets.push_back(target);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002929 }
2930}
2931
Robert Carrc9bf1d32020-04-13 17:21:08 -07002932/**
2933 * Indicate whether one window handle should be considered as obscuring
2934 * another window handle. We only check a few preconditions. Actually
2935 * checking the bounds is left to the caller.
2936 */
chaviw98318de2021-05-19 16:45:23 -05002937static bool canBeObscuredBy(const sp<WindowInfoHandle>& windowHandle,
2938 const sp<WindowInfoHandle>& otherHandle) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002939 // Compare by token so cloned layers aren't counted
2940 if (haveSameToken(windowHandle, otherHandle)) {
2941 return false;
2942 }
2943 auto info = windowHandle->getInfo();
2944 auto otherInfo = otherHandle->getInfo();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002945 if (otherInfo->inputConfig.test(WindowInfo::InputConfig::NOT_VISIBLE)) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002946 return false;
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002947 } else if (otherInfo->alpha == 0 &&
2948 otherInfo->inputConfig.test(WindowInfo::InputConfig::NOT_TOUCHABLE)) {
Bernardo Rufino653d2e02020-10-20 17:32:40 +00002949 // Those act as if they were invisible, so we don't need to flag them.
2950 // We do want to potentially flag touchable windows even if they have 0
2951 // opacity, since they can consume touches and alter the effects of the
2952 // user interaction (eg. apps that rely on
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002953 // Flags::WINDOW_IS_PARTIALLY_OBSCURED should still be told about those
Bernardo Rufino653d2e02020-10-20 17:32:40 +00002954 // windows), hence we also check for FLAG_NOT_TOUCHABLE.
2955 return false;
Bernardo Rufino8007daf2020-09-22 09:40:01 +00002956 } else if (info->ownerUid == otherInfo->ownerUid) {
2957 // If ownerUid is the same we don't generate occlusion events as there
2958 // is no security boundary within an uid.
Robert Carrc9bf1d32020-04-13 17:21:08 -07002959 return false;
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002960 } else if (otherInfo->inputConfig.test(gui::WindowInfo::InputConfig::TRUSTED_OVERLAY)) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002961 return false;
2962 } else if (otherInfo->displayId != info->displayId) {
2963 return false;
2964 }
2965 return true;
2966}
2967
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002968/**
2969 * Returns touch occlusion information in the form of TouchOcclusionInfo. To check if the touch is
2970 * untrusted, one should check:
2971 *
2972 * 1. If result.hasBlockingOcclusion is true.
2973 * If it's, it means the touch should be blocked due to a window with occlusion mode of
2974 * BLOCK_UNTRUSTED.
2975 *
2976 * 2. If result.obscuringOpacity > mMaximumObscuringOpacityForTouch.
2977 * If it is (and 1 is false), then the touch should be blocked because a stack of windows
2978 * (possibly only one) with occlusion mode of USE_OPACITY from one UID resulted in a composed
2979 * obscuring opacity above the threshold. Note that if there was no window of occlusion mode
2980 * USE_OPACITY, result.obscuringOpacity would've been 0 and since
2981 * mMaximumObscuringOpacityForTouch >= 0, the condition above would never be true.
2982 *
2983 * If neither of those is true, then it means the touch can be allowed.
2984 */
2985InputDispatcher::TouchOcclusionInfo InputDispatcher::computeTouchOcclusionInfoLocked(
chaviw98318de2021-05-19 16:45:23 -05002986 const sp<WindowInfoHandle>& windowHandle, int32_t x, int32_t y) const {
2987 const WindowInfo* windowInfo = windowHandle->getInfo();
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002988 int32_t displayId = windowInfo->displayId;
chaviw98318de2021-05-19 16:45:23 -05002989 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002990 TouchOcclusionInfo info;
2991 info.hasBlockingOcclusion = false;
2992 info.obscuringOpacity = 0;
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00002993 info.obscuringUid = gui::Uid::INVALID;
2994 std::map<gui::Uid, float> opacityByUid;
chaviw98318de2021-05-19 16:45:23 -05002995 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002996 if (windowHandle == otherHandle) {
2997 break; // All future windows are below us. Exit early.
2998 }
chaviw98318de2021-05-19 16:45:23 -05002999 const WindowInfo* otherInfo = otherHandle->getInfo();
Bernardo Rufino1ff9d592021-01-18 16:58:57 +00003000 if (canBeObscuredBy(windowHandle, otherHandle) && otherInfo->frameContainsPoint(x, y) &&
3001 !haveSameApplicationToken(windowInfo, otherInfo)) {
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00003002 if (DEBUG_TOUCH_OCCLUSION) {
3003 info.debugInfo.push_back(
Harry Cutts101ee9b2023-07-06 18:04:14 +00003004 dumpWindowForTouchOcclusion(otherInfo, /*isTouchedWindow=*/false));
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00003005 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003006 // canBeObscuredBy() has returned true above, which means this window is untrusted, so
3007 // we perform the checks below to see if the touch can be propagated or not based on the
3008 // window's touch occlusion mode
3009 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::BLOCK_UNTRUSTED) {
3010 info.hasBlockingOcclusion = true;
3011 info.obscuringUid = otherInfo->ownerUid;
3012 info.obscuringPackage = otherInfo->packageName;
3013 break;
3014 }
3015 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::USE_OPACITY) {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003016 const auto uid = otherInfo->ownerUid;
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003017 float opacity =
3018 (opacityByUid.find(uid) == opacityByUid.end()) ? 0 : opacityByUid[uid];
3019 // Given windows A and B:
3020 // opacity(A, B) = 1 - [1 - opacity(A)] * [1 - opacity(B)]
3021 opacity = 1 - (1 - opacity) * (1 - otherInfo->alpha);
3022 opacityByUid[uid] = opacity;
3023 if (opacity > info.obscuringOpacity) {
3024 info.obscuringOpacity = opacity;
3025 info.obscuringUid = uid;
3026 info.obscuringPackage = otherInfo->packageName;
3027 }
3028 }
3029 }
3030 }
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00003031 if (DEBUG_TOUCH_OCCLUSION) {
Harry Cutts101ee9b2023-07-06 18:04:14 +00003032 info.debugInfo.push_back(dumpWindowForTouchOcclusion(windowInfo, /*isTouchedWindow=*/true));
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00003033 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003034 return info;
3035}
3036
chaviw98318de2021-05-19 16:45:23 -05003037std::string InputDispatcher::dumpWindowForTouchOcclusion(const WindowInfo* info,
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00003038 bool isTouchedWindow) const {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003039 return StringPrintf(INDENT2 "* %spackage=%s/%s, id=%" PRId32 ", mode=%s, alpha=%.2f, "
Prabir Pradhan51e7db02022-02-07 06:02:57 -08003040 "frame=[%" PRId32 ",%" PRId32 "][%" PRId32 ",%" PRId32
3041 "], touchableRegion=%s, window={%s}, inputConfig={%s}, "
3042 "hasToken=%s, applicationInfo.name=%s, applicationInfo.token=%s\n",
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08003043 isTouchedWindow ? "[TOUCHED] " : "", info->packageName.c_str(),
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003044 info->ownerUid.toString().c_str(), info->id,
Chavi Weingarten7f019192023-08-08 20:39:01 +00003045 toString(info->touchOcclusionMode).c_str(), info->alpha, info->frame.left,
3046 info->frame.top, info->frame.right, info->frame.bottom,
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003047 dumpRegion(info->touchableRegion).c_str(), info->name.c_str(),
3048 info->inputConfig.string().c_str(), toString(info->token != nullptr),
3049 info->applicationInfo.name.c_str(),
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07003050 binderToString(info->applicationInfo.token).c_str());
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00003051}
3052
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003053bool InputDispatcher::isTouchTrustedLocked(const TouchOcclusionInfo& occlusionInfo) const {
3054 if (occlusionInfo.hasBlockingOcclusion) {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003055 ALOGW("Untrusted touch due to occlusion by %s/%s", occlusionInfo.obscuringPackage.c_str(),
3056 occlusionInfo.obscuringUid.toString().c_str());
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003057 return false;
3058 }
3059 if (occlusionInfo.obscuringOpacity > mMaximumObscuringOpacityForTouch) {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003060 ALOGW("Untrusted touch due to occlusion by %s/%s (obscuring opacity = "
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003061 "%.2f, maximum allowed = %.2f)",
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003062 occlusionInfo.obscuringPackage.c_str(), occlusionInfo.obscuringUid.toString().c_str(),
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003063 occlusionInfo.obscuringOpacity, mMaximumObscuringOpacityForTouch);
3064 return false;
3065 }
3066 return true;
3067}
3068
chaviw98318de2021-05-19 16:45:23 -05003069bool InputDispatcher::isWindowObscuredAtPointLocked(const sp<WindowInfoHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003070 int32_t x, int32_t y) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003071 int32_t displayId = windowHandle->getInfo()->displayId;
chaviw98318de2021-05-19 16:45:23 -05003072 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
3073 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07003074 if (windowHandle == otherHandle) {
3075 break; // All future windows are below us. Exit early.
Michael Wrightd02c5b62014-02-10 15:10:22 -08003076 }
chaviw98318de2021-05-19 16:45:23 -05003077 const WindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07003078 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08003079 otherInfo->frameContainsPoint(x, y)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003080 return true;
3081 }
3082 }
3083 return false;
3084}
3085
chaviw98318de2021-05-19 16:45:23 -05003086bool InputDispatcher::isWindowObscuredLocked(const sp<WindowInfoHandle>& windowHandle) const {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07003087 int32_t displayId = windowHandle->getInfo()->displayId;
chaviw98318de2021-05-19 16:45:23 -05003088 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
3089 const WindowInfo* windowInfo = windowHandle->getInfo();
3090 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07003091 if (windowHandle == otherHandle) {
3092 break; // All future windows are below us. Exit early.
Michael Wrightcdcd8f22016-03-22 16:52:13 -07003093 }
chaviw98318de2021-05-19 16:45:23 -05003094 const WindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07003095 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08003096 otherInfo->overlaps(windowInfo)) {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07003097 return true;
3098 }
3099 }
3100 return false;
3101}
3102
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08003103std::string InputDispatcher::getApplicationWindowLabel(
chaviw98318de2021-05-19 16:45:23 -05003104 const InputApplicationHandle* applicationHandle, const sp<WindowInfoHandle>& windowHandle) {
Yi Kong9b14ac62018-07-17 13:48:38 -07003105 if (applicationHandle != nullptr) {
3106 if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07003107 return applicationHandle->getName() + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003108 } else {
3109 return applicationHandle->getName();
3110 }
Yi Kong9b14ac62018-07-17 13:48:38 -07003111 } else if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07003112 return windowHandle->getInfo()->applicationInfo.name + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003113 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003114 return "<unknown application or window>";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003115 }
3116}
3117
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003118void InputDispatcher::pokeUserActivityLocked(const EventEntry& eventEntry) {
Antonio Kantekf16f2832021-09-28 04:39:20 +00003119 if (!isUserActivityEvent(eventEntry)) {
3120 // Not poking user activity if the event type does not represent a user activity
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003121 return;
3122 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003123 int32_t displayId = getTargetDisplayId(eventEntry);
chaviw98318de2021-05-19 16:45:23 -05003124 sp<WindowInfoHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Josep del Riob3981622023-04-18 15:49:45 +00003125 const WindowInfo* windowDisablingUserActivityInfo = nullptr;
Tiger Huang721e26f2018-07-24 22:26:19 +08003126 if (focusedWindowHandle != nullptr) {
chaviw98318de2021-05-19 16:45:23 -05003127 const WindowInfo* info = focusedWindowHandle->getInfo();
Prabir Pradhan51e7db02022-02-07 06:02:57 -08003128 if (info->inputConfig.test(WindowInfo::InputConfig::DISABLE_USER_ACTIVITY)) {
Josep del Riob3981622023-04-18 15:49:45 +00003129 windowDisablingUserActivityInfo = info;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003130 }
3131 }
3132
3133 int32_t eventType = USER_ACTIVITY_EVENT_OTHER;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003134 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003135 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003136 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
3137 if (motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003138 return;
3139 }
Josep del Riob3981622023-04-18 15:49:45 +00003140 if (windowDisablingUserActivityInfo != nullptr) {
3141 if (DEBUG_DISPATCH_CYCLE) {
3142 ALOGD("Not poking user activity: disabled by window '%s'.",
3143 windowDisablingUserActivityInfo->name.c_str());
3144 }
3145 return;
3146 }
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003147 if (MotionEvent::isTouchEvent(motionEntry.source, motionEntry.action)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003148 eventType = USER_ACTIVITY_EVENT_TOUCH;
3149 }
3150 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003151 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003152 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003153 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
3154 if (keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003155 return;
3156 }
Josep del Riob3981622023-04-18 15:49:45 +00003157 // If the key code is unknown, we don't consider it user activity
3158 if (keyEntry.keyCode == AKEYCODE_UNKNOWN) {
3159 return;
3160 }
3161 // Don't inhibit events that were intercepted or are not passed to
3162 // the apps, like system shortcuts
3163 if (windowDisablingUserActivityInfo != nullptr &&
3164 keyEntry.interceptKeyResult != KeyEntry::InterceptKeyResult::SKIP &&
3165 keyEntry.policyFlags & POLICY_FLAG_PASS_TO_USER) {
3166 if (DEBUG_DISPATCH_CYCLE) {
3167 ALOGD("Not poking user activity: disabled by window '%s'.",
3168 windowDisablingUserActivityInfo->name.c_str());
3169 }
3170 return;
3171 }
3172
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003173 eventType = USER_ACTIVITY_EVENT_BUTTON;
3174 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003175 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00003176 default: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003177 LOG_ALWAYS_FATAL("%s events are not user activity",
Dominik Laskowski75788452021-02-09 18:51:25 -08003178 ftl::enum_string(eventEntry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003179 break;
3180 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003181 }
3182
Prabir Pradhancef936d2021-07-21 16:17:52 +00003183 auto command = [this, eventTime = eventEntry.eventTime, eventType, displayId]()
3184 REQUIRES(mLock) {
3185 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00003186 mPolicy.pokeUserActivity(eventTime, eventType, displayId);
Prabir Pradhancef936d2021-07-21 16:17:52 +00003187 };
3188 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003189}
3190
3191void InputDispatcher::prepareDispatchCycleLocked(nsecs_t currentTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003192 const std::shared_ptr<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003193 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003194 const InputTarget& inputTarget) {
Prabir Pradhan2dac8b82023-09-06 01:11:51 +00003195 ATRACE_NAME_IF(ATRACE_ENABLED(),
3196 StringPrintf("prepareDispatchCycleLocked(inputChannel=%s, id=0x%" PRIx32 ")",
3197 connection->getInputChannelName().c_str(), eventEntry->id));
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003198 if (DEBUG_DISPATCH_CYCLE) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003199 ALOGD("channel '%s' ~ prepareDispatchCycle - flags=%s, "
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08003200 "globalScaleFactor=%f, pointerIds=%s %s",
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003201 connection->getInputChannelName().c_str(), inputTarget.flags.string().c_str(),
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08003202 inputTarget.globalScaleFactor, bitsetToString(inputTarget.pointerIds).c_str(),
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003203 inputTarget.getPointerInfoString().c_str());
3204 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003205
3206 // Skip this event if the connection status is not normal.
3207 // We don't want to enqueue additional outbound events if the connection is broken.
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003208 if (connection->status != Connection::Status::NORMAL) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003209 if (DEBUG_DISPATCH_CYCLE) {
3210 ALOGD("channel '%s' ~ Dropping event because the channel status is %s",
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003211 connection->getInputChannelName().c_str(),
3212 ftl::enum_string(connection->status).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003213 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003214 return;
3215 }
3216
3217 // Split a motion event if needed.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003218 if (inputTarget.flags.test(InputTarget::Flags::SPLIT)) {
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003219 LOG_ALWAYS_FATAL_IF(eventEntry->type != EventEntry::Type::MOTION,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003220 "Entry type %s should not have Flags::SPLIT",
Dominik Laskowski75788452021-02-09 18:51:25 -08003221 ftl::enum_string(eventEntry->type).c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003222
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003223 const MotionEntry& originalMotionEntry = static_cast<const MotionEntry&>(*eventEntry);
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003224 if (inputTarget.pointerIds.count() != originalMotionEntry.pointerCount) {
Siarhei Vishniakou16e4fa02023-02-16 17:48:56 -08003225 if (!inputTarget.firstDownTimeInTarget.has_value()) {
3226 logDispatchStateLocked();
3227 LOG(FATAL) << "Splitting motion events requires a down time to be set for the "
3228 "target on connection "
3229 << connection->getInputChannelName() << " for "
3230 << originalMotionEntry.getDescription();
3231 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003232 std::unique_ptr<MotionEntry> splitMotionEntry =
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00003233 splitMotionEvent(originalMotionEntry, inputTarget.pointerIds,
3234 inputTarget.firstDownTimeInTarget.value());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003235 if (!splitMotionEntry) {
3236 return; // split event was dropped
3237 }
Arthur Hungb3307ee2021-10-14 10:57:37 +00003238 if (splitMotionEntry->action == AMOTION_EVENT_ACTION_CANCEL) {
3239 std::string reason = std::string("reason=pointer cancel on split window");
3240 android_log_event_list(LOGTAG_INPUT_CANCEL)
3241 << connection->getInputChannelName().c_str() << reason << LOG_ID_EVENTS;
3242 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003243 if (DEBUG_FOCUS) {
3244 ALOGD("channel '%s' ~ Split motion event.",
3245 connection->getInputChannelName().c_str());
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003246 logOutboundMotionDetails(" ", *splitMotionEntry);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003247 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003248 enqueueDispatchEntriesLocked(currentTime, connection, std::move(splitMotionEntry),
3249 inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003250 return;
3251 }
3252 }
3253
3254 // Not splitting. Enqueue dispatch entries for the event as is.
3255 enqueueDispatchEntriesLocked(currentTime, connection, eventEntry, inputTarget);
3256}
3257
3258void InputDispatcher::enqueueDispatchEntriesLocked(nsecs_t currentTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003259 const std::shared_ptr<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003260 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003261 const InputTarget& inputTarget) {
Prabir Pradhan2dac8b82023-09-06 01:11:51 +00003262 ATRACE_NAME_IF(ATRACE_ENABLED(),
3263 StringPrintf("enqueueDispatchEntriesLocked(inputChannel=%s, id=0x%" PRIx32 ")",
3264 connection->getInputChannelName().c_str(), eventEntry->id));
Siarhei Vishniakou5cee1e32022-11-29 12:35:39 -08003265 LOG_ALWAYS_FATAL_IF(!inputTarget.flags.any(InputTarget::DISPATCH_MASK),
3266 "No dispatch flags are set for %s", eventEntry->getDescription().c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00003267
hongzuo liu95785e22022-09-06 02:51:35 +00003268 const bool wasEmpty = connection->outboundQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003269
3270 // Enqueue dispatch entries for the requested modes.
chaviw8c9cf542019-03-25 13:02:48 -07003271 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003272 InputTarget::Flags::DISPATCH_AS_HOVER_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07003273 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003274 InputTarget::Flags::DISPATCH_AS_OUTSIDE);
chaviw8c9cf542019-03-25 13:02:48 -07003275 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003276 InputTarget::Flags::DISPATCH_AS_HOVER_ENTER);
chaviw8c9cf542019-03-25 13:02:48 -07003277 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003278 InputTarget::Flags::DISPATCH_AS_IS);
chaviw8c9cf542019-03-25 13:02:48 -07003279 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003280 InputTarget::Flags::DISPATCH_AS_SLIPPERY_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07003281 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003282 InputTarget::Flags::DISPATCH_AS_SLIPPERY_ENTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003283
3284 // If the outbound queue was previously empty, start the dispatch cycle going.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003285 if (wasEmpty && !connection->outboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003286 startDispatchCycleLocked(currentTime, connection);
3287 }
3288}
3289
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003290void InputDispatcher::enqueueDispatchEntryLocked(const std::shared_ptr<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003291 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003292 const InputTarget& inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003293 ftl::Flags<InputTarget::Flags> dispatchMode) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003294 ftl::Flags<InputTarget::Flags> inputTargetFlags = inputTarget.flags;
3295 if (!inputTargetFlags.any(dispatchMode)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003296 return;
3297 }
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003298
3299 inputTargetFlags.clear(InputTarget::DISPATCH_MASK);
3300 inputTargetFlags |= dispatchMode;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003301
3302 // This is a new event.
3303 // Enqueue a new dispatch entry onto the outbound queue for this connection.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003304 std::unique_ptr<DispatchEntry> dispatchEntry =
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003305 createDispatchEntry(inputTarget, eventEntry, inputTargetFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003306
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003307 // Use the eventEntry from dispatchEntry since the entry may have changed and can now be a
3308 // different EventEntry than what was passed in.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003309 EventEntry& newEntry = *(dispatchEntry->eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003310 // Apply target flags and update the connection's input state.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003311 switch (newEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003312 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003313 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(newEntry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003314 if (!connection->inputState.trackKey(keyEntry, dispatchEntry->resolvedAction,
3315 dispatchEntry->resolvedFlags)) {
Siarhei Vishniakouc94dafe2023-05-26 10:24:19 -07003316 LOG(WARNING) << "channel " << connection->getInputChannelName()
3317 << "~ dropping inconsistent event: " << *dispatchEntry;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003318 return; // skip the inconsistent event
3319 }
3320 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003321 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003322
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003323 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003324 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003325 // Assign a default value to dispatchEntry that will never be generated by InputReader,
3326 // and assign a InputDispatcher value if it doesn't change in the if-else chain below.
3327 constexpr int32_t DEFAULT_RESOLVED_EVENT_ID =
3328 static_cast<int32_t>(IdGenerator::Source::OTHER);
3329 dispatchEntry->resolvedEventId = DEFAULT_RESOLVED_EVENT_ID;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003330 if (dispatchMode.test(InputTarget::Flags::DISPATCH_AS_OUTSIDE)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003331 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_OUTSIDE;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003332 } else if (dispatchMode.test(InputTarget::Flags::DISPATCH_AS_HOVER_EXIT)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003333 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_EXIT;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003334 } else if (dispatchMode.test(InputTarget::Flags::DISPATCH_AS_HOVER_ENTER)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003335 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003336 } else if (dispatchMode.test(InputTarget::Flags::DISPATCH_AS_SLIPPERY_EXIT)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003337 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_CANCEL;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003338 } else if (dispatchMode.test(InputTarget::Flags::DISPATCH_AS_SLIPPERY_ENTER)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003339 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_DOWN;
3340 } else {
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003341 dispatchEntry->resolvedEventId = motionEntry.id;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003342 }
3343 if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_HOVER_MOVE &&
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003344 !connection->inputState.isHovering(motionEntry.deviceId, motionEntry.source,
3345 motionEntry.displayId)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003346 if (DEBUG_DISPATCH_CYCLE) {
3347 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: filling in missing hover "
3348 "enter event",
3349 connection->getInputChannelName().c_str());
3350 }
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00003351 // We keep the 'resolvedEventId' here equal to the original 'motionEntry.id' because
3352 // this is a one-to-one event conversion.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003353 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
3354 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003355
Siarhei Vishniakou1ae72f12023-01-29 12:55:30 -08003356 if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_CANCEL) {
3357 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_CANCELED;
3358 }
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003359 if (dispatchEntry->targetFlags.test(InputTarget::Flags::WINDOW_IS_OBSCURED)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003360 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED;
3361 }
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003362 if (dispatchEntry->targetFlags.test(InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003363 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
3364 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003365
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003366 if (!connection->inputState.trackMotion(motionEntry, dispatchEntry->resolvedAction,
3367 dispatchEntry->resolvedFlags)) {
Siarhei Vishniakouc94dafe2023-05-26 10:24:19 -07003368 LOG(WARNING) << "channel " << connection->getInputChannelName()
3369 << "~ dropping inconsistent event: " << *dispatchEntry;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003370 return; // skip the inconsistent event
3371 }
3372
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003373 dispatchEntry->resolvedEventId =
3374 dispatchEntry->resolvedEventId == DEFAULT_RESOLVED_EVENT_ID
3375 ? mIdGenerator.nextId()
3376 : motionEntry.id;
3377 if (ATRACE_ENABLED() && dispatchEntry->resolvedEventId != motionEntry.id) {
3378 std::string message = StringPrintf("Transmute MotionEvent(id=0x%" PRIx32
3379 ") to MotionEvent(id=0x%" PRIx32 ").",
3380 motionEntry.id, dispatchEntry->resolvedEventId);
3381 ATRACE_NAME(message.c_str());
3382 }
3383
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08003384 if ((motionEntry.flags & AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE) &&
3385 (motionEntry.policyFlags & POLICY_FLAG_TRUSTED)) {
3386 // Skip reporting pointer down outside focus to the policy.
3387 break;
3388 }
3389
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003390 dispatchPointerDownOutsideFocus(motionEntry.source, dispatchEntry->resolvedAction,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003391 inputTarget.inputChannel->getConnectionToken());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003392
3393 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003394 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003395 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003396 case EventEntry::Type::TOUCH_MODE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08003397 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
3398 case EventEntry::Type::DRAG: {
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003399 break;
3400 }
Chris Yef59a2f42020-10-16 12:55:26 -07003401 case EventEntry::Type::SENSOR: {
3402 LOG_ALWAYS_FATAL("SENSOR events should not go to apps via input channel");
3403 break;
3404 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003405 case EventEntry::Type::CONFIGURATION_CHANGED:
3406 case EventEntry::Type::DEVICE_RESET: {
3407 LOG_ALWAYS_FATAL("%s events should not go to apps",
Dominik Laskowski75788452021-02-09 18:51:25 -08003408 ftl::enum_string(newEntry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003409 break;
3410 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003411 }
3412
3413 // Remember that we are waiting for this dispatch to complete.
3414 if (dispatchEntry->hasForegroundTarget()) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003415 incrementPendingForegroundDispatches(newEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003416 }
3417
3418 // Enqueue the dispatch entry.
Prabir Pradhan8c90d782023-09-15 21:16:44 +00003419 connection->outboundQueue.emplace_back(std::move(dispatchEntry));
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003420 traceOutboundQueueLength(*connection);
chaviw8c9cf542019-03-25 13:02:48 -07003421}
3422
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003423/**
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003424 * This function is for debugging and metrics collection. It has two roles.
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003425 *
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003426 * The first role is to log input interaction with windows, which helps determine what the user was
3427 * interacting with. For example, if user is touching launcher, we will see an input_interaction log
3428 * that user started interacting with launcher window, as well as any other window that received
3429 * that gesture, such as the wallpaper or other spy windows. A new input_interaction is only logged
3430 * when the set of tokens that received the event changes. It is not logged again as long as the
3431 * user is interacting with the same windows.
3432 *
3433 * The second role is to track input device activity for metrics collection. For each input event,
3434 * we report the set of UIDs that the input device interacted with to the policy. Unlike for the
3435 * input_interaction logs, the device interaction is reported even when the set of interaction
3436 * tokens do not change.
3437 *
3438 * For these purposes, we do not count ACTION_OUTSIDE, ACTION_UP and ACTION_CANCEL actions as
3439 * interaction. This includes up and cancel events for both keys and motions.
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003440 */
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003441void InputDispatcher::processInteractionsLocked(const EventEntry& entry,
3442 const std::vector<InputTarget>& targets) {
3443 int32_t deviceId;
3444 nsecs_t eventTime;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003445 // Skip ACTION_UP events, and all events other than keys and motions
3446 if (entry.type == EventEntry::Type::KEY) {
3447 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
3448 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
3449 return;
3450 }
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003451 deviceId = keyEntry.deviceId;
3452 eventTime = keyEntry.eventTime;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003453 } else if (entry.type == EventEntry::Type::MOTION) {
3454 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
3455 if (motionEntry.action == AMOTION_EVENT_ACTION_UP ||
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003456 motionEntry.action == AMOTION_EVENT_ACTION_CANCEL ||
3457 MotionEvent::getActionMasked(motionEntry.action) == AMOTION_EVENT_ACTION_POINTER_UP) {
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003458 return;
3459 }
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003460 deviceId = motionEntry.deviceId;
3461 eventTime = motionEntry.eventTime;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003462 } else {
3463 return; // Not a key or a motion
3464 }
3465
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003466 std::set<gui::Uid> interactionUids;
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07003467 std::unordered_set<sp<IBinder>, StrongPointerHash<IBinder>> newConnectionTokens;
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003468 std::vector<std::shared_ptr<Connection>> newConnections;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003469 for (const InputTarget& target : targets) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003470 if (target.flags.test(InputTarget::Flags::DISPATCH_AS_OUTSIDE)) {
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003471 continue; // Skip windows that receive ACTION_OUTSIDE
3472 }
3473
3474 sp<IBinder> token = target.inputChannel->getConnectionToken();
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003475 std::shared_ptr<Connection> connection = getConnectionLocked(token);
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003476 if (connection == nullptr) {
3477 continue;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003478 }
3479 newConnectionTokens.insert(std::move(token));
3480 newConnections.emplace_back(connection);
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003481 if (target.windowHandle) {
3482 interactionUids.emplace(target.windowHandle->getInfo()->ownerUid);
3483 }
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003484 }
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003485
3486 auto command = [this, deviceId, eventTime, uids = std::move(interactionUids)]()
3487 REQUIRES(mLock) {
3488 scoped_unlock unlock(mLock);
3489 mPolicy.notifyDeviceInteraction(deviceId, eventTime, uids);
3490 };
3491 postCommandLocked(std::move(command));
3492
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003493 if (newConnectionTokens == mInteractionConnectionTokens) {
3494 return; // no change
3495 }
3496 mInteractionConnectionTokens = newConnectionTokens;
3497
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003498 std::string targetList;
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003499 for (const std::shared_ptr<Connection>& connection : newConnections) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003500 targetList += connection->getWindowName() + ", ";
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003501 }
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003502 std::string message = "Interaction with: " + targetList;
3503 if (targetList.empty()) {
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003504 message += "<none>";
3505 }
3506 android_log_event_list(LOGTAG_INPUT_INTERACTION) << message << LOG_ID_EVENTS;
3507}
3508
chaviwfd6d3512019-03-25 13:23:49 -07003509void InputDispatcher::dispatchPointerDownOutsideFocus(uint32_t source, int32_t action,
Vishnu Nairad321cd2020-08-20 16:40:21 -07003510 const sp<IBinder>& token) {
chaviw8c9cf542019-03-25 13:02:48 -07003511 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
chaviwfd6d3512019-03-25 13:23:49 -07003512 uint32_t maskedSource = source & AINPUT_SOURCE_CLASS_MASK;
3513 if (maskedSource != AINPUT_SOURCE_CLASS_POINTER || maskedAction != AMOTION_EVENT_ACTION_DOWN) {
chaviw8c9cf542019-03-25 13:02:48 -07003514 return;
3515 }
3516
Vishnu Nairc519ff72021-01-21 08:23:08 -08003517 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07003518 if (focusedToken == token) {
3519 // ignore since token is focused
chaviw8c9cf542019-03-25 13:02:48 -07003520 return;
3521 }
3522
Prabir Pradhancef936d2021-07-21 16:17:52 +00003523 auto command = [this, token]() REQUIRES(mLock) {
3524 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00003525 mPolicy.onPointerDownOutsideFocus(token);
Prabir Pradhancef936d2021-07-21 16:17:52 +00003526 };
3527 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003528}
3529
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003530status_t InputDispatcher::publishMotionEvent(Connection& connection,
3531 DispatchEntry& dispatchEntry) const {
3532 const EventEntry& eventEntry = *(dispatchEntry.eventEntry);
3533 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
3534
3535 PointerCoords scaledCoords[MAX_POINTERS];
3536 const PointerCoords* usingCoords = motionEntry.pointerCoords;
3537
3538 // Set the X and Y offset and X and Y scale depending on the input source.
3539 if ((motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) &&
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003540 !(dispatchEntry.targetFlags.test(InputTarget::Flags::ZERO_COORDS))) {
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003541 float globalScaleFactor = dispatchEntry.globalScaleFactor;
3542 if (globalScaleFactor != 1.0f) {
3543 for (uint32_t i = 0; i < motionEntry.pointerCount; i++) {
3544 scaledCoords[i] = motionEntry.pointerCoords[i];
3545 // Don't apply window scale here since we don't want scale to affect raw
3546 // coordinates. The scale will be sent back to the client and applied
3547 // later when requesting relative coordinates.
Harry Cutts33476232023-01-30 19:57:29 +00003548 scaledCoords[i].scale(globalScaleFactor, /*windowXScale=*/1, /*windowYScale=*/1);
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003549 }
3550 usingCoords = scaledCoords;
3551 }
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003552 } else if (dispatchEntry.targetFlags.test(InputTarget::Flags::ZERO_COORDS)) {
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003553 // We don't want the dispatch target to know the coordinates
3554 for (uint32_t i = 0; i < motionEntry.pointerCount; i++) {
3555 scaledCoords[i].clear();
3556 }
3557 usingCoords = scaledCoords;
3558 }
3559
3560 std::array<uint8_t, 32> hmac = getSignature(motionEntry, dispatchEntry);
3561
3562 // Publish the motion event.
3563 return connection.inputPublisher
3564 .publishMotionEvent(dispatchEntry.seq, dispatchEntry.resolvedEventId,
3565 motionEntry.deviceId, motionEntry.source, motionEntry.displayId,
3566 std::move(hmac), dispatchEntry.resolvedAction,
3567 motionEntry.actionButton, dispatchEntry.resolvedFlags,
3568 motionEntry.edgeFlags, motionEntry.metaState,
3569 motionEntry.buttonState, motionEntry.classification,
3570 dispatchEntry.transform, motionEntry.xPrecision,
3571 motionEntry.yPrecision, motionEntry.xCursorPosition,
3572 motionEntry.yCursorPosition, dispatchEntry.rawTransform,
3573 motionEntry.downTime, motionEntry.eventTime,
3574 motionEntry.pointerCount, motionEntry.pointerProperties,
3575 usingCoords);
3576}
3577
Michael Wrightd02c5b62014-02-10 15:10:22 -08003578void InputDispatcher::startDispatchCycleLocked(nsecs_t currentTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003579 const std::shared_ptr<Connection>& connection) {
Prabir Pradhan2dac8b82023-09-06 01:11:51 +00003580 ATRACE_NAME_IF(ATRACE_ENABLED(),
3581 StringPrintf("startDispatchCycleLocked(inputChannel=%s)",
3582 connection->getInputChannelName().c_str()));
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003583 if (DEBUG_DISPATCH_CYCLE) {
3584 ALOGD("channel '%s' ~ startDispatchCycle", connection->getInputChannelName().c_str());
3585 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003586
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003587 while (connection->status == Connection::Status::NORMAL && !connection->outboundQueue.empty()) {
Prabir Pradhan8c90d782023-09-15 21:16:44 +00003588 std::unique_ptr<DispatchEntry>& dispatchEntry = connection->outboundQueue.front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003589 dispatchEntry->deliveryTime = currentTime;
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003590 const std::chrono::nanoseconds timeout = getDispatchingTimeoutLocked(connection);
Siarhei Vishniakou70622952020-07-30 11:17:23 -05003591 dispatchEntry->timeoutTime = currentTime + timeout.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003592
3593 // Publish the event.
3594 status_t status;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003595 const EventEntry& eventEntry = *(dispatchEntry->eventEntry);
3596 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003597 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003598 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
3599 std::array<uint8_t, 32> hmac = getSignature(keyEntry, *dispatchEntry);
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08003600 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07003601 LOG(INFO) << "Publishing " << *dispatchEntry << " to "
3602 << connection->getInputChannelName();
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08003603 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003604
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003605 // Publish the key event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003606 status = connection->inputPublisher
3607 .publishKeyEvent(dispatchEntry->seq,
3608 dispatchEntry->resolvedEventId, keyEntry.deviceId,
3609 keyEntry.source, keyEntry.displayId,
3610 std::move(hmac), dispatchEntry->resolvedAction,
3611 dispatchEntry->resolvedFlags, keyEntry.keyCode,
3612 keyEntry.scanCode, keyEntry.metaState,
3613 keyEntry.repeatCount, keyEntry.downTime,
3614 keyEntry.eventTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003615 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003616 }
3617
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003618 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08003619 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07003620 LOG(INFO) << "Publishing " << *dispatchEntry << " to "
3621 << connection->getInputChannelName();
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08003622 }
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003623 status = publishMotionEvent(*connection, *dispatchEntry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003624 break;
3625 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003626
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003627 case EventEntry::Type::FOCUS: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003628 const FocusEntry& focusEntry = static_cast<const FocusEntry&>(eventEntry);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003629 status = connection->inputPublisher.publishFocusEvent(dispatchEntry->seq,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003630 focusEntry.id,
Antonio Kantek3cfec7b2021-11-05 18:26:17 -07003631 focusEntry.hasFocus);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003632 break;
3633 }
3634
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003635 case EventEntry::Type::TOUCH_MODE_CHANGED: {
3636 const TouchModeEntry& touchModeEntry =
3637 static_cast<const TouchModeEntry&>(eventEntry);
3638 status = connection->inputPublisher
3639 .publishTouchModeEvent(dispatchEntry->seq, touchModeEntry.id,
3640 touchModeEntry.inTouchMode);
3641
3642 break;
3643 }
3644
Prabir Pradhan99987712020-11-10 18:43:05 -08003645 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
3646 const auto& captureEntry =
3647 static_cast<const PointerCaptureChangedEntry&>(eventEntry);
3648 status = connection->inputPublisher
3649 .publishCaptureEvent(dispatchEntry->seq, captureEntry.id,
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00003650 captureEntry.pointerCaptureRequest.enable);
Prabir Pradhan99987712020-11-10 18:43:05 -08003651 break;
3652 }
3653
arthurhungb89ccb02020-12-30 16:19:01 +08003654 case EventEntry::Type::DRAG: {
3655 const DragEntry& dragEntry = static_cast<const DragEntry&>(eventEntry);
3656 status = connection->inputPublisher.publishDragEvent(dispatchEntry->seq,
3657 dragEntry.id, dragEntry.x,
3658 dragEntry.y,
3659 dragEntry.isExiting);
3660 break;
3661 }
3662
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003663 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07003664 case EventEntry::Type::DEVICE_RESET:
3665 case EventEntry::Type::SENSOR: {
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003666 LOG_ALWAYS_FATAL("Should never start dispatch cycles for %s events",
Dominik Laskowski75788452021-02-09 18:51:25 -08003667 ftl::enum_string(eventEntry.type).c_str());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003668 return;
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003669 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003670 }
3671
3672 // Check the result.
3673 if (status) {
3674 if (status == WOULD_BLOCK) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003675 if (connection->waitQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003676 ALOGE("channel '%s' ~ Could not publish event because the pipe is full. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003677 "This is unexpected because the wait queue is empty, so the pipe "
3678 "should be empty and we shouldn't have any problems writing an "
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +00003679 "event to it, status=%s(%d)",
3680 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3681 status);
Harry Cutts33476232023-01-30 19:57:29 +00003682 abortBrokenDispatchCycleLocked(currentTime, connection, /*notify=*/true);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003683 } else {
3684 // Pipe is full and we are waiting for the app to finish process some events
3685 // before sending more events to it.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003686 if (DEBUG_DISPATCH_CYCLE) {
3687 ALOGD("channel '%s' ~ Could not publish event because the pipe is full, "
3688 "waiting for the application to catch up",
3689 connection->getInputChannelName().c_str());
3690 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003691 }
3692 } else {
3693 ALOGE("channel '%s' ~ Could not publish event due to an unexpected error, "
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +00003694 "status=%s(%d)",
3695 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3696 status);
Harry Cutts33476232023-01-30 19:57:29 +00003697 abortBrokenDispatchCycleLocked(currentTime, connection, /*notify=*/true);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003698 }
3699 return;
3700 }
3701
3702 // Re-enqueue the event on the wait queue.
Prabir Pradhan8c90d782023-09-15 21:16:44 +00003703 const nsecs_t timeoutTime = dispatchEntry->timeoutTime;
3704 connection->waitQueue.emplace_back(std::move(dispatchEntry));
3705 connection->outboundQueue.erase(connection->outboundQueue.begin());
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003706 traceOutboundQueueLength(*connection);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003707 if (connection->responsive) {
Prabir Pradhan8c90d782023-09-15 21:16:44 +00003708 mAnrTracker.insert(timeoutTime, connection->inputChannel->getConnectionToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003709 }
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003710 traceWaitQueueLength(*connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003711 }
3712}
3713
chaviw09c8d2d2020-08-24 15:48:26 -07003714std::array<uint8_t, 32> InputDispatcher::sign(const VerifiedInputEvent& event) const {
3715 size_t size;
3716 switch (event.type) {
3717 case VerifiedInputEvent::Type::KEY: {
3718 size = sizeof(VerifiedKeyEvent);
3719 break;
3720 }
3721 case VerifiedInputEvent::Type::MOTION: {
3722 size = sizeof(VerifiedMotionEvent);
3723 break;
3724 }
3725 }
3726 const uint8_t* start = reinterpret_cast<const uint8_t*>(&event);
3727 return mHmacKeyManager.sign(start, size);
3728}
3729
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003730const std::array<uint8_t, 32> InputDispatcher::getSignature(
3731 const MotionEntry& motionEntry, const DispatchEntry& dispatchEntry) const {
Siarhei Vishniakoubf880522023-05-01 11:03:22 -07003732 const int32_t actionMasked = MotionEvent::getActionMasked(dispatchEntry.resolvedAction);
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003733 if (actionMasked != AMOTION_EVENT_ACTION_UP && actionMasked != AMOTION_EVENT_ACTION_DOWN) {
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003734 // Only sign events up and down events as the purely move events
3735 // are tied to their up/down counterparts so signing would be redundant.
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003736 return INVALID_HMAC;
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003737 }
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003738
3739 VerifiedMotionEvent verifiedEvent =
3740 verifiedMotionEventFromMotionEntry(motionEntry, dispatchEntry.rawTransform);
3741 verifiedEvent.actionMasked = actionMasked;
3742 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_MOTION_EVENT_FLAGS;
3743 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003744}
3745
3746const std::array<uint8_t, 32> InputDispatcher::getSignature(
3747 const KeyEntry& keyEntry, const DispatchEntry& dispatchEntry) const {
3748 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEntry(keyEntry);
3749 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_KEY_EVENT_FLAGS;
3750 verifiedEvent.action = dispatchEntry.resolvedAction;
chaviw09c8d2d2020-08-24 15:48:26 -07003751 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003752}
3753
Michael Wrightd02c5b62014-02-10 15:10:22 -08003754void InputDispatcher::finishDispatchCycleLocked(nsecs_t currentTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003755 const std::shared_ptr<Connection>& connection,
3756 uint32_t seq, bool handled, nsecs_t consumeTime) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003757 if (DEBUG_DISPATCH_CYCLE) {
3758 ALOGD("channel '%s' ~ finishDispatchCycle - seq=%u, handled=%s",
3759 connection->getInputChannelName().c_str(), seq, toString(handled));
3760 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003761
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003762 if (connection->status == Connection::Status::BROKEN ||
3763 connection->status == Connection::Status::ZOMBIE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003764 return;
3765 }
3766
3767 // Notify other system components and prepare to start the next dispatch cycle.
Prabir Pradhancef936d2021-07-21 16:17:52 +00003768 auto command = [this, currentTime, connection, seq, handled, consumeTime]() REQUIRES(mLock) {
3769 doDispatchCycleFinishedCommand(currentTime, connection, seq, handled, consumeTime);
3770 };
3771 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003772}
3773
3774void InputDispatcher::abortBrokenDispatchCycleLocked(nsecs_t currentTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003775 const std::shared_ptr<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003776 bool notify) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003777 if (DEBUG_DISPATCH_CYCLE) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07003778 LOG(INFO) << "channel '" << connection->getInputChannelName() << "'~ " << __func__
3779 << " - notify=" << toString(notify);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003780 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003781
3782 // Clear the dispatch queues.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003783 drainDispatchQueue(connection->outboundQueue);
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003784 traceOutboundQueueLength(*connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003785 drainDispatchQueue(connection->waitQueue);
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003786 traceWaitQueueLength(*connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003787
3788 // The connection appears to be unrecoverably broken.
3789 // Ignore already broken or zombie connections.
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003790 if (connection->status == Connection::Status::NORMAL) {
3791 connection->status = Connection::Status::BROKEN;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003792
3793 if (notify) {
3794 // Notify other system components.
Prabir Pradhancef936d2021-07-21 16:17:52 +00003795 ALOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
3796 connection->getInputChannelName().c_str());
3797
3798 auto command = [this, connection]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00003799 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00003800 mPolicy.notifyInputChannelBroken(connection->inputChannel->getConnectionToken());
Prabir Pradhancef936d2021-07-21 16:17:52 +00003801 };
3802 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003803 }
3804 }
3805}
3806
Prabir Pradhan8c90d782023-09-15 21:16:44 +00003807void InputDispatcher::drainDispatchQueue(std::deque<std::unique_ptr<DispatchEntry>>& queue) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003808 while (!queue.empty()) {
Prabir Pradhan8c90d782023-09-15 21:16:44 +00003809 releaseDispatchEntry(std::move(queue.front()));
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003810 queue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003811 }
3812}
3813
Prabir Pradhan8c90d782023-09-15 21:16:44 +00003814void InputDispatcher::releaseDispatchEntry(std::unique_ptr<DispatchEntry> dispatchEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003815 if (dispatchEntry->hasForegroundTarget()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003816 decrementPendingForegroundDispatches(*(dispatchEntry->eventEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003817 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003818}
3819
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003820int InputDispatcher::handleReceiveCallback(int events, sp<IBinder> connectionToken) {
3821 std::scoped_lock _l(mLock);
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003822 std::shared_ptr<Connection> connection = getConnectionLocked(connectionToken);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003823 if (connection == nullptr) {
3824 ALOGW("Received looper callback for unknown input channel token %p. events=0x%x",
3825 connectionToken.get(), events);
3826 return 0; // remove the callback
3827 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003828
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003829 bool notify;
3830 if (!(events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP))) {
3831 if (!(events & ALOOPER_EVENT_INPUT)) {
3832 ALOGW("channel '%s' ~ Received spurious callback for unhandled poll event. "
3833 "events=0x%x",
3834 connection->getInputChannelName().c_str(), events);
3835 return 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003836 }
3837
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003838 nsecs_t currentTime = now();
3839 bool gotOne = false;
3840 status_t status = OK;
3841 for (;;) {
3842 Result<InputPublisher::ConsumerResponse> result =
3843 connection->inputPublisher.receiveConsumerResponse();
3844 if (!result.ok()) {
3845 status = result.error().code();
3846 break;
3847 }
3848
3849 if (std::holds_alternative<InputPublisher::Finished>(*result)) {
3850 const InputPublisher::Finished& finish =
3851 std::get<InputPublisher::Finished>(*result);
3852 finishDispatchCycleLocked(currentTime, connection, finish.seq, finish.handled,
3853 finish.consumeTime);
3854 } else if (std::holds_alternative<InputPublisher::Timeline>(*result)) {
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00003855 if (shouldReportMetricsForConnection(*connection)) {
3856 const InputPublisher::Timeline& timeline =
3857 std::get<InputPublisher::Timeline>(*result);
3858 mLatencyTracker
3859 .trackGraphicsLatency(timeline.inputEventId,
3860 connection->inputChannel->getConnectionToken(),
3861 std::move(timeline.graphicsTimeline));
3862 }
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003863 }
3864 gotOne = true;
3865 }
3866 if (gotOne) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00003867 runCommandsLockedInterruptable();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003868 if (status == WOULD_BLOCK) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003869 return 1;
3870 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003871 }
3872
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003873 notify = status != DEAD_OBJECT || !connection->monitor;
3874 if (notify) {
3875 ALOGE("channel '%s' ~ Failed to receive finished signal. status=%s(%d)",
3876 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3877 status);
3878 }
3879 } else {
3880 // Monitor channels are never explicitly unregistered.
3881 // We do it automatically when the remote endpoint is closed so don't warn about them.
3882 const bool stillHaveWindowHandle =
3883 getWindowHandleLocked(connection->inputChannel->getConnectionToken()) != nullptr;
3884 notify = !connection->monitor && stillHaveWindowHandle;
3885 if (notify) {
3886 ALOGW("channel '%s' ~ Consumer closed input channel or an error occurred. events=0x%x",
3887 connection->getInputChannelName().c_str(), events);
3888 }
3889 }
3890
3891 // Remove the channel.
3892 removeInputChannelLocked(connection->inputChannel->getConnectionToken(), notify);
3893 return 0; // remove the callback
Michael Wrightd02c5b62014-02-10 15:10:22 -08003894}
3895
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003896void InputDispatcher::synthesizeCancelationEventsForAllConnectionsLocked(
Michael Wrightd02c5b62014-02-10 15:10:22 -08003897 const CancelationOptions& options) {
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003898 for (const auto& [token, connection] : mConnectionsByToken) {
Siarhei Vishniakou2e2ea992020-12-15 02:57:19 +00003899 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003900 }
3901}
3902
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003903void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
Michael Wrightfa13dcf2015-06-12 13:25:11 +01003904 const CancelationOptions& options) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08003905 for (const auto& [_, monitors] : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003906 for (const Monitor& monitor : monitors) {
3907 synthesizeCancelationEventsForInputChannelLocked(monitor.inputChannel, options);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003908 }
Michael Wrightfa13dcf2015-06-12 13:25:11 +01003909 }
3910}
3911
Michael Wrightd02c5b62014-02-10 15:10:22 -08003912void InputDispatcher::synthesizeCancelationEventsForInputChannelLocked(
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05003913 const std::shared_ptr<InputChannel>& channel, const CancelationOptions& options) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003914 std::shared_ptr<Connection> connection = getConnectionLocked(channel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003915 if (connection == nullptr) {
3916 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003917 }
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003918
3919 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003920}
3921
3922void InputDispatcher::synthesizeCancelationEventsForConnectionLocked(
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003923 const std::shared_ptr<Connection>& connection, const CancelationOptions& options) {
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003924 if (connection->status == Connection::Status::BROKEN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003925 return;
3926 }
3927
3928 nsecs_t currentTime = now();
3929
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003930 std::vector<std::unique_ptr<EventEntry>> cancelationEvents =
Siarhei Vishniakou00fca7c2019-10-29 13:05:57 -07003931 connection->inputState.synthesizeCancelationEvents(currentTime, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003932
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003933 if (cancelationEvents.empty()) {
3934 return;
3935 }
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003936 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
3937 ALOGD("channel '%s' ~ Synthesized %zu cancelation events to bring channel back in sync "
Siarhei Vishniakou2e3e4432023-02-09 18:34:11 -08003938 "with reality: %s, mode=%s.",
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003939 connection->getInputChannelName().c_str(), cancelationEvents.size(), options.reason,
Siarhei Vishniakou2e3e4432023-02-09 18:34:11 -08003940 ftl::enum_string(options.mode).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003941 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08003942
Arthur Hungb3307ee2021-10-14 10:57:37 +00003943 std::string reason = std::string("reason=").append(options.reason);
3944 android_log_event_list(LOGTAG_INPUT_CANCEL)
3945 << connection->getInputChannelName().c_str() << reason << LOG_ID_EVENTS;
3946
Svet Ganov5d3bc372020-01-26 23:11:07 -08003947 InputTarget target;
Hu Guo771a7692023-09-17 20:51:08 +08003948 sp<WindowInfoHandle> windowHandle;
3949 if (options.displayId) {
3950 windowHandle = getWindowHandleLocked(connection->inputChannel->getConnectionToken(),
3951 options.displayId.value());
3952 } else {
3953 windowHandle = getWindowHandleLocked(connection->inputChannel->getConnectionToken());
3954 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08003955 if (windowHandle != nullptr) {
chaviw98318de2021-05-19 16:45:23 -05003956 const WindowInfo* windowInfo = windowHandle->getInfo();
chaviw1ff3d1e2020-07-01 15:53:47 -07003957 target.setDefaultPointerTransform(windowInfo->transform);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003958 target.globalScaleFactor = windowInfo->globalScaleFactor;
3959 }
3960 target.inputChannel = connection->inputChannel;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003961 target.flags = InputTarget::Flags::DISPATCH_AS_IS;
Svet Ganov5d3bc372020-01-26 23:11:07 -08003962
hongzuo liu95785e22022-09-06 02:51:35 +00003963 const bool wasEmpty = connection->outboundQueue.empty();
3964
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003965 for (size_t i = 0; i < cancelationEvents.size(); i++) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003966 std::unique_ptr<EventEntry> cancelationEventEntry = std::move(cancelationEvents[i]);
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003967 switch (cancelationEventEntry->type) {
3968 case EventEntry::Type::KEY: {
3969 logOutboundKeyDetails("cancel - ",
3970 static_cast<const KeyEntry&>(*cancelationEventEntry));
3971 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003972 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003973 case EventEntry::Type::MOTION: {
3974 logOutboundMotionDetails("cancel - ",
3975 static_cast<const MotionEntry&>(*cancelationEventEntry));
3976 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003977 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003978 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003979 case EventEntry::Type::TOUCH_MODE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08003980 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
3981 case EventEntry::Type::DRAG: {
Prabir Pradhan99987712020-11-10 18:43:05 -08003982 LOG_ALWAYS_FATAL("Canceling %s events is not supported",
Dominik Laskowski75788452021-02-09 18:51:25 -08003983 ftl::enum_string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003984 break;
3985 }
3986 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07003987 case EventEntry::Type::DEVICE_RESET:
3988 case EventEntry::Type::SENSOR: {
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003989 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Dominik Laskowski75788452021-02-09 18:51:25 -08003990 ftl::enum_string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003991 break;
3992 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003993 }
3994
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003995 enqueueDispatchEntryLocked(connection, std::move(cancelationEventEntry), target,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003996 InputTarget::Flags::DISPATCH_AS_IS);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003997 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003998
hongzuo liu95785e22022-09-06 02:51:35 +00003999 // If the outbound queue was previously empty, start the dispatch cycle going.
4000 if (wasEmpty && !connection->outboundQueue.empty()) {
4001 startDispatchCycleLocked(currentTime, connection);
4002 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004003}
4004
Svet Ganov5d3bc372020-01-26 23:11:07 -08004005void InputDispatcher::synthesizePointerDownEventsForConnectionLocked(
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07004006 const nsecs_t downTime, const std::shared_ptr<Connection>& connection,
Arthur Hungc539dbb2022-12-08 07:45:36 +00004007 ftl::Flags<InputTarget::Flags> targetFlags) {
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08004008 if (connection->status == Connection::Status::BROKEN) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08004009 return;
4010 }
4011
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004012 std::vector<std::unique_ptr<EventEntry>> downEvents =
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00004013 connection->inputState.synthesizePointerDownEvents(downTime);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004014
4015 if (downEvents.empty()) {
4016 return;
4017 }
4018
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004019 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08004020 ALOGD("channel '%s' ~ Synthesized %zu down events to ensure consistent event stream.",
4021 connection->getInputChannelName().c_str(), downEvents.size());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004022 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08004023
4024 InputTarget target;
chaviw98318de2021-05-19 16:45:23 -05004025 sp<WindowInfoHandle> windowHandle =
Svet Ganov5d3bc372020-01-26 23:11:07 -08004026 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
4027 if (windowHandle != nullptr) {
chaviw98318de2021-05-19 16:45:23 -05004028 const WindowInfo* windowInfo = windowHandle->getInfo();
chaviw1ff3d1e2020-07-01 15:53:47 -07004029 target.setDefaultPointerTransform(windowInfo->transform);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004030 target.globalScaleFactor = windowInfo->globalScaleFactor;
4031 }
4032 target.inputChannel = connection->inputChannel;
Arthur Hungc539dbb2022-12-08 07:45:36 +00004033 target.flags = targetFlags;
Svet Ganov5d3bc372020-01-26 23:11:07 -08004034
hongzuo liu95785e22022-09-06 02:51:35 +00004035 const bool wasEmpty = connection->outboundQueue.empty();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004036 for (std::unique_ptr<EventEntry>& downEventEntry : downEvents) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08004037 switch (downEventEntry->type) {
4038 case EventEntry::Type::MOTION: {
4039 logOutboundMotionDetails("down - ",
4040 static_cast<const MotionEntry&>(*downEventEntry));
4041 break;
4042 }
4043
4044 case EventEntry::Type::KEY:
4045 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07004046 case EventEntry::Type::TOUCH_MODE_CHANGED:
Svet Ganov5d3bc372020-01-26 23:11:07 -08004047 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08004048 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07004049 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08004050 case EventEntry::Type::SENSOR:
4051 case EventEntry::Type::DRAG: {
Svet Ganov5d3bc372020-01-26 23:11:07 -08004052 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Dominik Laskowski75788452021-02-09 18:51:25 -08004053 ftl::enum_string(downEventEntry->type).c_str());
Svet Ganov5d3bc372020-01-26 23:11:07 -08004054 break;
4055 }
4056 }
4057
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004058 enqueueDispatchEntryLocked(connection, std::move(downEventEntry), target,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08004059 InputTarget::Flags::DISPATCH_AS_IS);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004060 }
4061
hongzuo liu95785e22022-09-06 02:51:35 +00004062 // If the outbound queue was previously empty, start the dispatch cycle going.
4063 if (wasEmpty && !connection->outboundQueue.empty()) {
4064 startDispatchCycleLocked(downTime, connection);
4065 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08004066}
4067
Arthur Hungc539dbb2022-12-08 07:45:36 +00004068void InputDispatcher::synthesizeCancelationEventsForWindowLocked(
4069 const sp<WindowInfoHandle>& windowHandle, const CancelationOptions& options) {
4070 if (windowHandle != nullptr) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07004071 std::shared_ptr<Connection> wallpaperConnection =
4072 getConnectionLocked(windowHandle->getToken());
Arthur Hungc539dbb2022-12-08 07:45:36 +00004073 if (wallpaperConnection != nullptr) {
4074 synthesizeCancelationEventsForConnectionLocked(wallpaperConnection, options);
4075 }
4076 }
4077}
4078
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004079std::unique_ptr<MotionEntry> InputDispatcher::splitMotionEvent(
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08004080 const MotionEntry& originalMotionEntry, std::bitset<MAX_POINTER_ID + 1> pointerIds,
4081 nsecs_t splitDownTime) {
4082 ALOG_ASSERT(pointerIds.any());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004083
4084 uint32_t splitPointerIndexMap[MAX_POINTERS];
4085 PointerProperties splitPointerProperties[MAX_POINTERS];
4086 PointerCoords splitPointerCoords[MAX_POINTERS];
4087
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07004088 uint32_t originalPointerCount = originalMotionEntry.pointerCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004089 uint32_t splitPointerCount = 0;
4090
4091 for (uint32_t originalPointerIndex = 0; originalPointerIndex < originalPointerCount;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004092 originalPointerIndex++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004093 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07004094 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08004095 uint32_t pointerId = uint32_t(pointerProperties.id);
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08004096 if (pointerIds.test(pointerId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004097 splitPointerIndexMap[splitPointerCount] = originalPointerIndex;
Siarhei Vishniakou73e6d372023-07-06 18:07:21 -07004098 splitPointerProperties[splitPointerCount] = pointerProperties;
4099 splitPointerCoords[splitPointerCount] =
4100 originalMotionEntry.pointerCoords[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08004101 splitPointerCount += 1;
4102 }
4103 }
4104
4105 if (splitPointerCount != pointerIds.count()) {
4106 // This is bad. We are missing some of the pointers that we expected to deliver.
4107 // Most likely this indicates that we received an ACTION_MOVE events that has
4108 // different pointer ids than we expected based on the previous ACTION_DOWN
4109 // or ACTION_POINTER_DOWN events that caused us to decide to split the pointers
4110 // in this way.
4111 ALOGW("Dropping split motion event because the pointer count is %d but "
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08004112 "we expected there to be %zu pointers. This probably means we received "
Siarhei Vishniakou16e4fa02023-02-16 17:48:56 -08004113 "a broken sequence of pointer ids from the input device: %s",
4114 splitPointerCount, pointerIds.count(), originalMotionEntry.getDescription().c_str());
Yi Kong9b14ac62018-07-17 13:48:38 -07004115 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004116 }
4117
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07004118 int32_t action = originalMotionEntry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004119 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004120 if (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN ||
4121 maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
Siarhei Vishniakou5b9766d2023-07-18 14:06:29 -07004122 int32_t originalPointerIndex = MotionEvent::getActionIndex(action);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004123 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07004124 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08004125 uint32_t pointerId = uint32_t(pointerProperties.id);
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08004126 if (pointerIds.test(pointerId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004127 if (pointerIds.count() == 1) {
4128 // The first/last pointer went down/up.
4129 action = maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004130 ? AMOTION_EVENT_ACTION_DOWN
arthurhungea3f4fc2020-12-21 23:18:53 +08004131 : (originalMotionEntry.flags & AMOTION_EVENT_FLAG_CANCELED) != 0
4132 ? AMOTION_EVENT_ACTION_CANCEL
4133 : AMOTION_EVENT_ACTION_UP;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004134 } else {
4135 // A secondary pointer went down/up.
4136 uint32_t splitPointerIndex = 0;
4137 while (pointerId != uint32_t(splitPointerProperties[splitPointerIndex].id)) {
4138 splitPointerIndex += 1;
4139 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004140 action = maskedAction |
4141 (splitPointerIndex << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004142 }
4143 } else {
4144 // An unrelated pointer changed.
4145 action = AMOTION_EVENT_ACTION_MOVE;
4146 }
4147 }
4148
Siarhei Vishniakou59e302b2023-06-05 08:04:53 -07004149 if (action == AMOTION_EVENT_ACTION_DOWN && splitDownTime != originalMotionEntry.eventTime) {
4150 logDispatchStateLocked();
4151 LOG_ALWAYS_FATAL("Split motion event has mismatching downTime and eventTime for "
4152 "ACTION_DOWN, motionEntry=%s, splitDownTime=%" PRId64,
4153 originalMotionEntry.getDescription().c_str(), splitDownTime);
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00004154 }
4155
Garfield Tanff1f1bb2020-01-28 13:24:04 -08004156 int32_t newId = mIdGenerator.nextId();
Prabir Pradhan2dac8b82023-09-06 01:11:51 +00004157 ATRACE_NAME_IF(ATRACE_ENABLED(),
4158 StringPrintf("Split MotionEvent(id=0x%" PRIx32 ") to MotionEvent(id=0x%" PRIx32
4159 ").",
4160 originalMotionEntry.id, newId));
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004161 std::unique_ptr<MotionEntry> splitMotionEntry =
4162 std::make_unique<MotionEntry>(newId, originalMotionEntry.eventTime,
4163 originalMotionEntry.deviceId, originalMotionEntry.source,
4164 originalMotionEntry.displayId,
4165 originalMotionEntry.policyFlags, action,
4166 originalMotionEntry.actionButton,
4167 originalMotionEntry.flags, originalMotionEntry.metaState,
4168 originalMotionEntry.buttonState,
4169 originalMotionEntry.classification,
4170 originalMotionEntry.edgeFlags,
4171 originalMotionEntry.xPrecision,
4172 originalMotionEntry.yPrecision,
4173 originalMotionEntry.xCursorPosition,
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00004174 originalMotionEntry.yCursorPosition, splitDownTime,
4175 splitPointerCount, splitPointerProperties,
4176 splitPointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004177
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07004178 if (originalMotionEntry.injectionState) {
4179 splitMotionEntry->injectionState = originalMotionEntry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004180 splitMotionEntry->injectionState->refCount += 1;
4181 }
4182
4183 return splitMotionEntry;
4184}
4185
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004186void InputDispatcher::notifyConfigurationChanged(const NotifyConfigurationChangedArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004187 if (debugInboundEventDetails()) {
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004188 ALOGD("notifyConfigurationChanged - eventTime=%" PRId64, args.eventTime);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004189 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004190
Antonio Kantekf16f2832021-09-28 04:39:20 +00004191 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004192 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004193 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004194
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004195 std::unique_ptr<ConfigurationChangedEntry> newEntry =
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004196 std::make_unique<ConfigurationChangedEntry>(args.id, args.eventTime);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004197 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004198 } // release lock
4199
4200 if (needWake) {
4201 mLooper->wake();
4202 }
4203}
4204
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004205void InputDispatcher::notifyKey(const NotifyKeyArgs& args) {
Prabir Pradhan96282b02023-02-24 22:36:17 +00004206 ALOGD_IF(debugInboundEventDetails(),
4207 "notifyKey - id=%" PRIx32 ", eventTime=%" PRId64
4208 ", deviceId=%d, source=%s, displayId=%" PRId32
4209 "policyFlags=0x%x, action=%s, flags=0x%x, keyCode=%s, scanCode=0x%x, metaState=0x%x, "
4210 "downTime=%" PRId64,
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004211 args.id, args.eventTime, args.deviceId, inputEventSourceToString(args.source).c_str(),
4212 args.displayId, args.policyFlags, KeyEvent::actionToString(args.action), args.flags,
4213 KeyEvent::getLabel(args.keyCode), args.scanCode, args.metaState, args.downTime);
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004214 Result<void> keyCheck = validateKeyEvent(args.action);
4215 if (!keyCheck.ok()) {
4216 LOG(ERROR) << "invalid key event: " << keyCheck.error();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004217 return;
4218 }
4219
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004220 uint32_t policyFlags = args.policyFlags;
4221 int32_t flags = args.flags;
4222 int32_t metaState = args.metaState;
Siarhei Vishniakou622bd322018-10-29 18:02:27 -07004223 // InputDispatcher tracks and generates key repeats on behalf of
4224 // whatever notifies it, so repeatCount should always be set to 0
4225 constexpr int32_t repeatCount = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004226 if ((policyFlags & POLICY_FLAG_VIRTUAL) || (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY)) {
4227 policyFlags |= POLICY_FLAG_VIRTUAL;
4228 flags |= AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
4229 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004230 if (policyFlags & POLICY_FLAG_FUNCTION) {
4231 metaState |= AMETA_FUNCTION_ON;
4232 }
4233
4234 policyFlags |= POLICY_FLAG_TRUSTED;
4235
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004236 int32_t keyCode = args.keyCode;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004237 KeyEvent event;
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004238 event.initialize(args.id, args.deviceId, args.source, args.displayId, INVALID_HMAC, args.action,
4239 flags, keyCode, args.scanCode, metaState, repeatCount, args.downTime,
4240 args.eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004241
Michael Wright2b3c3302018-03-02 17:19:13 +00004242 android::base::Timer t;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004243 mPolicy.interceptKeyBeforeQueueing(event, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00004244 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4245 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004246 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00004247 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004248
Antonio Kantekf16f2832021-09-28 04:39:20 +00004249 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004250 { // acquire lock
4251 mLock.lock();
4252
4253 if (shouldSendKeyToInputFilterLocked(args)) {
4254 mLock.unlock();
4255
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004256 policyFlags |= POLICY_FLAG_FILTERED;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004257 if (!mPolicy.filterInputEvent(event, policyFlags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004258 return; // event was consumed by the filter
4259 }
4260
4261 mLock.lock();
4262 }
4263
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004264 std::unique_ptr<KeyEntry> newEntry =
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004265 std::make_unique<KeyEntry>(args.id, args.eventTime, args.deviceId, args.source,
4266 args.displayId, policyFlags, args.action, flags, keyCode,
4267 args.scanCode, metaState, repeatCount, args.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004268
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004269 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004270 mLock.unlock();
4271 } // release lock
4272
4273 if (needWake) {
4274 mLooper->wake();
4275 }
4276}
4277
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004278bool InputDispatcher::shouldSendKeyToInputFilterLocked(const NotifyKeyArgs& args) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004279 return mInputFilterEnabled;
4280}
4281
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004282void InputDispatcher::notifyMotion(const NotifyMotionArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004283 if (debugInboundEventDetails()) {
Prabir Pradhan96282b02023-02-24 22:36:17 +00004284 ALOGD("notifyMotion - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=%s, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004285 "displayId=%" PRId32 ", policyFlags=0x%x, "
Siarhei Vishniakou6ebd0692022-10-20 15:05:45 -07004286 "action=%s, actionButton=0x%x, flags=0x%x, metaState=0x%x, buttonState=0x%x, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004287 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, xCursorPosition=%f, "
4288 "yCursorPosition=%f, downTime=%" PRId64,
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004289 args.id, args.eventTime, args.deviceId, inputEventSourceToString(args.source).c_str(),
4290 args.displayId, args.policyFlags, MotionEvent::actionToString(args.action).c_str(),
4291 args.actionButton, args.flags, args.metaState, args.buttonState, args.edgeFlags,
4292 args.xPrecision, args.yPrecision, args.xCursorPosition, args.yCursorPosition,
4293 args.downTime);
Siarhei Vishniakou3218fc02023-06-15 20:41:02 -07004294 for (uint32_t i = 0; i < args.getPointerCount(); i++) {
Prabir Pradhan96282b02023-02-24 22:36:17 +00004295 ALOGD(" Pointer %d: id=%d, toolType=%s, x=%f, y=%f, pressure=%f, size=%f, "
4296 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, orientation=%f",
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004297 i, args.pointerProperties[i].id,
4298 ftl::enum_string(args.pointerProperties[i].toolType).c_str(),
4299 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
4300 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
4301 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
4302 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
4303 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
4304 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
4305 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
4306 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
4307 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004308 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004309 }
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004310
Siarhei Vishniakou3218fc02023-06-15 20:41:02 -07004311 Result<void> motionCheck =
4312 validateMotionEvent(args.action, args.actionButton, args.getPointerCount(),
4313 args.pointerProperties.data());
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004314 if (!motionCheck.ok()) {
4315 LOG(FATAL) << "Invalid event: " << args.dump() << "; reason: " << motionCheck.error();
4316 return;
4317 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004318
Siarhei Vishniakou5c02a712023-05-15 15:45:02 -07004319 if (DEBUG_VERIFY_EVENTS) {
4320 auto [it, _] =
4321 mVerifiersByDisplay.try_emplace(args.displayId,
4322 StringPrintf("display %" PRId32, args.displayId));
4323 Result<void> result =
Siarhei Vishniakou2d151ac2023-09-19 13:30:24 -07004324 it->second.processMovement(args.deviceId, args.source, args.action,
4325 args.getPointerCount(), args.pointerProperties.data(),
4326 args.pointerCoords.data(), args.flags);
Siarhei Vishniakou5c02a712023-05-15 15:45:02 -07004327 if (!result.ok()) {
4328 LOG(FATAL) << "Bad stream: " << result.error() << " caused by " << args.dump();
4329 }
4330 }
4331
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004332 uint32_t policyFlags = args.policyFlags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004333 policyFlags |= POLICY_FLAG_TRUSTED;
Michael Wright2b3c3302018-03-02 17:19:13 +00004334
4335 android::base::Timer t;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004336 mPolicy.interceptMotionBeforeQueueing(args.displayId, args.eventTime, policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00004337 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4338 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004339 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00004340 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004341
Antonio Kantekf16f2832021-09-28 04:39:20 +00004342 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004343 { // acquire lock
4344 mLock.lock();
Siarhei Vishniakou5bf25d92023-02-08 15:43:38 -08004345 if (!(policyFlags & POLICY_FLAG_PASS_TO_USER)) {
4346 // Set the flag anyway if we already have an ongoing gesture. That would allow us to
4347 // complete the processing of the current stroke.
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004348 const auto touchStateIt = mTouchStatesByDisplay.find(args.displayId);
Siarhei Vishniakou5bf25d92023-02-08 15:43:38 -08004349 if (touchStateIt != mTouchStatesByDisplay.end()) {
4350 const TouchState& touchState = touchStateIt->second;
Siarhei Vishniakou45504fe2023-05-05 16:05:10 -07004351 if (touchState.hasTouchingPointers(args.deviceId)) {
Siarhei Vishniakou5bf25d92023-02-08 15:43:38 -08004352 policyFlags |= POLICY_FLAG_PASS_TO_USER;
4353 }
4354 }
4355 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004356
4357 if (shouldSendMotionToInputFilterLocked(args)) {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004358 ui::Transform displayTransform;
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004359 if (const auto it = mDisplayInfos.find(args.displayId); it != mDisplayInfos.end()) {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004360 displayTransform = it->second.transform;
4361 }
4362
Michael Wrightd02c5b62014-02-10 15:10:22 -08004363 mLock.unlock();
4364
4365 MotionEvent event;
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004366 event.initialize(args.id, args.deviceId, args.source, args.displayId, INVALID_HMAC,
4367 args.action, args.actionButton, args.flags, args.edgeFlags,
4368 args.metaState, args.buttonState, args.classification,
4369 displayTransform, args.xPrecision, args.yPrecision,
4370 args.xCursorPosition, args.yCursorPosition, displayTransform,
Siarhei Vishniakou3218fc02023-06-15 20:41:02 -07004371 args.downTime, args.eventTime, args.getPointerCount(),
4372 args.pointerProperties.data(), args.pointerCoords.data());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004373
4374 policyFlags |= POLICY_FLAG_FILTERED;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004375 if (!mPolicy.filterInputEvent(event, policyFlags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004376 return; // event was consumed by the filter
4377 }
4378
4379 mLock.lock();
4380 }
4381
4382 // Just enqueue a new motion event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004383 std::unique_ptr<MotionEntry> newEntry =
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004384 std::make_unique<MotionEntry>(args.id, args.eventTime, args.deviceId, args.source,
4385 args.displayId, policyFlags, args.action,
4386 args.actionButton, args.flags, args.metaState,
4387 args.buttonState, args.classification, args.edgeFlags,
4388 args.xPrecision, args.yPrecision,
4389 args.xCursorPosition, args.yCursorPosition,
Siarhei Vishniakou3218fc02023-06-15 20:41:02 -07004390 args.downTime, args.getPointerCount(),
4391 args.pointerProperties.data(),
4392 args.pointerCoords.data());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004393
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004394 if (args.id != android::os::IInputConstants::INVALID_INPUT_EVENT_ID &&
4395 IdGenerator::getSource(args.id) == IdGenerator::Source::INPUT_READER &&
Siarhei Vishniakou363e7292021-07-09 03:22:42 +00004396 !mInputFilterEnabled) {
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004397 const bool isDown = args.action == AMOTION_EVENT_ACTION_DOWN;
4398 mLatencyTracker.trackListener(args.id, isDown, args.eventTime, args.readTime);
Siarhei Vishniakou363e7292021-07-09 03:22:42 +00004399 }
4400
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004401 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004402 mLock.unlock();
4403 } // release lock
4404
4405 if (needWake) {
4406 mLooper->wake();
4407 }
4408}
4409
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004410void InputDispatcher::notifySensor(const NotifySensorArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004411 if (debugInboundEventDetails()) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004412 ALOGD("notifySensor - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=0x%x, "
4413 " sensorType=%s",
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004414 args.id, args.eventTime, args.deviceId, args.source,
4415 ftl::enum_string(args.sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004416 }
Chris Yef59a2f42020-10-16 12:55:26 -07004417
Antonio Kantekf16f2832021-09-28 04:39:20 +00004418 bool needWake = false;
Chris Yef59a2f42020-10-16 12:55:26 -07004419 { // acquire lock
4420 mLock.lock();
4421
4422 // Just enqueue a new sensor event.
4423 std::unique_ptr<SensorEntry> newEntry =
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004424 std::make_unique<SensorEntry>(args.id, args.eventTime, args.deviceId, args.source,
4425 /* policyFlags=*/0, args.hwTimestamp, args.sensorType,
4426 args.accuracy, args.accuracyChanged, args.values);
Chris Yef59a2f42020-10-16 12:55:26 -07004427
4428 needWake = enqueueInboundEventLocked(std::move(newEntry));
4429 mLock.unlock();
4430 } // release lock
4431
4432 if (needWake) {
4433 mLooper->wake();
4434 }
4435}
4436
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004437void InputDispatcher::notifyVibratorState(const NotifyVibratorStateArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004438 if (debugInboundEventDetails()) {
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004439 ALOGD("notifyVibratorState - eventTime=%" PRId64 ", device=%d, isOn=%d", args.eventTime,
4440 args.deviceId, args.isOn);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004441 }
Prabir Pradhana41d2442023-04-20 21:30:40 +00004442 mPolicy.notifyVibratorState(args.deviceId, args.isOn);
Chris Yefb552902021-02-03 17:18:37 -08004443}
4444
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004445bool InputDispatcher::shouldSendMotionToInputFilterLocked(const NotifyMotionArgs& args) {
Jackal Guof9696682018-10-05 12:23:23 +08004446 return mInputFilterEnabled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004447}
4448
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004449void InputDispatcher::notifySwitch(const NotifySwitchArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004450 if (debugInboundEventDetails()) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004451 ALOGD("notifySwitch - eventTime=%" PRId64 ", policyFlags=0x%x, switchValues=0x%08x, "
4452 "switchMask=0x%08x",
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004453 args.eventTime, args.policyFlags, args.switchValues, args.switchMask);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004454 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004455
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004456 uint32_t policyFlags = args.policyFlags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004457 policyFlags |= POLICY_FLAG_TRUSTED;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004458 mPolicy.notifySwitch(args.eventTime, args.switchValues, args.switchMask, policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004459}
4460
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004461void InputDispatcher::notifyDeviceReset(const NotifyDeviceResetArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004462 if (debugInboundEventDetails()) {
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004463 ALOGD("notifyDeviceReset - eventTime=%" PRId64 ", deviceId=%d", args.eventTime,
4464 args.deviceId);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004465 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004466
Antonio Kantekf16f2832021-09-28 04:39:20 +00004467 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004468 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004469 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004470
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004471 std::unique_ptr<DeviceResetEntry> newEntry =
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004472 std::make_unique<DeviceResetEntry>(args.id, args.eventTime, args.deviceId);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004473 needWake = enqueueInboundEventLocked(std::move(newEntry));
Siarhei Vishniakou1160ecd2023-06-28 15:57:47 -07004474
4475 for (auto& [_, verifier] : mVerifiersByDisplay) {
4476 verifier.resetDevice(args.deviceId);
4477 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004478 } // release lock
4479
4480 if (needWake) {
4481 mLooper->wake();
4482 }
4483}
4484
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004485void InputDispatcher::notifyPointerCaptureChanged(const NotifyPointerCaptureChangedArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004486 if (debugInboundEventDetails()) {
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004487 ALOGD("notifyPointerCaptureChanged - eventTime=%" PRId64 ", enabled=%s", args.eventTime,
4488 args.request.enable ? "true" : "false");
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004489 }
Prabir Pradhan7e186182020-11-10 13:56:45 -08004490
Antonio Kantekf16f2832021-09-28 04:39:20 +00004491 bool needWake = false;
Prabir Pradhan99987712020-11-10 18:43:05 -08004492 { // acquire lock
4493 std::scoped_lock _l(mLock);
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004494 auto entry =
4495 std::make_unique<PointerCaptureChangedEntry>(args.id, args.eventTime, args.request);
Prabir Pradhan99987712020-11-10 18:43:05 -08004496 needWake = enqueueInboundEventLocked(std::move(entry));
4497 } // release lock
4498
4499 if (needWake) {
4500 mLooper->wake();
4501 }
Prabir Pradhan7e186182020-11-10 13:56:45 -08004502}
4503
Prabir Pradhan5735a322022-04-11 17:23:34 +00004504InputEventInjectionResult InputDispatcher::injectInputEvent(const InputEvent* event,
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00004505 std::optional<gui::Uid> targetUid,
Prabir Pradhan5735a322022-04-11 17:23:34 +00004506 InputEventInjectionSync syncMode,
4507 std::chrono::milliseconds timeout,
4508 uint32_t policyFlags) {
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004509 Result<void> eventValidation = validateInputEvent(*event);
4510 if (!eventValidation.ok()) {
4511 LOG(INFO) << "Injection failed: invalid event: " << eventValidation.error();
4512 return InputEventInjectionResult::FAILED;
4513 }
4514
Prabir Pradhan65613802023-02-22 23:36:58 +00004515 if (debugInboundEventDetails()) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07004516 LOG(INFO) << __func__ << ": targetUid=" << toString(targetUid, &uidString)
4517 << ", syncMode=" << ftl::enum_string(syncMode) << ", timeout=" << timeout.count()
4518 << "ms, policyFlags=0x" << std::hex << policyFlags << std::dec
4519 << ", event=" << *event;
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004520 }
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07004521 nsecs_t endTime = now() + std::chrono::duration_cast<std::chrono::nanoseconds>(timeout).count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004522
Prabir Pradhan5735a322022-04-11 17:23:34 +00004523 policyFlags |= POLICY_FLAG_INJECTED | POLICY_FLAG_TRUSTED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004524
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004525 // For all injected events, set device id = VIRTUAL_KEYBOARD_ID. The only exception is events
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004526 // that have gone through the InputFilter. If the event passed through the InputFilter, assign
4527 // the provided device id. If the InputFilter is accessibility, and it modifies or synthesizes
4528 // the injected event, it is responsible for setting POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY.
4529 // For those events, we will set FLAG_IS_ACCESSIBILITY_EVENT to allow apps to distinguish them
4530 // from events that originate from actual hardware.
Siarhei Vishniakouf4043212023-09-18 19:33:03 -07004531 DeviceId resolvedDeviceId = VIRTUAL_KEYBOARD_ID;
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004532 if (policyFlags & POLICY_FLAG_FILTERED) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004533 resolvedDeviceId = event->getDeviceId();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004534 }
4535
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004536 std::queue<std::unique_ptr<EventEntry>> injectedEntries;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004537 switch (event->getType()) {
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004538 case InputEventType::KEY: {
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004539 const KeyEvent& incomingKey = static_cast<const KeyEvent&>(*event);
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004540 const int32_t action = incomingKey.getAction();
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004541 int32_t flags = incomingKey.getFlags();
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004542 if (policyFlags & POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY) {
4543 flags |= AKEY_EVENT_FLAG_IS_ACCESSIBILITY_EVENT;
4544 }
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004545 int32_t keyCode = incomingKey.getKeyCode();
4546 int32_t metaState = incomingKey.getMetaState();
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004547 KeyEvent keyEvent;
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004548 keyEvent.initialize(incomingKey.getId(), resolvedDeviceId, incomingKey.getSource(),
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004549 incomingKey.getDisplayId(), INVALID_HMAC, action, flags, keyCode,
4550 incomingKey.getScanCode(), metaState, incomingKey.getRepeatCount(),
4551 incomingKey.getDownTime(), incomingKey.getEventTime());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004552
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004553 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
4554 policyFlags |= POLICY_FLAG_VIRTUAL;
Michael Wright2b3c3302018-03-02 17:19:13 +00004555 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004556
4557 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
4558 android::base::Timer t;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004559 mPolicy.interceptKeyBeforeQueueing(keyEvent, /*byref*/ policyFlags);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004560 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4561 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
4562 std::to_string(t.duration().count()).c_str());
4563 }
4564 }
4565
4566 mLock.lock();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004567 std::unique_ptr<KeyEntry> injectedEntry =
4568 std::make_unique<KeyEntry>(incomingKey.getId(), incomingKey.getEventTime(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004569 resolvedDeviceId, incomingKey.getSource(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004570 incomingKey.getDisplayId(), policyFlags, action,
4571 flags, keyCode, incomingKey.getScanCode(), metaState,
4572 incomingKey.getRepeatCount(),
4573 incomingKey.getDownTime());
4574 injectedEntries.push(std::move(injectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004575 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004576 }
4577
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004578 case InputEventType::MOTION: {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004579 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(*event);
Prabir Pradhanaa561d12021-09-24 06:57:33 -07004580 const bool isPointerEvent =
4581 isFromSource(event->getSource(), AINPUT_SOURCE_CLASS_POINTER);
4582 // If a pointer event has no displayId specified, inject it to the default display.
4583 const uint32_t displayId = isPointerEvent && (event->getDisplayId() == ADISPLAY_ID_NONE)
4584 ? ADISPLAY_ID_DEFAULT
4585 : event->getDisplayId();
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004586 int32_t flags = motionEvent.getFlags();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004587
4588 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004589 nsecs_t eventTime = motionEvent.getEventTime();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004590 android::base::Timer t;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004591 mPolicy.interceptMotionBeforeQueueing(displayId, eventTime, /*byref*/ policyFlags);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004592 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4593 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
4594 std::to_string(t.duration().count()).c_str());
4595 }
4596 }
4597
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004598 if (policyFlags & POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY) {
4599 flags |= AMOTION_EVENT_FLAG_IS_ACCESSIBILITY_EVENT;
4600 }
4601
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004602 mLock.lock();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004603 const nsecs_t* sampleEventTimes = motionEvent.getSampleEventTimes();
4604 const PointerCoords* samplePointerCoords = motionEvent.getSamplePointerCoords();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004605 std::unique_ptr<MotionEntry> injectedEntry =
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004606 std::make_unique<MotionEntry>(motionEvent.getId(), *sampleEventTimes,
4607 resolvedDeviceId, motionEvent.getSource(),
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004608 displayId, policyFlags, motionEvent.getAction(),
4609 motionEvent.getActionButton(), flags,
4610 motionEvent.getMetaState(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004611 motionEvent.getButtonState(),
4612 motionEvent.getClassification(),
4613 motionEvent.getEdgeFlags(),
4614 motionEvent.getXPrecision(),
4615 motionEvent.getYPrecision(),
4616 motionEvent.getRawXCursorPosition(),
4617 motionEvent.getRawYCursorPosition(),
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004618 motionEvent.getDownTime(),
4619 motionEvent.getPointerCount(),
4620 motionEvent.getPointerProperties(),
4621 samplePointerCoords);
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004622 transformMotionEntryForInjectionLocked(*injectedEntry, motionEvent.getTransform());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004623 injectedEntries.push(std::move(injectedEntry));
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004624 for (size_t i = motionEvent.getHistorySize(); i > 0; i--) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004625 sampleEventTimes += 1;
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004626 samplePointerCoords += motionEvent.getPointerCount();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004627 std::unique_ptr<MotionEntry> nextInjectedEntry =
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004628 std::make_unique<MotionEntry>(motionEvent.getId(), *sampleEventTimes,
4629 resolvedDeviceId, motionEvent.getSource(),
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004630 displayId, policyFlags,
4631 motionEvent.getAction(),
4632 motionEvent.getActionButton(), flags,
4633 motionEvent.getMetaState(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004634 motionEvent.getButtonState(),
4635 motionEvent.getClassification(),
4636 motionEvent.getEdgeFlags(),
4637 motionEvent.getXPrecision(),
4638 motionEvent.getYPrecision(),
4639 motionEvent.getRawXCursorPosition(),
4640 motionEvent.getRawYCursorPosition(),
4641 motionEvent.getDownTime(),
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004642 motionEvent.getPointerCount(),
4643 motionEvent.getPointerProperties(),
Prabir Pradhan5beda762021-12-10 09:30:08 +00004644 samplePointerCoords);
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004645 transformMotionEntryForInjectionLocked(*nextInjectedEntry,
4646 motionEvent.getTransform());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004647 injectedEntries.push(std::move(nextInjectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004648 }
4649 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004650 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004651
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004652 default:
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004653 LOG(WARNING) << "Cannot inject " << ftl::enum_string(event->getType()) << " events";
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004654 return InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004655 }
4656
Prabir Pradhan5735a322022-04-11 17:23:34 +00004657 InjectionState* injectionState = new InjectionState(targetUid);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004658 if (syncMode == InputEventInjectionSync::NONE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004659 injectionState->injectionIsAsync = true;
4660 }
4661
4662 injectionState->refCount += 1;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004663 injectedEntries.back()->injectionState = injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004664
4665 bool needWake = false;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004666 while (!injectedEntries.empty()) {
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08004667 if (DEBUG_INJECTION) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07004668 LOG(INFO) << "Injecting " << injectedEntries.front()->getDescription();
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08004669 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004670 needWake |= enqueueInboundEventLocked(std::move(injectedEntries.front()));
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004671 injectedEntries.pop();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004672 }
4673
4674 mLock.unlock();
4675
4676 if (needWake) {
4677 mLooper->wake();
4678 }
4679
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004680 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004681 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004682 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004683
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004684 if (syncMode == InputEventInjectionSync::NONE) {
4685 injectionResult = InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004686 } else {
4687 for (;;) {
4688 injectionResult = injectionState->injectionResult;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004689 if (injectionResult != InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004690 break;
4691 }
4692
4693 nsecs_t remainingTimeout = endTime - now();
4694 if (remainingTimeout <= 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004695 if (DEBUG_INJECTION) {
4696 ALOGD("injectInputEvent - Timed out waiting for injection result "
4697 "to become available.");
4698 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004699 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004700 break;
4701 }
4702
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004703 mInjectionResultAvailable.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004704 }
4705
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004706 if (injectionResult == InputEventInjectionResult::SUCCEEDED &&
4707 syncMode == InputEventInjectionSync::WAIT_FOR_FINISHED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004708 while (injectionState->pendingForegroundDispatches != 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004709 if (DEBUG_INJECTION) {
4710 ALOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
4711 injectionState->pendingForegroundDispatches);
4712 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004713 nsecs_t remainingTimeout = endTime - now();
4714 if (remainingTimeout <= 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004715 if (DEBUG_INJECTION) {
4716 ALOGD("injectInputEvent - Timed out waiting for pending foreground "
4717 "dispatches to finish.");
4718 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004719 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004720 break;
4721 }
4722
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004723 mInjectionSyncFinished.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004724 }
4725 }
4726 }
4727
4728 injectionState->release();
4729 } // release lock
4730
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004731 if (DEBUG_INJECTION) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07004732 LOG(INFO) << "injectInputEvent - Finished with result "
4733 << ftl::enum_string(injectionResult);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004734 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004735
4736 return injectionResult;
4737}
4738
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004739std::unique_ptr<VerifiedInputEvent> InputDispatcher::verifyInputEvent(const InputEvent& event) {
Gang Wange9087892020-01-07 12:17:14 -05004740 std::array<uint8_t, 32> calculatedHmac;
4741 std::unique_ptr<VerifiedInputEvent> result;
4742 switch (event.getType()) {
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004743 case InputEventType::KEY: {
Gang Wange9087892020-01-07 12:17:14 -05004744 const KeyEvent& keyEvent = static_cast<const KeyEvent&>(event);
4745 VerifiedKeyEvent verifiedKeyEvent = verifiedKeyEventFromKeyEvent(keyEvent);
4746 result = std::make_unique<VerifiedKeyEvent>(verifiedKeyEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004747 calculatedHmac = sign(verifiedKeyEvent);
Gang Wange9087892020-01-07 12:17:14 -05004748 break;
4749 }
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004750 case InputEventType::MOTION: {
Gang Wange9087892020-01-07 12:17:14 -05004751 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(event);
4752 VerifiedMotionEvent verifiedMotionEvent =
4753 verifiedMotionEventFromMotionEvent(motionEvent);
4754 result = std::make_unique<VerifiedMotionEvent>(verifiedMotionEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004755 calculatedHmac = sign(verifiedMotionEvent);
Gang Wange9087892020-01-07 12:17:14 -05004756 break;
4757 }
4758 default: {
4759 ALOGE("Cannot verify events of type %" PRId32, event.getType());
4760 return nullptr;
4761 }
4762 }
4763 if (calculatedHmac == INVALID_HMAC) {
4764 return nullptr;
4765 }
tyiu1573a672023-02-21 22:38:32 +00004766 if (0 != CRYPTO_memcmp(calculatedHmac.data(), event.getHmac().data(), calculatedHmac.size())) {
Gang Wange9087892020-01-07 12:17:14 -05004767 return nullptr;
4768 }
4769 return result;
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004770}
4771
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004772void InputDispatcher::setInjectionResult(EventEntry& entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004773 InputEventInjectionResult injectionResult) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004774 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004775 if (injectionState) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004776 if (DEBUG_INJECTION) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07004777 LOG(INFO) << "Setting input event injection result to "
4778 << ftl::enum_string(injectionResult);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004779 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004780
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004781 if (injectionState->injectionIsAsync && !(entry.policyFlags & POLICY_FLAG_FILTERED)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004782 // Log the outcome since the injector did not wait for the injection result.
4783 switch (injectionResult) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004784 case InputEventInjectionResult::SUCCEEDED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004785 ALOGV("Asynchronous input event injection succeeded.");
4786 break;
Prabir Pradhan5735a322022-04-11 17:23:34 +00004787 case InputEventInjectionResult::TARGET_MISMATCH:
4788 ALOGV("Asynchronous input event injection target mismatch.");
4789 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004790 case InputEventInjectionResult::FAILED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004791 ALOGW("Asynchronous input event injection failed.");
4792 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004793 case InputEventInjectionResult::TIMED_OUT:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004794 ALOGW("Asynchronous input event injection timed out.");
4795 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004796 case InputEventInjectionResult::PENDING:
4797 ALOGE("Setting result to 'PENDING' for asynchronous injection");
4798 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004799 }
4800 }
4801
4802 injectionState->injectionResult = injectionResult;
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004803 mInjectionResultAvailable.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004804 }
4805}
4806
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004807void InputDispatcher::transformMotionEntryForInjectionLocked(
4808 MotionEntry& entry, const ui::Transform& injectedTransform) const {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004809 // Input injection works in the logical display coordinate space, but the input pipeline works
4810 // display space, so we need to transform the injected events accordingly.
4811 const auto it = mDisplayInfos.find(entry.displayId);
4812 if (it == mDisplayInfos.end()) return;
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004813 const auto& transformToDisplay = it->second.transform.inverse() * injectedTransform;
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004814
Prabir Pradhand9a2ebe2022-07-20 19:25:13 +00004815 if (entry.xCursorPosition != AMOTION_EVENT_INVALID_CURSOR_POSITION &&
4816 entry.yCursorPosition != AMOTION_EVENT_INVALID_CURSOR_POSITION) {
4817 const vec2 cursor =
4818 MotionEvent::calculateTransformedXY(entry.source, transformToDisplay,
4819 {entry.xCursorPosition, entry.yCursorPosition});
4820 entry.xCursorPosition = cursor.x;
4821 entry.yCursorPosition = cursor.y;
4822 }
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004823 for (uint32_t i = 0; i < entry.pointerCount; i++) {
Prabir Pradhan8e6ce222022-02-24 09:08:54 -08004824 entry.pointerCoords[i] =
4825 MotionEvent::calculateTransformedCoords(entry.source, transformToDisplay,
4826 entry.pointerCoords[i]);
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004827 }
4828}
4829
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004830void InputDispatcher::incrementPendingForegroundDispatches(EventEntry& entry) {
4831 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004832 if (injectionState) {
4833 injectionState->pendingForegroundDispatches += 1;
4834 }
4835}
4836
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004837void InputDispatcher::decrementPendingForegroundDispatches(EventEntry& entry) {
4838 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004839 if (injectionState) {
4840 injectionState->pendingForegroundDispatches -= 1;
4841
4842 if (injectionState->pendingForegroundDispatches == 0) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004843 mInjectionSyncFinished.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004844 }
4845 }
4846}
4847
chaviw98318de2021-05-19 16:45:23 -05004848const std::vector<sp<WindowInfoHandle>>& InputDispatcher::getWindowHandlesLocked(
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004849 int32_t displayId) const {
chaviw98318de2021-05-19 16:45:23 -05004850 static const std::vector<sp<WindowInfoHandle>> EMPTY_WINDOW_HANDLES;
Vishnu Nairad321cd2020-08-20 16:40:21 -07004851 auto it = mWindowHandlesByDisplay.find(displayId);
4852 return it != mWindowHandlesByDisplay.end() ? it->second : EMPTY_WINDOW_HANDLES;
Arthur Hungb92218b2018-08-14 12:00:21 +08004853}
4854
chaviw98318de2021-05-19 16:45:23 -05004855sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(
chaviwfbe5d9c2018-12-26 12:23:37 -08004856 const sp<IBinder>& windowHandleToken) const {
arthurhungbe737672020-06-24 12:29:21 +08004857 if (windowHandleToken == nullptr) {
4858 return nullptr;
4859 }
4860
Arthur Hungb92218b2018-08-14 12:00:21 +08004861 for (auto& it : mWindowHandlesByDisplay) {
chaviw98318de2021-05-19 16:45:23 -05004862 const std::vector<sp<WindowInfoHandle>>& windowHandles = it.second;
4863 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
chaviwfbe5d9c2018-12-26 12:23:37 -08004864 if (windowHandle->getToken() == windowHandleToken) {
Arthur Hungb92218b2018-08-14 12:00:21 +08004865 return windowHandle;
4866 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004867 }
4868 }
Yi Kong9b14ac62018-07-17 13:48:38 -07004869 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004870}
4871
chaviw98318de2021-05-19 16:45:23 -05004872sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(const sp<IBinder>& windowHandleToken,
4873 int displayId) const {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004874 if (windowHandleToken == nullptr) {
4875 return nullptr;
4876 }
4877
chaviw98318de2021-05-19 16:45:23 -05004878 for (const sp<WindowInfoHandle>& windowHandle : getWindowHandlesLocked(displayId)) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004879 if (windowHandle->getToken() == windowHandleToken) {
4880 return windowHandle;
4881 }
4882 }
4883 return nullptr;
4884}
4885
chaviw98318de2021-05-19 16:45:23 -05004886sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(
4887 const sp<WindowInfoHandle>& windowHandle) const {
Mady Mellor017bcd12020-06-23 19:12:00 +00004888 for (auto& it : mWindowHandlesByDisplay) {
chaviw98318de2021-05-19 16:45:23 -05004889 const std::vector<sp<WindowInfoHandle>>& windowHandles = it.second;
4890 for (const sp<WindowInfoHandle>& handle : windowHandles) {
arthurhungbe737672020-06-24 12:29:21 +08004891 if (handle->getId() == windowHandle->getId() &&
4892 handle->getToken() == windowHandle->getToken()) {
Mady Mellor017bcd12020-06-23 19:12:00 +00004893 if (windowHandle->getInfo()->displayId != it.first) {
4894 ALOGE("Found window %s in display %" PRId32
4895 ", but it should belong to display %" PRId32,
4896 windowHandle->getName().c_str(), it.first,
4897 windowHandle->getInfo()->displayId);
4898 }
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004899 return handle;
Arthur Hungb92218b2018-08-14 12:00:21 +08004900 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004901 }
4902 }
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004903 return nullptr;
4904}
4905
chaviw98318de2021-05-19 16:45:23 -05004906sp<WindowInfoHandle> InputDispatcher::getFocusedWindowHandleLocked(int displayId) const {
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004907 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(displayId);
4908 return getWindowHandleLocked(focusedToken, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004909}
4910
Prabir Pradhan33e3baa2022-12-06 20:30:22 +00004911ui::Transform InputDispatcher::getTransformLocked(int32_t displayId) const {
4912 auto displayInfoIt = mDisplayInfos.find(displayId);
4913 return displayInfoIt != mDisplayInfos.end() ? displayInfoIt->second.transform
4914 : kIdentityTransform;
4915}
4916
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004917bool InputDispatcher::canWindowReceiveMotionLocked(const sp<WindowInfoHandle>& window,
4918 const MotionEntry& motionEntry) const {
4919 const WindowInfo& info = *window->getInfo();
4920
4921 // Skip spy window targets that are not valid for targeted injection.
4922 if (const auto err = verifyTargetedInjection(window, motionEntry); err) {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004923 return false;
4924 }
4925
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004926 if (info.inputConfig.test(WindowInfo::InputConfig::PAUSE_DISPATCHING)) {
4927 ALOGI("Not sending touch event to %s because it is paused", window->getName().c_str());
4928 return false;
4929 }
4930
4931 if (info.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL)) {
4932 ALOGW("Not sending touch gesture to %s because it has config NO_INPUT_CHANNEL",
4933 window->getName().c_str());
4934 return false;
4935 }
4936
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07004937 std::shared_ptr<Connection> connection = getConnectionLocked(window->getToken());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004938 if (connection == nullptr) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004939 ALOGW("Not sending touch to %s because there's no corresponding connection",
4940 window->getName().c_str());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004941 return false;
4942 }
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004943
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004944 if (!connection->responsive) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004945 ALOGW("Not sending touch to %s because it is not responsive", window->getName().c_str());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004946 return false;
4947 }
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004948
4949 // Drop events that can't be trusted due to occlusion
4950 const auto [x, y] = resolveTouchedPosition(motionEntry);
4951 TouchOcclusionInfo occlusionInfo = computeTouchOcclusionInfoLocked(window, x, y);
4952 if (!isTouchTrustedLocked(occlusionInfo)) {
4953 if (DEBUG_TOUCH_OCCLUSION) {
Prabir Pradhan82e081e2022-12-06 09:50:09 +00004954 ALOGD("Stack of obscuring windows during untrusted touch (%.1f, %.1f):", x, y);
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004955 for (const auto& log : occlusionInfo.debugInfo) {
4956 ALOGD("%s", log.c_str());
4957 }
4958 }
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00004959 ALOGW("Dropping untrusted touch event due to %s/%s", occlusionInfo.obscuringPackage.c_str(),
4960 occlusionInfo.obscuringUid.toString().c_str());
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004961 return false;
4962 }
4963
4964 // Drop touch events if requested by input feature
4965 if (shouldDropInput(motionEntry, window)) {
4966 return false;
4967 }
4968
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004969 return true;
4970}
4971
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004972std::shared_ptr<InputChannel> InputDispatcher::getInputChannelLocked(
4973 const sp<IBinder>& token) const {
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00004974 auto connectionIt = mConnectionsByToken.find(token);
4975 if (connectionIt == mConnectionsByToken.end()) {
Robert Carr5c8a0262018-10-03 16:30:44 -07004976 return nullptr;
4977 }
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00004978 return connectionIt->second->inputChannel;
Robert Carr5c8a0262018-10-03 16:30:44 -07004979}
4980
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004981void InputDispatcher::updateWindowHandlesForDisplayLocked(
chaviw98318de2021-05-19 16:45:23 -05004982 const std::vector<sp<WindowInfoHandle>>& windowInfoHandles, int32_t displayId) {
4983 if (windowInfoHandles.empty()) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004984 // Remove all handles on a display if there are no windows left.
4985 mWindowHandlesByDisplay.erase(displayId);
4986 return;
4987 }
4988
4989 // Since we compare the pointer of input window handles across window updates, we need
4990 // to make sure the handle object for the same window stays unchanged across updates.
chaviw98318de2021-05-19 16:45:23 -05004991 const std::vector<sp<WindowInfoHandle>>& oldHandles = getWindowHandlesLocked(displayId);
4992 std::unordered_map<int32_t /*id*/, sp<WindowInfoHandle>> oldHandlesById;
4993 for (const sp<WindowInfoHandle>& handle : oldHandles) {
chaviwaf87b3e2019-10-01 16:59:28 -07004994 oldHandlesById[handle->getId()] = handle;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004995 }
4996
chaviw98318de2021-05-19 16:45:23 -05004997 std::vector<sp<WindowInfoHandle>> newHandles;
4998 for (const sp<WindowInfoHandle>& handle : windowInfoHandles) {
chaviw98318de2021-05-19 16:45:23 -05004999 const WindowInfo* info = handle->getInfo();
Siarhei Vishniakou64452932020-11-06 17:51:32 -06005000 if (getInputChannelLocked(handle->getToken()) == nullptr) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005001 const bool noInputChannel =
Prabir Pradhan51e7db02022-02-07 06:02:57 -08005002 info->inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005003 const bool canReceiveInput =
5004 !info->inputConfig.test(WindowInfo::InputConfig::NOT_TOUCHABLE) ||
5005 !info->inputConfig.test(WindowInfo::InputConfig::NOT_FOCUSABLE);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005006 if (canReceiveInput && !noInputChannel) {
John Recke0710582019-09-26 13:46:12 -07005007 ALOGV("Window handle %s has no registered input channel",
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005008 handle->getName().c_str());
Robert Carr2984b7a2020-04-13 17:06:45 -07005009 continue;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005010 }
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005011 }
5012
5013 if (info->displayId != displayId) {
5014 ALOGE("Window %s updated by wrong display %d, should belong to display %d",
5015 handle->getName().c_str(), displayId, info->displayId);
5016 continue;
5017 }
5018
Robert Carredd13602020-04-13 17:24:34 -07005019 if ((oldHandlesById.find(handle->getId()) != oldHandlesById.end()) &&
5020 (oldHandlesById.at(handle->getId())->getToken() == handle->getToken())) {
chaviw98318de2021-05-19 16:45:23 -05005021 const sp<WindowInfoHandle>& oldHandle = oldHandlesById.at(handle->getId());
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005022 oldHandle->updateFrom(handle);
5023 newHandles.push_back(oldHandle);
5024 } else {
5025 newHandles.push_back(handle);
5026 }
5027 }
5028
5029 // Insert or replace
5030 mWindowHandlesByDisplay[displayId] = newHandles;
5031}
5032
Arthur Hungb92218b2018-08-14 12:00:21 +08005033/**
5034 * Called from InputManagerService, update window handle list by displayId that can receive input.
5035 * A window handle contains information about InputChannel, Touch Region, Types, Focused,...
5036 * If set an empty list, remove all handles from the specific display.
5037 * For focused handle, check if need to change and send a cancel event to previous one.
5038 * For removed handle, check if need to send a cancel event if already in touch.
5039 */
Arthur Hung72d8dc32020-03-28 00:48:39 +00005040void InputDispatcher::setInputWindowsLocked(
chaviw98318de2021-05-19 16:45:23 -05005041 const std::vector<sp<WindowInfoHandle>>& windowInfoHandles, int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005042 if (DEBUG_FOCUS) {
5043 std::string windowList;
chaviw98318de2021-05-19 16:45:23 -05005044 for (const sp<WindowInfoHandle>& iwh : windowInfoHandles) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005045 windowList += iwh->getName() + " ";
5046 }
5047 ALOGD("setInputWindows displayId=%" PRId32 " %s", displayId, windowList.c_str());
5048 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005049
Prabir Pradhand65552b2021-10-07 11:23:50 -07005050 // Check preconditions for new input windows
chaviw98318de2021-05-19 16:45:23 -05005051 for (const sp<WindowInfoHandle>& window : windowInfoHandles) {
Prabir Pradhand65552b2021-10-07 11:23:50 -07005052 const WindowInfo& info = *window->getInfo();
5053
5054 // Ensure all tokens are null if the window has feature NO_INPUT_CHANNEL
Prabir Pradhan51e7db02022-02-07 06:02:57 -08005055 const bool noInputWindow = info.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005056 if (noInputWindow && window->getToken() != nullptr) {
5057 ALOGE("%s has feature NO_INPUT_WINDOW, but a non-null token. Clearing",
5058 window->getName().c_str());
5059 window->releaseChannel();
5060 }
Prabir Pradhand65552b2021-10-07 11:23:50 -07005061
Prabir Pradhan5c85e052021-12-22 02:27:12 -08005062 // Ensure all spy windows are trusted overlays
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005063 LOG_ALWAYS_FATAL_IF(info.isSpy() &&
5064 !info.inputConfig.test(
5065 WindowInfo::InputConfig::TRUSTED_OVERLAY),
Prabir Pradhan5c85e052021-12-22 02:27:12 -08005066 "%s has feature SPY, but is not a trusted overlay.",
5067 window->getName().c_str());
5068
Prabir Pradhand65552b2021-10-07 11:23:50 -07005069 // Ensure all stylus interceptors are trusted overlays
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005070 LOG_ALWAYS_FATAL_IF(info.interceptsStylus() &&
5071 !info.inputConfig.test(
5072 WindowInfo::InputConfig::TRUSTED_OVERLAY),
Prabir Pradhand65552b2021-10-07 11:23:50 -07005073 "%s has feature INTERCEPTS_STYLUS, but is not a trusted overlay.",
5074 window->getName().c_str());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005075 }
5076
Arthur Hung72d8dc32020-03-28 00:48:39 +00005077 // Copy old handles for release if they are no longer present.
chaviw98318de2021-05-19 16:45:23 -05005078 const std::vector<sp<WindowInfoHandle>> oldWindowHandles = getWindowHandlesLocked(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005079
chaviw98318de2021-05-19 16:45:23 -05005080 updateWindowHandlesForDisplayLocked(windowInfoHandles, displayId);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005081
chaviw98318de2021-05-19 16:45:23 -05005082 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Arthur Hung72d8dc32020-03-28 00:48:39 +00005083
Vishnu Nairc519ff72021-01-21 08:23:08 -08005084 std::optional<FocusResolver::FocusChanges> changes =
5085 mFocusResolver.setInputWindows(displayId, windowHandles);
5086 if (changes) {
5087 onFocusChangedLocked(*changes);
Arthur Hung72d8dc32020-03-28 00:48:39 +00005088 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005089
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005090 std::unordered_map<int32_t, TouchState>::iterator stateIt =
5091 mTouchStatesByDisplay.find(displayId);
5092 if (stateIt != mTouchStatesByDisplay.end()) {
5093 TouchState& state = stateIt->second;
Arthur Hung72d8dc32020-03-28 00:48:39 +00005094 for (size_t i = 0; i < state.windows.size();) {
5095 TouchedWindow& touchedWindow = state.windows[i];
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07005096 if (getWindowHandleLocked(touchedWindow.windowHandle) == nullptr) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005097 if (DEBUG_FOCUS) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00005098 ALOGD("Touched window was removed: %s in display %" PRId32,
5099 touchedWindow.windowHandle->getName().c_str(), displayId);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005100 }
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005101 std::shared_ptr<InputChannel> touchedInputChannel =
Arthur Hung72d8dc32020-03-28 00:48:39 +00005102 getInputChannelLocked(touchedWindow.windowHandle->getToken());
5103 if (touchedInputChannel != nullptr) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00005104 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
Arthur Hung72d8dc32020-03-28 00:48:39 +00005105 "touched window was removed");
5106 synthesizeCancelationEventsForInputChannelLocked(touchedInputChannel, options);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00005107 // Since we are about to drop the touch, cancel the events for the wallpaper as
5108 // well.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005109 if (touchedWindow.targetFlags.test(InputTarget::Flags::FOREGROUND) &&
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005110 touchedWindow.windowHandle->getInfo()->inputConfig.test(
5111 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER)) {
Siarhei Vishniakouca205502021-07-16 21:31:58 +00005112 sp<WindowInfoHandle> wallpaper = state.getWallpaperWindow();
Arthur Hungc539dbb2022-12-08 07:45:36 +00005113 synthesizeCancelationEventsForWindowLocked(wallpaper, options);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00005114 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005115 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00005116 state.windows.erase(state.windows.begin() + i);
5117 } else {
5118 ++i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005119 }
5120 }
arthurhungb89ccb02020-12-30 16:19:01 +08005121
arthurhung6d4bed92021-03-17 11:59:33 +08005122 // If drag window is gone, it would receive a cancel event and broadcast the DRAG_END. We
arthurhungb89ccb02020-12-30 16:19:01 +08005123 // could just clear the state here.
Arthur Hung3915c1f2022-05-31 07:17:17 +00005124 if (mDragState && mDragState->dragWindow->getInfo()->displayId == displayId &&
arthurhung6d4bed92021-03-17 11:59:33 +08005125 std::find(windowHandles.begin(), windowHandles.end(), mDragState->dragWindow) ==
arthurhungb89ccb02020-12-30 16:19:01 +08005126 windowHandles.end()) {
Arthur Hung3915c1f2022-05-31 07:17:17 +00005127 ALOGI("Drag window went away: %s", mDragState->dragWindow->getName().c_str());
5128 sendDropWindowCommandLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08005129 mDragState.reset();
arthurhungb89ccb02020-12-30 16:19:01 +08005130 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00005131 }
Arthur Hung25e2af12020-03-26 12:58:37 +00005132
Arthur Hung72d8dc32020-03-28 00:48:39 +00005133 // Release information for windows that are no longer present.
5134 // This ensures that unused input channels are released promptly.
5135 // Otherwise, they might stick around until the window handle is destroyed
5136 // which might not happen until the next GC.
chaviw98318de2021-05-19 16:45:23 -05005137 for (const sp<WindowInfoHandle>& oldWindowHandle : oldWindowHandles) {
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07005138 if (getWindowHandleLocked(oldWindowHandle) == nullptr) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00005139 if (DEBUG_FOCUS) {
5140 ALOGD("Window went away: %s", oldWindowHandle->getName().c_str());
Arthur Hung25e2af12020-03-26 12:58:37 +00005141 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00005142 oldWindowHandle->releaseChannel();
Arthur Hung25e2af12020-03-26 12:58:37 +00005143 }
chaviw291d88a2019-02-14 10:33:58 -08005144 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005145}
5146
5147void InputDispatcher::setFocusedApplication(
Chris Yea209fde2020-07-22 13:54:51 -07005148 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005149 if (DEBUG_FOCUS) {
5150 ALOGD("setFocusedApplication displayId=%" PRId32 " %s", displayId,
5151 inputApplicationHandle ? inputApplicationHandle->getName().c_str() : "<nullptr>");
5152 }
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05005153 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005154 std::scoped_lock _l(mLock);
Vishnu Nair599f1412021-06-21 10:39:58 -07005155 setFocusedApplicationLocked(displayId, inputApplicationHandle);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005156 } // release lock
5157
5158 // Wake up poll loop since it may need to make new input dispatching choices.
5159 mLooper->wake();
5160}
5161
Vishnu Nair599f1412021-06-21 10:39:58 -07005162void InputDispatcher::setFocusedApplicationLocked(
5163 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
5164 std::shared_ptr<InputApplicationHandle> oldFocusedApplicationHandle =
5165 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
5166
5167 if (sharedPointersEqual(oldFocusedApplicationHandle, inputApplicationHandle)) {
5168 return; // This application is already focused. No need to wake up or change anything.
5169 }
5170
5171 // Set the new application handle.
5172 if (inputApplicationHandle != nullptr) {
5173 mFocusedApplicationHandlesByDisplay[displayId] = inputApplicationHandle;
5174 } else {
5175 mFocusedApplicationHandlesByDisplay.erase(displayId);
5176 }
5177
5178 // No matter what the old focused application was, stop waiting on it because it is
5179 // no longer focused.
5180 resetNoFocusedWindowTimeoutLocked();
5181}
5182
Tiger Huang721e26f2018-07-24 22:26:19 +08005183/**
5184 * Sets the focused display, which is responsible for receiving focus-dispatched input events where
5185 * the display not specified.
5186 *
5187 * We track any unreleased events for each window. If a window loses the ability to receive the
5188 * released event, we will send a cancel event to it. So when the focused display is changed, we
5189 * cancel all the unreleased display-unspecified events for the focused window on the old focused
5190 * display. The display-specified events won't be affected.
5191 */
5192void InputDispatcher::setFocusedDisplay(int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005193 if (DEBUG_FOCUS) {
5194 ALOGD("setFocusedDisplay displayId=%" PRId32, displayId);
5195 }
Tiger Huang721e26f2018-07-24 22:26:19 +08005196 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005197 std::scoped_lock _l(mLock);
Tiger Huang721e26f2018-07-24 22:26:19 +08005198
5199 if (mFocusedDisplayId != displayId) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07005200 sp<IBinder> oldFocusedWindowToken =
Vishnu Nairc519ff72021-01-21 08:23:08 -08005201 mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07005202 if (oldFocusedWindowToken != nullptr) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005203 std::shared_ptr<InputChannel> inputChannel =
Vishnu Nairad321cd2020-08-20 16:40:21 -07005204 getInputChannelLocked(oldFocusedWindowToken);
Tiger Huang721e26f2018-07-24 22:26:19 +08005205 if (inputChannel != nullptr) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005206 CancelationOptions
Michael Wrightfb04fd52022-11-24 22:31:11 +00005207 options(CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005208 "The display which contains this window no longer has focus.");
Michael Wright3dd60e22019-03-27 22:06:44 +00005209 options.displayId = ADISPLAY_ID_NONE;
Tiger Huang721e26f2018-07-24 22:26:19 +08005210 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
5211 }
5212 }
5213 mFocusedDisplayId = displayId;
5214
Chris Ye3c2d6f52020-08-09 10:39:48 -07005215 // Find new focused window and validate
Vishnu Nairc519ff72021-01-21 08:23:08 -08005216 sp<IBinder> newFocusedWindowToken = mFocusResolver.getFocusedWindowToken(displayId);
Prabir Pradhancef936d2021-07-21 16:17:52 +00005217 sendFocusChangedCommandLocked(oldFocusedWindowToken, newFocusedWindowToken);
Robert Carrf759f162018-11-13 12:57:11 -08005218
Vishnu Nairad321cd2020-08-20 16:40:21 -07005219 if (newFocusedWindowToken == nullptr) {
Tiger Huang721e26f2018-07-24 22:26:19 +08005220 ALOGW("Focused display #%" PRId32 " does not have a focused window.", displayId);
Vishnu Nairc519ff72021-01-21 08:23:08 -08005221 if (mFocusResolver.hasFocusedWindowTokens()) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07005222 ALOGE("But another display has a focused window\n%s",
Vishnu Nairc519ff72021-01-21 08:23:08 -08005223 mFocusResolver.dumpFocusedWindows().c_str());
Tiger Huang721e26f2018-07-24 22:26:19 +08005224 }
5225 }
5226 }
Tiger Huang721e26f2018-07-24 22:26:19 +08005227 } // release lock
5228
5229 // Wake up poll loop since it may need to make new input dispatching choices.
5230 mLooper->wake();
5231}
5232
Michael Wrightd02c5b62014-02-10 15:10:22 -08005233void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005234 if (DEBUG_FOCUS) {
5235 ALOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
5236 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005237
5238 bool changed;
5239 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005240 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005241
5242 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
5243 if (mDispatchFrozen && !frozen) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005244 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005245 }
5246
5247 if (mDispatchEnabled && !enabled) {
5248 resetAndDropEverythingLocked("dispatcher is being disabled");
5249 }
5250
5251 mDispatchEnabled = enabled;
5252 mDispatchFrozen = frozen;
5253 changed = true;
5254 } else {
5255 changed = false;
5256 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005257 } // release lock
5258
5259 if (changed) {
5260 // Wake up poll loop since it may need to make new input dispatching choices.
5261 mLooper->wake();
5262 }
5263}
5264
5265void InputDispatcher::setInputFilterEnabled(bool enabled) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005266 if (DEBUG_FOCUS) {
5267 ALOGD("setInputFilterEnabled: enabled=%d", enabled);
5268 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005269
5270 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005271 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005272
5273 if (mInputFilterEnabled == enabled) {
5274 return;
5275 }
5276
5277 mInputFilterEnabled = enabled;
5278 resetAndDropEverythingLocked("input filter is being enabled or disabled");
5279 } // release lock
5280
5281 // Wake up poll loop since there might be work to do to drop everything.
5282 mLooper->wake();
5283}
5284
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005285bool InputDispatcher::setInTouchMode(bool inTouchMode, gui::Pid pid, gui::Uid uid,
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00005286 bool hasPermission, int32_t displayId) {
Antonio Kantekf16f2832021-09-28 04:39:20 +00005287 bool needWake = false;
5288 {
5289 std::scoped_lock lock(mLock);
Antonio Kantek15beb512022-06-13 22:35:41 +00005290 ALOGD_IF(DEBUG_TOUCH_MODE,
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005291 "Request to change touch mode to %s (calling pid=%s, uid=%s, "
Antonio Kantek15beb512022-06-13 22:35:41 +00005292 "hasPermission=%s, target displayId=%d, mTouchModePerDisplay[displayId]=%s)",
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005293 toString(inTouchMode), pid.toString().c_str(), uid.toString().c_str(),
5294 toString(hasPermission), displayId,
Antonio Kantek15beb512022-06-13 22:35:41 +00005295 mTouchModePerDisplay.count(displayId) == 0
5296 ? "not set"
5297 : std::to_string(mTouchModePerDisplay[displayId]).c_str());
5298
Antonio Kantek15beb512022-06-13 22:35:41 +00005299 auto touchModeIt = mTouchModePerDisplay.find(displayId);
5300 if (touchModeIt != mTouchModePerDisplay.end() && touchModeIt->second == inTouchMode) {
Antonio Kantekea47acb2021-12-23 12:41:25 -08005301 return false;
Antonio Kantekf16f2832021-09-28 04:39:20 +00005302 }
Antonio Kantekea47acb2021-12-23 12:41:25 -08005303 if (!hasPermission) {
Antonio Kantek48710e42022-03-24 14:19:30 -07005304 if (!focusedWindowIsOwnedByLocked(pid, uid) &&
5305 !recentWindowsAreOwnedByLocked(pid, uid)) {
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005306 ALOGD("Touch mode switch rejected, caller (pid=%s, uid=%s) doesn't own the focused "
Antonio Kantek48710e42022-03-24 14:19:30 -07005307 "window nor none of the previously interacted window",
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005308 pid.toString().c_str(), uid.toString().c_str());
Antonio Kantekea47acb2021-12-23 12:41:25 -08005309 return false;
5310 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00005311 }
Antonio Kantek15beb512022-06-13 22:35:41 +00005312 mTouchModePerDisplay[displayId] = inTouchMode;
5313 auto entry = std::make_unique<TouchModeEntry>(mIdGenerator.nextId(), now(), inTouchMode,
5314 displayId);
Antonio Kantekf16f2832021-09-28 04:39:20 +00005315 needWake = enqueueInboundEventLocked(std::move(entry));
5316 } // release lock
5317
5318 if (needWake) {
5319 mLooper->wake();
5320 }
Antonio Kantekea47acb2021-12-23 12:41:25 -08005321 return true;
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -08005322}
5323
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005324bool InputDispatcher::focusedWindowIsOwnedByLocked(gui::Pid pid, gui::Uid uid) {
Antonio Kantek48710e42022-03-24 14:19:30 -07005325 const sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
5326 if (focusedToken == nullptr) {
5327 return false;
5328 }
5329 sp<WindowInfoHandle> windowHandle = getWindowHandleLocked(focusedToken);
5330 return isWindowOwnedBy(windowHandle, pid, uid);
5331}
5332
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005333bool InputDispatcher::recentWindowsAreOwnedByLocked(gui::Pid pid, gui::Uid uid) {
Antonio Kantek48710e42022-03-24 14:19:30 -07005334 return std::find_if(mInteractionConnectionTokens.begin(), mInteractionConnectionTokens.end(),
5335 [&](const sp<IBinder>& connectionToken) REQUIRES(mLock) {
5336 const sp<WindowInfoHandle> windowHandle =
5337 getWindowHandleLocked(connectionToken);
5338 return isWindowOwnedBy(windowHandle, pid, uid);
5339 }) != mInteractionConnectionTokens.end();
5340}
5341
Bernardo Rufinoea97d182020-08-19 14:43:14 +01005342void InputDispatcher::setMaximumObscuringOpacityForTouch(float opacity) {
5343 if (opacity < 0 || opacity > 1) {
5344 LOG_ALWAYS_FATAL("Maximum obscuring opacity for touch should be >= 0 and <= 1");
5345 return;
5346 }
5347
5348 std::scoped_lock lock(mLock);
5349 mMaximumObscuringOpacityForTouch = opacity;
5350}
5351
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005352std::tuple<TouchState*, TouchedWindow*, int32_t /*displayId*/>
5353InputDispatcher::findTouchStateWindowAndDisplayLocked(const sp<IBinder>& token) {
Arthur Hungabbb9d82021-09-01 14:52:30 +00005354 for (auto& [displayId, state] : mTouchStatesByDisplay) {
5355 for (TouchedWindow& w : state.windows) {
5356 if (w.windowHandle->getToken() == token) {
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005357 return std::make_tuple(&state, &w, displayId);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005358 }
5359 }
5360 }
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005361 return std::make_tuple(nullptr, nullptr, ADISPLAY_ID_DEFAULT);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005362}
5363
arthurhungb89ccb02020-12-30 16:19:01 +08005364bool InputDispatcher::transferTouchFocus(const sp<IBinder>& fromToken, const sp<IBinder>& toToken,
5365 bool isDragDrop) {
chaviwfbe5d9c2018-12-26 12:23:37 -08005366 if (fromToken == toToken) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005367 if (DEBUG_FOCUS) {
5368 ALOGD("Trivial transfer to same window.");
5369 }
chaviwfbe5d9c2018-12-26 12:23:37 -08005370 return true;
5371 }
5372
Michael Wrightd02c5b62014-02-10 15:10:22 -08005373 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005374 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005375
Arthur Hungabbb9d82021-09-01 14:52:30 +00005376 // Find the target touch state and touched window by fromToken.
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005377 auto [state, touchedWindow, displayId] = findTouchStateWindowAndDisplayLocked(fromToken);
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005378
Arthur Hungabbb9d82021-09-01 14:52:30 +00005379 if (state == nullptr || touchedWindow == nullptr) {
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005380 ALOGD("Touch transfer failed because from window is not being touched.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005381 return false;
5382 }
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005383 std::set<int32_t> deviceIds = touchedWindow->getTouchingDeviceIds();
5384 if (deviceIds.size() != 1) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07005385 LOG(INFO) << "Can't transfer touch. Currently touching devices: " << dumpSet(deviceIds)
5386 << " for window: " << touchedWindow->dump();
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005387 return false;
5388 }
5389 const int32_t deviceId = *deviceIds.begin();
Arthur Hungabbb9d82021-09-01 14:52:30 +00005390
Arthur Hungabbb9d82021-09-01 14:52:30 +00005391 sp<WindowInfoHandle> toWindowHandle = getWindowHandleLocked(toToken, displayId);
5392 if (toWindowHandle == nullptr) {
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005393 ALOGW("Cannot transfer touch because to window not found.");
Arthur Hungabbb9d82021-09-01 14:52:30 +00005394 return false;
5395 }
5396
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005397 if (DEBUG_FOCUS) {
5398 ALOGD("transferTouchFocus: fromWindowHandle=%s, toWindowHandle=%s",
Arthur Hungabbb9d82021-09-01 14:52:30 +00005399 touchedWindow->windowHandle->getName().c_str(),
5400 toWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005401 }
5402
Arthur Hungabbb9d82021-09-01 14:52:30 +00005403 // Erase old window.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005404 ftl::Flags<InputTarget::Flags> oldTargetFlags = touchedWindow->targetFlags;
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005405 std::bitset<MAX_POINTER_ID + 1> pointerIds = touchedWindow->getTouchingPointers(deviceId);
Arthur Hungc539dbb2022-12-08 07:45:36 +00005406 sp<WindowInfoHandle> fromWindowHandle = touchedWindow->windowHandle;
Arthur Hungabbb9d82021-09-01 14:52:30 +00005407 state->removeWindowByToken(fromToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005408
Arthur Hungabbb9d82021-09-01 14:52:30 +00005409 // Add new window.
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00005410 nsecs_t downTimeInTarget = now();
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005411 ftl::Flags<InputTarget::Flags> newTargetFlags =
5412 oldTargetFlags & (InputTarget::Flags::SPLIT | InputTarget::Flags::DISPATCH_AS_IS);
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00005413 if (canReceiveForegroundTouches(*toWindowHandle->getInfo())) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005414 newTargetFlags |= InputTarget::Flags::FOREGROUND;
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00005415 }
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005416 state->addOrUpdateWindow(toWindowHandle, newTargetFlags, deviceId, pointerIds,
5417 downTimeInTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005418
Arthur Hungabbb9d82021-09-01 14:52:30 +00005419 // Store the dragging window.
5420 if (isDragDrop) {
Arthur Hungb75c2aa2022-07-15 09:35:36 +00005421 if (pointerIds.count() != 1) {
5422 ALOGW("The drag and drop cannot be started when there is no pointer or more than 1"
5423 " pointer on the window.");
Arthur Hung54745652022-04-20 07:17:41 +00005424 return false;
5425 }
Arthur Hungb75c2aa2022-07-15 09:35:36 +00005426 // Track the pointer id for drag window and generate the drag state.
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08005427 const size_t id = firstMarkedBit(pointerIds);
Arthur Hung54745652022-04-20 07:17:41 +00005428 mDragState = std::make_unique<DragState>(toWindowHandle, id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005429 }
5430
Arthur Hungabbb9d82021-09-01 14:52:30 +00005431 // Synthesize cancel for old window and down for new window.
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07005432 std::shared_ptr<Connection> fromConnection = getConnectionLocked(fromToken);
5433 std::shared_ptr<Connection> toConnection = getConnectionLocked(toToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005434 if (fromConnection != nullptr && toConnection != nullptr) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08005435 fromConnection->inputState.mergePointerStateTo(toConnection->inputState);
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005436 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
5437 "transferring touch from this window to another window");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005438 synthesizeCancelationEventsForConnectionLocked(fromConnection, options);
Arthur Hungc539dbb2022-12-08 07:45:36 +00005439 synthesizePointerDownEventsForConnectionLocked(downTimeInTarget, toConnection,
5440 newTargetFlags);
5441
5442 // Check if the wallpaper window should deliver the corresponding event.
5443 transferWallpaperTouch(oldTargetFlags, newTargetFlags, fromWindowHandle, toWindowHandle,
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005444 *state, deviceId, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005445 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005446 } // release lock
5447
5448 // Wake up poll loop since it may need to make new input dispatching choices.
5449 mLooper->wake();
5450 return true;
5451}
5452
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005453/**
5454 * Get the touched foreground window on the given display.
5455 * Return null if there are no windows touched on that display, or if more than one foreground
5456 * window is being touched.
5457 */
5458sp<WindowInfoHandle> InputDispatcher::findTouchedForegroundWindowLocked(int32_t displayId) const {
5459 auto stateIt = mTouchStatesByDisplay.find(displayId);
5460 if (stateIt == mTouchStatesByDisplay.end()) {
5461 ALOGI("No touch state on display %" PRId32, displayId);
5462 return nullptr;
5463 }
5464
5465 const TouchState& state = stateIt->second;
5466 sp<WindowInfoHandle> touchedForegroundWindow;
5467 // If multiple foreground windows are touched, return nullptr
5468 for (const TouchedWindow& window : state.windows) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005469 if (window.targetFlags.test(InputTarget::Flags::FOREGROUND)) {
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005470 if (touchedForegroundWindow != nullptr) {
5471 ALOGI("Two or more foreground windows: %s and %s",
5472 touchedForegroundWindow->getName().c_str(),
5473 window.windowHandle->getName().c_str());
5474 return nullptr;
5475 }
5476 touchedForegroundWindow = window.windowHandle;
5477 }
5478 }
5479 return touchedForegroundWindow;
5480}
5481
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005482// Binder call
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005483bool InputDispatcher::transferTouch(const sp<IBinder>& destChannelToken, int32_t displayId) {
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005484 sp<IBinder> fromToken;
5485 { // acquire lock
5486 std::scoped_lock _l(mLock);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005487 sp<WindowInfoHandle> toWindowHandle = getWindowHandleLocked(destChannelToken, displayId);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005488 if (toWindowHandle == nullptr) {
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005489 ALOGW("Could not find window associated with token=%p on display %" PRId32,
5490 destChannelToken.get(), displayId);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005491 return false;
5492 }
5493
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005494 sp<WindowInfoHandle> from = findTouchedForegroundWindowLocked(displayId);
5495 if (from == nullptr) {
5496 ALOGE("Could not find a source window in %s for %p", __func__, destChannelToken.get());
5497 return false;
5498 }
5499
5500 fromToken = from->getToken();
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005501 } // release lock
5502
5503 return transferTouchFocus(fromToken, destChannelToken);
5504}
5505
Michael Wrightd02c5b62014-02-10 15:10:22 -08005506void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005507 if (DEBUG_FOCUS) {
5508 ALOGD("Resetting and dropping all events (%s).", reason);
5509 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005510
Michael Wrightfb04fd52022-11-24 22:31:11 +00005511 CancelationOptions options(CancelationOptions::Mode::CANCEL_ALL_EVENTS, reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005512 synthesizeCancelationEventsForAllConnectionsLocked(options);
5513
5514 resetKeyRepeatLocked();
5515 releasePendingEventLocked();
5516 drainInboundQueueLocked();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005517 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005518
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005519 mAnrTracker.clear();
Jeff Brownf086ddb2014-02-11 14:28:48 -08005520 mTouchStatesByDisplay.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005521}
5522
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005523void InputDispatcher::logDispatchStateLocked() const {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005524 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005525 dumpDispatchStateLocked(dump);
5526
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005527 std::istringstream stream(dump);
5528 std::string line;
5529
5530 while (std::getline(stream, line, '\n')) {
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07005531 ALOGI("%s", line.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005532 }
5533}
5534
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005535std::string InputDispatcher::dumpPointerCaptureStateLocked() const {
Prabir Pradhan99987712020-11-10 18:43:05 -08005536 std::string dump;
5537
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005538 dump += StringPrintf(INDENT "Pointer Capture Requested: %s\n",
5539 toString(mCurrentPointerCaptureRequest.enable));
Prabir Pradhan99987712020-11-10 18:43:05 -08005540
5541 std::string windowName = "None";
5542 if (mWindowTokenWithPointerCapture) {
chaviw98318de2021-05-19 16:45:23 -05005543 const sp<WindowInfoHandle> captureWindowHandle =
Prabir Pradhan99987712020-11-10 18:43:05 -08005544 getWindowHandleLocked(mWindowTokenWithPointerCapture);
5545 windowName = captureWindowHandle ? captureWindowHandle->getName().c_str()
5546 : "token has capture without window";
5547 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005548 dump += StringPrintf(INDENT "Current Window with Pointer Capture: %s\n", windowName.c_str());
Prabir Pradhan99987712020-11-10 18:43:05 -08005549
5550 return dump;
5551}
5552
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005553void InputDispatcher::dumpDispatchStateLocked(std::string& dump) const {
Siarhei Vishniakou043a3ec2019-05-01 11:30:46 -07005554 dump += StringPrintf(INDENT "DispatchEnabled: %s\n", toString(mDispatchEnabled));
5555 dump += StringPrintf(INDENT "DispatchFrozen: %s\n", toString(mDispatchFrozen));
5556 dump += StringPrintf(INDENT "InputFilterEnabled: %s\n", toString(mInputFilterEnabled));
Tiger Huang721e26f2018-07-24 22:26:19 +08005557 dump += StringPrintf(INDENT "FocusedDisplayId: %" PRId32 "\n", mFocusedDisplayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005558
Tiger Huang721e26f2018-07-24 22:26:19 +08005559 if (!mFocusedApplicationHandlesByDisplay.empty()) {
5560 dump += StringPrintf(INDENT "FocusedApplications:\n");
5561 for (auto& it : mFocusedApplicationHandlesByDisplay) {
5562 const int32_t displayId = it.first;
Chris Yea209fde2020-07-22 13:54:51 -07005563 const std::shared_ptr<InputApplicationHandle>& applicationHandle = it.second;
Siarhei Vishniakou70622952020-07-30 11:17:23 -05005564 const std::chrono::duration timeout =
5565 applicationHandle->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005566 dump += StringPrintf(INDENT2 "displayId=%" PRId32
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005567 ", name='%s', dispatchingTimeout=%" PRId64 "ms\n",
Siarhei Vishniakou70622952020-07-30 11:17:23 -05005568 displayId, applicationHandle->getName().c_str(), millis(timeout));
Tiger Huang721e26f2018-07-24 22:26:19 +08005569 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005570 } else {
Tiger Huang721e26f2018-07-24 22:26:19 +08005571 dump += StringPrintf(INDENT "FocusedApplications: <none>\n");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005572 }
Tiger Huang721e26f2018-07-24 22:26:19 +08005573
Vishnu Nairc519ff72021-01-21 08:23:08 -08005574 dump += mFocusResolver.dump();
Prabir Pradhan99987712020-11-10 18:43:05 -08005575 dump += dumpPointerCaptureStateLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005576
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005577 if (!mTouchStatesByDisplay.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005578 dump += StringPrintf(INDENT "TouchStatesByDisplay:\n");
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005579 for (const auto& [displayId, state] : mTouchStatesByDisplay) {
Siarhei Vishniakou6e1e9872022-11-08 17:51:35 -08005580 std::string touchStateDump = addLinePrefix(state.dump(), INDENT2);
5581 dump += INDENT2 + std::to_string(displayId) + " : " + touchStateDump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005582 }
5583 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005584 dump += INDENT "TouchStates: <no displays touched>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005585 }
5586
arthurhung6d4bed92021-03-17 11:59:33 +08005587 if (mDragState) {
5588 dump += StringPrintf(INDENT "DragState:\n");
5589 mDragState->dump(dump, INDENT2);
5590 }
5591
Arthur Hungb92218b2018-08-14 12:00:21 +08005592 if (!mWindowHandlesByDisplay.empty()) {
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005593 for (const auto& [displayId, windowHandles] : mWindowHandlesByDisplay) {
5594 dump += StringPrintf(INDENT "Display: %" PRId32 "\n", displayId);
5595 if (const auto& it = mDisplayInfos.find(displayId); it != mDisplayInfos.end()) {
5596 const auto& displayInfo = it->second;
5597 dump += StringPrintf(INDENT2 "logicalSize=%dx%d\n", displayInfo.logicalWidth,
5598 displayInfo.logicalHeight);
5599 displayInfo.transform.dump(dump, "transform", INDENT4);
5600 } else {
5601 dump += INDENT2 "No DisplayInfo found!\n";
5602 }
5603
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08005604 if (!windowHandles.empty()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08005605 dump += INDENT2 "Windows:\n";
5606 for (size_t i = 0; i < windowHandles.size(); i++) {
chaviw98318de2021-05-19 16:45:23 -05005607 const sp<WindowInfoHandle>& windowHandle = windowHandles[i];
5608 const WindowInfo* windowInfo = windowHandle->getInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005609
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00005610 dump += StringPrintf(INDENT3 "%zu: name='%s', id=%" PRId32 ", displayId=%d, "
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005611 "inputConfig=%s, alpha=%.2f, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005612 "frame=[%d,%d][%d,%d], globalScale=%f, "
Bernardo Rufino49d99e42021-01-18 15:16:59 +00005613 "applicationInfo.name=%s, "
5614 "applicationInfo.token=%s, "
chaviw1ff3d1e2020-07-01 15:53:47 -07005615 "touchableRegion=",
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00005616 i, windowInfo->name.c_str(), windowInfo->id,
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005617 windowInfo->displayId,
5618 windowInfo->inputConfig.string().c_str(),
Chavi Weingarten7f019192023-08-08 20:39:01 +00005619 windowInfo->alpha, windowInfo->frame.left,
5620 windowInfo->frame.top, windowInfo->frame.right,
5621 windowInfo->frame.bottom, windowInfo->globalScaleFactor,
Bernardo Rufino49d99e42021-01-18 15:16:59 +00005622 windowInfo->applicationInfo.name.c_str(),
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07005623 binderToString(windowInfo->applicationInfo.token).c_str());
Bernardo Rufino53fc31e2020-11-03 11:01:07 +00005624 dump += dumpRegion(windowInfo->touchableRegion);
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005625 dump += StringPrintf(", ownerPid=%s, ownerUid=%s, dispatchingTimeout=%" PRId64
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005626 "ms, hasToken=%s, "
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005627 "touchOcclusionMode=%s\n",
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005628 windowInfo->ownerPid.toString().c_str(),
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00005629 windowInfo->ownerUid.toString().c_str(),
Bernardo Rufinoc2f1fad2020-11-04 17:30:57 +00005630 millis(windowInfo->dispatchingTimeout),
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07005631 binderToString(windowInfo->token).c_str(),
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005632 toString(windowInfo->touchOcclusionMode).c_str());
chaviw85b44202020-07-24 11:46:21 -07005633 windowInfo->transform.dump(dump, "transform", INDENT4);
Arthur Hungb92218b2018-08-14 12:00:21 +08005634 }
5635 } else {
5636 dump += INDENT2 "Windows: <none>\n";
5637 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005638 }
5639 } else {
Arthur Hungb92218b2018-08-14 12:00:21 +08005640 dump += INDENT "Displays: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005641 }
5642
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005643 if (!mGlobalMonitorsByDisplay.empty()) {
5644 for (const auto& [displayId, monitors] : mGlobalMonitorsByDisplay) {
5645 dump += StringPrintf(INDENT "Global monitors on display %d:\n", displayId);
Michael Wright3dd60e22019-03-27 22:06:44 +00005646 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005647 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005648 } else {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005649 dump += INDENT "Global Monitors: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005650 }
5651
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005652 const nsecs_t currentTime = now();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005653
5654 // Dump recently dispatched or dropped events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005655 if (!mRecentQueue.empty()) {
5656 dump += StringPrintf(INDENT "RecentQueue: length=%zu\n", mRecentQueue.size());
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005657 for (const std::shared_ptr<EventEntry>& entry : mRecentQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005658 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005659 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005660 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005661 }
5662 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005663 dump += INDENT "RecentQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005664 }
5665
5666 // Dump event currently being dispatched.
5667 if (mPendingEvent) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005668 dump += INDENT "PendingEvent:\n";
5669 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005670 dump += mPendingEvent->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005671 dump += StringPrintf(", age=%" PRId64 "ms\n",
5672 ns2ms(currentTime - mPendingEvent->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005673 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005674 dump += INDENT "PendingEvent: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005675 }
5676
5677 // Dump inbound events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005678 if (!mInboundQueue.empty()) {
5679 dump += StringPrintf(INDENT "InboundQueue: length=%zu\n", mInboundQueue.size());
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005680 for (const std::shared_ptr<EventEntry>& entry : mInboundQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005681 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005682 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005683 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005684 }
5685 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005686 dump += INDENT "InboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005687 }
5688
Prabir Pradhancef936d2021-07-21 16:17:52 +00005689 if (!mCommandQueue.empty()) {
5690 dump += StringPrintf(INDENT "CommandQueue: size=%zu\n", mCommandQueue.size());
5691 } else {
5692 dump += INDENT "CommandQueue: <empty>\n";
5693 }
5694
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005695 if (!mConnectionsByToken.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005696 dump += INDENT "Connections:\n";
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005697 for (const auto& [token, connection] : mConnectionsByToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005698 dump += StringPrintf(INDENT2 "%i: channelName='%s', windowName='%s', "
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005699 "status=%s, monitor=%s, responsive=%s\n",
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005700 connection->inputChannel->getFd().get(),
5701 connection->getInputChannelName().c_str(),
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08005702 connection->getWindowName().c_str(),
5703 ftl::enum_string(connection->status).c_str(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005704 toString(connection->monitor), toString(connection->responsive));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005705
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005706 if (!connection->outboundQueue.empty()) {
5707 dump += StringPrintf(INDENT3 "OutboundQueue: length=%zu\n",
5708 connection->outboundQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005709 dump += dumpQueue(connection->outboundQueue, currentTime);
5710
Michael Wrightd02c5b62014-02-10 15:10:22 -08005711 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005712 dump += INDENT3 "OutboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005713 }
5714
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005715 if (!connection->waitQueue.empty()) {
5716 dump += StringPrintf(INDENT3 "WaitQueue: length=%zu\n",
5717 connection->waitQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005718 dump += dumpQueue(connection->waitQueue, currentTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005719 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005720 dump += INDENT3 "WaitQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005721 }
Siarhei Vishniakoud38a1e02023-07-18 11:55:17 -07005722 std::stringstream inputStateDump;
5723 inputStateDump << connection->inputState;
5724 if (!isEmpty(inputStateDump)) {
5725 dump += INDENT3 "InputState: ";
5726 dump += inputStateDump.str() + "\n";
5727 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005728 }
5729 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005730 dump += INDENT "Connections: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005731 }
5732
5733 if (isAppSwitchPendingLocked()) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005734 dump += StringPrintf(INDENT "AppSwitch: pending, due in %" PRId64 "ms\n",
5735 ns2ms(mAppSwitchDueTime - now()));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005736 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005737 dump += INDENT "AppSwitch: not pending\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005738 }
5739
Antonio Kantek15beb512022-06-13 22:35:41 +00005740 if (!mTouchModePerDisplay.empty()) {
5741 dump += INDENT "TouchModePerDisplay:\n";
5742 for (const auto& [displayId, touchMode] : mTouchModePerDisplay) {
5743 dump += StringPrintf(INDENT2 "Display: %" PRId32 " TouchMode: %s\n", displayId,
5744 std::to_string(touchMode).c_str());
5745 }
5746 } else {
5747 dump += INDENT "TouchModePerDisplay: <none>\n";
5748 }
5749
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005750 dump += INDENT "Configuration:\n";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005751 dump += StringPrintf(INDENT2 "KeyRepeatDelay: %" PRId64 "ms\n", ns2ms(mConfig.keyRepeatDelay));
5752 dump += StringPrintf(INDENT2 "KeyRepeatTimeout: %" PRId64 "ms\n",
5753 ns2ms(mConfig.keyRepeatTimeout));
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00005754 dump += mLatencyTracker.dump(INDENT2);
Siarhei Vishniakoua04181f2021-03-26 05:56:49 +00005755 dump += mLatencyAggregator.dump(INDENT2);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005756}
5757
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005758void InputDispatcher::dumpMonitors(std::string& dump, const std::vector<Monitor>& monitors) const {
Michael Wright3dd60e22019-03-27 22:06:44 +00005759 const size_t numMonitors = monitors.size();
5760 for (size_t i = 0; i < numMonitors; i++) {
5761 const Monitor& monitor = monitors[i];
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005762 const std::shared_ptr<InputChannel>& channel = monitor.inputChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005763 dump += StringPrintf(INDENT2 "%zu: '%s', ", i, channel->getName().c_str());
5764 dump += "\n";
5765 }
5766}
5767
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005768class LooperEventCallback : public LooperCallback {
5769public:
5770 LooperEventCallback(std::function<int(int events)> callback) : mCallback(callback) {}
5771 int handleEvent(int /*fd*/, int events, void* /*data*/) override { return mCallback(events); }
5772
5773private:
5774 std::function<int(int events)> mCallback;
5775};
5776
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005777Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputChannel(const std::string& name) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00005778 if (DEBUG_CHANNEL_CREATION) {
5779 ALOGD("channel '%s' ~ createInputChannel", name.c_str());
5780 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005781
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005782 std::unique_ptr<InputChannel> serverChannel;
Garfield Tan15601662020-09-22 15:32:38 -07005783 std::unique_ptr<InputChannel> clientChannel;
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005784 status_t result = InputChannel::openInputChannelPair(name, serverChannel, clientChannel);
Garfield Tan15601662020-09-22 15:32:38 -07005785
5786 if (result) {
5787 return base::Error(result) << "Failed to open input channel pair with name " << name;
5788 }
5789
Michael Wrightd02c5b62014-02-10 15:10:22 -08005790 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005791 std::scoped_lock _l(mLock);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005792 const sp<IBinder>& token = serverChannel->getConnectionToken();
Garfield Tan15601662020-09-22 15:32:38 -07005793 int fd = serverChannel->getFd();
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07005794 std::shared_ptr<Connection> connection =
5795 std::make_shared<Connection>(std::move(serverChannel), /*monitor=*/false,
5796 mIdGenerator);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005797
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005798 if (mConnectionsByToken.find(token) != mConnectionsByToken.end()) {
5799 ALOGE("Created a new connection, but the token %p is already known", token.get());
5800 }
5801 mConnectionsByToken.emplace(token, connection);
5802
5803 std::function<int(int events)> callback = std::bind(&InputDispatcher::handleReceiveCallback,
5804 this, std::placeholders::_1, token);
5805
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005806 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, sp<LooperEventCallback>::make(callback),
5807 nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005808 } // release lock
5809
5810 // Wake the looper because some connections have changed.
5811 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07005812 return clientChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005813}
5814
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005815Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputMonitor(int32_t displayId,
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005816 const std::string& name,
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005817 gui::Pid pid) {
Garfield Tan15601662020-09-22 15:32:38 -07005818 std::shared_ptr<InputChannel> serverChannel;
5819 std::unique_ptr<InputChannel> clientChannel;
5820 status_t result = openInputChannelPair(name, serverChannel, clientChannel);
5821 if (result) {
5822 return base::Error(result) << "Failed to open input channel pair with name " << name;
5823 }
5824
Michael Wright3dd60e22019-03-27 22:06:44 +00005825 { // acquire lock
5826 std::scoped_lock _l(mLock);
5827
5828 if (displayId < 0) {
Garfield Tan15601662020-09-22 15:32:38 -07005829 return base::Error(BAD_VALUE) << "Attempted to create input monitor with name " << name
5830 << " without a specified display.";
Michael Wright3dd60e22019-03-27 22:06:44 +00005831 }
5832
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07005833 std::shared_ptr<Connection> connection =
5834 std::make_shared<Connection>(serverChannel, /*monitor=*/true, mIdGenerator);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005835 const sp<IBinder>& token = serverChannel->getConnectionToken();
Garfield Tan15601662020-09-22 15:32:38 -07005836 const int fd = serverChannel->getFd();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005837
5838 if (mConnectionsByToken.find(token) != mConnectionsByToken.end()) {
5839 ALOGE("Created a new connection, but the token %p is already known", token.get());
5840 }
5841 mConnectionsByToken.emplace(token, connection);
5842 std::function<int(int events)> callback = std::bind(&InputDispatcher::handleReceiveCallback,
5843 this, std::placeholders::_1, token);
Michael Wright3dd60e22019-03-27 22:06:44 +00005844
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005845 mGlobalMonitorsByDisplay[displayId].emplace_back(serverChannel, pid);
Michael Wright3dd60e22019-03-27 22:06:44 +00005846
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005847 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, sp<LooperEventCallback>::make(callback),
5848 nullptr);
Michael Wright3dd60e22019-03-27 22:06:44 +00005849 }
Garfield Tan15601662020-09-22 15:32:38 -07005850
Michael Wright3dd60e22019-03-27 22:06:44 +00005851 // Wake the looper because some connections have changed.
5852 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07005853 return clientChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005854}
5855
Garfield Tan15601662020-09-22 15:32:38 -07005856status_t InputDispatcher::removeInputChannel(const sp<IBinder>& connectionToken) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005857 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005858 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005859
Harry Cutts33476232023-01-30 19:57:29 +00005860 status_t status = removeInputChannelLocked(connectionToken, /*notify=*/false);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005861 if (status) {
5862 return status;
5863 }
5864 } // release lock
5865
5866 // Wake the poll loop because removing the connection may have changed the current
5867 // synchronization state.
5868 mLooper->wake();
5869 return OK;
5870}
5871
Garfield Tan15601662020-09-22 15:32:38 -07005872status_t InputDispatcher::removeInputChannelLocked(const sp<IBinder>& connectionToken,
5873 bool notify) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07005874 std::shared_ptr<Connection> connection = getConnectionLocked(connectionToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005875 if (connection == nullptr) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005876 // Connection can be removed via socket hang up or an explicit call to 'removeInputChannel'
Michael Wrightd02c5b62014-02-10 15:10:22 -08005877 return BAD_VALUE;
5878 }
5879
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005880 removeConnectionLocked(connection);
Robert Carr5c8a0262018-10-03 16:30:44 -07005881
Michael Wrightd02c5b62014-02-10 15:10:22 -08005882 if (connection->monitor) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005883 removeMonitorChannelLocked(connectionToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005884 }
5885
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005886 mLooper->removeFd(connection->inputChannel->getFd());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005887
5888 nsecs_t currentTime = now();
5889 abortBrokenDispatchCycleLocked(currentTime, connection, notify);
5890
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08005891 connection->status = Connection::Status::ZOMBIE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005892 return OK;
5893}
5894
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005895void InputDispatcher::removeMonitorChannelLocked(const sp<IBinder>& connectionToken) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005896 for (auto it = mGlobalMonitorsByDisplay.begin(); it != mGlobalMonitorsByDisplay.end();) {
5897 auto& [displayId, monitors] = *it;
5898 std::erase_if(monitors, [connectionToken](const Monitor& monitor) {
5899 return monitor.inputChannel->getConnectionToken() == connectionToken;
5900 });
Michael Wright3dd60e22019-03-27 22:06:44 +00005901
Michael Wright3dd60e22019-03-27 22:06:44 +00005902 if (monitors.empty()) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005903 it = mGlobalMonitorsByDisplay.erase(it);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005904 } else {
5905 ++it;
5906 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005907 }
5908}
5909
Michael Wright3dd60e22019-03-27 22:06:44 +00005910status_t InputDispatcher::pilferPointers(const sp<IBinder>& token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005911 std::scoped_lock _l(mLock);
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00005912 return pilferPointersLocked(token);
5913}
Michael Wright3dd60e22019-03-27 22:06:44 +00005914
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00005915status_t InputDispatcher::pilferPointersLocked(const sp<IBinder>& token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005916 const std::shared_ptr<InputChannel> requestingChannel = getInputChannelLocked(token);
5917 if (!requestingChannel) {
Siarhei Vishniakou8384e0d2023-09-18 18:48:27 -07005918 LOG(WARNING)
5919 << "Attempted to pilfer pointers from an un-registered channel or invalid token";
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005920 return BAD_VALUE;
Michael Wright3dd60e22019-03-27 22:06:44 +00005921 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005922
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005923 auto [statePtr, windowPtr, displayId] = findTouchStateWindowAndDisplayLocked(token);
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005924 if (statePtr == nullptr || windowPtr == nullptr) {
Siarhei Vishniakou8384e0d2023-09-18 18:48:27 -07005925 LOG(WARNING)
5926 << "Attempted to pilfer points from a channel without any on-going pointer streams."
5927 " Ignoring.";
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005928 return BAD_VALUE;
5929 }
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005930 std::set<int32_t> deviceIds = windowPtr->getTouchingDeviceIds();
5931 if (deviceIds.size() != 1) {
5932 LOG(WARNING) << "Can't pilfer. Currently touching devices: " << dumpSet(deviceIds)
5933 << " in window: " << windowPtr->dump();
5934 return BAD_VALUE;
5935 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005936
Siarhei Vishniakou8384e0d2023-09-18 18:48:27 -07005937 for (const DeviceId deviceId : deviceIds) {
5938 TouchState& state = *statePtr;
5939 TouchedWindow& window = *windowPtr;
5940 // Send cancel events to all the input channels we're stealing from.
5941 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
5942 "input channel stole pointer stream");
5943 options.deviceId = deviceId;
5944 options.displayId = displayId;
5945 std::bitset<MAX_POINTER_ID + 1> pointerIds = window.getTouchingPointers(deviceId);
5946 options.pointerIds = pointerIds;
5947 std::string canceledWindows;
5948 for (const TouchedWindow& w : state.windows) {
5949 const std::shared_ptr<InputChannel> channel =
5950 getInputChannelLocked(w.windowHandle->getToken());
5951 if (channel != nullptr && channel->getConnectionToken() != token) {
5952 synthesizeCancelationEventsForInputChannelLocked(channel, options);
5953 canceledWindows += canceledWindows.empty() ? "[" : ", ";
5954 canceledWindows += channel->getName();
5955 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005956 }
Siarhei Vishniakou8384e0d2023-09-18 18:48:27 -07005957 canceledWindows += canceledWindows.empty() ? "[]" : "]";
5958 LOG(INFO) << "Channel " << requestingChannel->getName()
5959 << " is stealing input gesture for device " << deviceId << " from "
5960 << canceledWindows;
5961
5962 // Prevent the gesture from being sent to any other windows.
5963 // This only blocks relevant pointers to be sent to other windows
5964 window.addPilferingPointers(deviceId, pointerIds);
5965
5966 state.cancelPointersForWindowsExcept(deviceId, pointerIds, token);
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005967 }
Michael Wright3dd60e22019-03-27 22:06:44 +00005968 return OK;
5969}
5970
Prabir Pradhan99987712020-11-10 18:43:05 -08005971void InputDispatcher::requestPointerCapture(const sp<IBinder>& windowToken, bool enabled) {
5972 { // acquire lock
5973 std::scoped_lock _l(mLock);
5974 if (DEBUG_FOCUS) {
chaviw98318de2021-05-19 16:45:23 -05005975 const sp<WindowInfoHandle> windowHandle = getWindowHandleLocked(windowToken);
Prabir Pradhan99987712020-11-10 18:43:05 -08005976 ALOGI("Request to %s Pointer Capture from: %s.", enabled ? "enable" : "disable",
5977 windowHandle != nullptr ? windowHandle->getName().c_str()
5978 : "token without window");
5979 }
5980
Vishnu Nairc519ff72021-01-21 08:23:08 -08005981 const sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Prabir Pradhan99987712020-11-10 18:43:05 -08005982 if (focusedToken != windowToken) {
5983 ALOGW("Ignoring request to %s Pointer Capture: window does not have focus.",
5984 enabled ? "enable" : "disable");
5985 return;
5986 }
5987
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005988 if (enabled == mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08005989 ALOGW("Ignoring request to %s Pointer Capture: "
5990 "window has %s requested pointer capture.",
5991 enabled ? "enable" : "disable", enabled ? "already" : "not");
5992 return;
5993 }
5994
Christine Franksb768bb42021-11-29 12:11:31 -08005995 if (enabled) {
5996 if (std::find(mIneligibleDisplaysForPointerCapture.begin(),
5997 mIneligibleDisplaysForPointerCapture.end(),
5998 mFocusedDisplayId) != mIneligibleDisplaysForPointerCapture.end()) {
5999 ALOGW("Ignoring request to enable Pointer Capture: display is not eligible");
6000 return;
6001 }
6002 }
6003
Prabir Pradhan99987712020-11-10 18:43:05 -08006004 setPointerCaptureLocked(enabled);
6005 } // release lock
6006
6007 // Wake the thread to process command entries.
6008 mLooper->wake();
6009}
6010
Christine Franksb768bb42021-11-29 12:11:31 -08006011void InputDispatcher::setDisplayEligibilityForPointerCapture(int32_t displayId, bool isEligible) {
6012 { // acquire lock
6013 std::scoped_lock _l(mLock);
6014 std::erase(mIneligibleDisplaysForPointerCapture, displayId);
6015 if (!isEligible) {
6016 mIneligibleDisplaysForPointerCapture.push_back(displayId);
6017 }
6018 } // release lock
6019}
6020
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00006021std::optional<gui::Pid> InputDispatcher::findMonitorPidByTokenLocked(const sp<IBinder>& token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006022 for (const auto& [_, monitors] : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00006023 for (const Monitor& monitor : monitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07006024 if (monitor.inputChannel->getConnectionToken() == token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006025 return monitor.pid;
Michael Wright3dd60e22019-03-27 22:06:44 +00006026 }
6027 }
6028 }
6029 return std::nullopt;
6030}
6031
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006032std::shared_ptr<Connection> InputDispatcher::getConnectionLocked(
6033 const sp<IBinder>& inputConnectionToken) const {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07006034 if (inputConnectionToken == nullptr) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07006035 return nullptr;
Arthur Hung3b413f22018-10-26 18:05:34 +08006036 }
6037
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00006038 for (const auto& [token, connection] : mConnectionsByToken) {
6039 if (token == inputConnectionToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07006040 return connection;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006041 }
6042 }
Robert Carr4e670e52018-08-15 13:26:12 -07006043
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07006044 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006045}
6046
Siarhei Vishniakouad991402020-10-28 11:40:09 -05006047std::string InputDispatcher::getConnectionNameLocked(const sp<IBinder>& connectionToken) const {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006048 std::shared_ptr<Connection> connection = getConnectionLocked(connectionToken);
Siarhei Vishniakouad991402020-10-28 11:40:09 -05006049 if (connection == nullptr) {
6050 return "<nullptr>";
6051 }
6052 return connection->getInputChannelName();
6053}
6054
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006055void InputDispatcher::removeConnectionLocked(const std::shared_ptr<Connection>& connection) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006056 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00006057 mConnectionsByToken.erase(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07006058}
6059
Prabir Pradhancef936d2021-07-21 16:17:52 +00006060void InputDispatcher::doDispatchCycleFinishedCommand(nsecs_t finishTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006061 const std::shared_ptr<Connection>& connection,
6062 uint32_t seq, bool handled,
6063 nsecs_t consumeTime) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006064 // Handle post-event policy actions.
Prabir Pradhancef936d2021-07-21 16:17:52 +00006065 bool restartEvent;
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006066
6067 { // Start critical section
6068 auto dispatchEntryIt =
6069 std::find_if(connection->waitQueue.begin(), connection->waitQueue.end(),
6070 [seq](auto& e) { return e->seq == seq; });
6071 if (dispatchEntryIt == connection->waitQueue.end()) {
6072 return;
6073 }
6074
6075 DispatchEntry& dispatchEntry = **dispatchEntryIt;
6076
6077 const nsecs_t eventDuration = finishTime - dispatchEntry.deliveryTime;
6078 if (eventDuration > SLOW_EVENT_PROCESSING_WARNING_TIMEOUT) {
6079 ALOGI("%s spent %" PRId64 "ms processing %s", connection->getWindowName().c_str(),
6080 ns2ms(eventDuration), dispatchEntry.eventEntry->getDescription().c_str());
6081 }
6082 if (shouldReportFinishedEvent(dispatchEntry, *connection)) {
6083 mLatencyTracker.trackFinishedEvent(dispatchEntry.eventEntry->id,
6084 connection->inputChannel->getConnectionToken(),
6085 dispatchEntry.deliveryTime, consumeTime, finishTime);
6086 }
6087
6088 if (dispatchEntry.eventEntry->type == EventEntry::Type::KEY) {
6089 KeyEntry& keyEntry = static_cast<KeyEntry&>(*(dispatchEntry.eventEntry));
6090 restartEvent =
6091 afterKeyEventLockedInterruptable(connection, dispatchEntry, keyEntry, handled);
6092 } else if (dispatchEntry.eventEntry->type == EventEntry::Type::MOTION) {
6093 MotionEntry& motionEntry = static_cast<MotionEntry&>(*(dispatchEntry.eventEntry));
6094 restartEvent = afterMotionEventLockedInterruptable(connection, dispatchEntry,
6095 motionEntry, handled);
6096 } else {
6097 restartEvent = false;
6098 }
6099 } // End critical section: The -LockedInterruptable methods may have released the lock.
Prabir Pradhancef936d2021-07-21 16:17:52 +00006100
6101 // Dequeue the event and start the next cycle.
6102 // Because the lock might have been released, it is possible that the
6103 // contents of the wait queue to have been drained, so we need to double-check
6104 // a few things.
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006105 auto entryIt = std::find_if(connection->waitQueue.begin(), connection->waitQueue.end(),
6106 [seq](auto& e) { return e->seq == seq; });
6107 if (entryIt != connection->waitQueue.end()) {
6108 std::unique_ptr<DispatchEntry> dispatchEntry = std::move(*entryIt);
6109 connection->waitQueue.erase(entryIt);
6110
Prabir Pradhancef936d2021-07-21 16:17:52 +00006111 const sp<IBinder>& connectionToken = connection->inputChannel->getConnectionToken();
6112 mAnrTracker.erase(dispatchEntry->timeoutTime, connectionToken);
6113 if (!connection->responsive) {
6114 connection->responsive = isConnectionResponsive(*connection);
6115 if (connection->responsive) {
6116 // The connection was unresponsive, and now it's responsive.
6117 processConnectionResponsiveLocked(*connection);
6118 }
6119 }
6120 traceWaitQueueLength(*connection);
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08006121 if (restartEvent && connection->status == Connection::Status::NORMAL) {
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006122 connection->outboundQueue.emplace_front(std::move(dispatchEntry));
Prabir Pradhancef936d2021-07-21 16:17:52 +00006123 traceOutboundQueueLength(*connection);
6124 } else {
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006125 releaseDispatchEntry(std::move(dispatchEntry));
Prabir Pradhancef936d2021-07-21 16:17:52 +00006126 }
6127 }
6128
6129 // Start the next dispatch cycle for this connection.
6130 startDispatchCycleLocked(now(), connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006131}
6132
Prabir Pradhancef936d2021-07-21 16:17:52 +00006133void InputDispatcher::sendFocusChangedCommandLocked(const sp<IBinder>& oldToken,
6134 const sp<IBinder>& newToken) {
6135 auto command = [this, oldToken, newToken]() REQUIRES(mLock) {
6136 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00006137 mPolicy.notifyFocusChanged(oldToken, newToken);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006138 };
6139 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08006140}
6141
Prabir Pradhancef936d2021-07-21 16:17:52 +00006142void InputDispatcher::sendDropWindowCommandLocked(const sp<IBinder>& token, float x, float y) {
6143 auto command = [this, token, x, y]() REQUIRES(mLock) {
6144 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00006145 mPolicy.notifyDropWindow(token, x, y);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006146 };
6147 postCommandLocked(std::move(command));
Robert Carrf759f162018-11-13 12:57:11 -08006148}
6149
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006150void InputDispatcher::onAnrLocked(const std::shared_ptr<Connection>& connection) {
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006151 if (connection == nullptr) {
6152 LOG_ALWAYS_FATAL("Caller must check for nullness");
6153 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006154 // Since we are allowing the policy to extend the timeout, maybe the waitQueue
6155 // is already healthy again. Don't raise ANR in this situation
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006156 if (connection->waitQueue.empty()) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006157 ALOGI("Not raising ANR because the connection %s has recovered",
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006158 connection->inputChannel->getName().c_str());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006159 return;
6160 }
6161 /**
6162 * The "oldestEntry" is the entry that was first sent to the application. That entry, however,
6163 * may not be the one that caused the timeout to occur. One possibility is that window timeout
6164 * has changed. This could cause newer entries to time out before the already dispatched
6165 * entries. In that situation, the newest entries caused ANR. But in all likelihood, the app
6166 * processes the events linearly. So providing information about the oldest entry seems to be
6167 * most useful.
6168 */
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006169 DispatchEntry& oldestEntry = *connection->waitQueue.front();
6170 const nsecs_t currentWait = now() - oldestEntry.deliveryTime;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006171 std::string reason =
6172 android::base::StringPrintf("%s is not responding. Waited %" PRId64 "ms for %s",
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006173 connection->inputChannel->getName().c_str(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006174 ns2ms(currentWait),
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006175 oldestEntry.eventEntry->getDescription().c_str());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006176 sp<IBinder> connectionToken = connection->inputChannel->getConnectionToken();
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -06006177 updateLastAnrStateLocked(getWindowHandleLocked(connectionToken), reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006178
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006179 processConnectionUnresponsiveLocked(*connection, std::move(reason));
6180
6181 // Stop waking up for events on this connection, it is already unresponsive
6182 cancelEventsForAnrLocked(connection);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006183}
6184
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05006185void InputDispatcher::onAnrLocked(std::shared_ptr<InputApplicationHandle> application) {
6186 std::string reason =
6187 StringPrintf("%s does not have a focused window", application->getName().c_str());
6188 updateLastAnrStateLocked(*application, reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006189
Yabin Cui8eb9c552023-06-08 18:05:07 +00006190 auto command = [this, app = std::move(application)]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006191 scoped_unlock unlock(mLock);
Yabin Cuiced952f2023-06-09 21:12:51 +00006192 mPolicy.notifyNoFocusedWindowAnr(app);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006193 };
6194 postCommandLocked(std::move(command));
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00006195}
6196
chaviw98318de2021-05-19 16:45:23 -05006197void InputDispatcher::updateLastAnrStateLocked(const sp<WindowInfoHandle>& window,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006198 const std::string& reason) {
6199 const std::string windowLabel = getApplicationWindowLabel(nullptr, window);
6200 updateLastAnrStateLocked(windowLabel, reason);
6201}
6202
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05006203void InputDispatcher::updateLastAnrStateLocked(const InputApplicationHandle& application,
6204 const std::string& reason) {
6205 const std::string windowLabel = getApplicationWindowLabel(&application, nullptr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006206 updateLastAnrStateLocked(windowLabel, reason);
6207}
6208
6209void InputDispatcher::updateLastAnrStateLocked(const std::string& windowLabel,
6210 const std::string& reason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006211 // Capture a record of the InputDispatcher state at the time of the ANR.
Yi Kong9b14ac62018-07-17 13:48:38 -07006212 time_t t = time(nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006213 struct tm tm;
6214 localtime_r(&t, &tm);
6215 char timestr[64];
6216 strftime(timestr, sizeof(timestr), "%F %T", &tm);
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006217 mLastAnrState.clear();
6218 mLastAnrState += INDENT "ANR:\n";
6219 mLastAnrState += StringPrintf(INDENT2 "Time: %s\n", timestr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006220 mLastAnrState += StringPrintf(INDENT2 "Reason: %s\n", reason.c_str());
6221 mLastAnrState += StringPrintf(INDENT2 "Window: %s\n", windowLabel.c_str());
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006222 dumpDispatchStateLocked(mLastAnrState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006223}
6224
Prabir Pradhancef936d2021-07-21 16:17:52 +00006225void InputDispatcher::doInterceptKeyBeforeDispatchingCommand(const sp<IBinder>& focusedWindowToken,
6226 KeyEntry& entry) {
6227 const KeyEvent event = createKeyEvent(entry);
6228 nsecs_t delay = 0;
6229 { // release lock
6230 scoped_unlock unlock(mLock);
6231 android::base::Timer t;
Prabir Pradhana41d2442023-04-20 21:30:40 +00006232 delay = mPolicy.interceptKeyBeforeDispatching(focusedWindowToken, event, entry.policyFlags);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006233 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
6234 ALOGW("Excessive delay in interceptKeyBeforeDispatching; took %s ms",
6235 std::to_string(t.duration().count()).c_str());
6236 }
6237 } // acquire lock
Michael Wrightd02c5b62014-02-10 15:10:22 -08006238
6239 if (delay < 0) {
Michael Wright5caf55a2022-11-24 22:31:42 +00006240 entry.interceptKeyResult = KeyEntry::InterceptKeyResult::SKIP;
Prabir Pradhancef936d2021-07-21 16:17:52 +00006241 } else if (delay == 0) {
Michael Wright5caf55a2022-11-24 22:31:42 +00006242 entry.interceptKeyResult = KeyEntry::InterceptKeyResult::CONTINUE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006243 } else {
Michael Wright5caf55a2022-11-24 22:31:42 +00006244 entry.interceptKeyResult = KeyEntry::InterceptKeyResult::TRY_AGAIN_LATER;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006245 entry.interceptKeyWakeupTime = now() + delay;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006246 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006247}
6248
Prabir Pradhancef936d2021-07-21 16:17:52 +00006249void InputDispatcher::sendWindowUnresponsiveCommandLocked(const sp<IBinder>& token,
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00006250 std::optional<gui::Pid> pid,
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006251 std::string reason) {
Yabin Cui8eb9c552023-06-08 18:05:07 +00006252 auto command = [this, token, pid, r = std::move(reason)]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006253 scoped_unlock unlock(mLock);
Yabin Cuiced952f2023-06-09 21:12:51 +00006254 mPolicy.notifyWindowUnresponsive(token, pid, r);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006255 };
6256 postCommandLocked(std::move(command));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006257}
6258
Prabir Pradhanedd96402022-02-15 01:46:16 -08006259void InputDispatcher::sendWindowResponsiveCommandLocked(const sp<IBinder>& token,
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00006260 std::optional<gui::Pid> pid) {
Prabir Pradhanedd96402022-02-15 01:46:16 -08006261 auto command = [this, token, pid]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006262 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00006263 mPolicy.notifyWindowResponsive(token, pid);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006264 };
6265 postCommandLocked(std::move(command));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006266}
6267
6268/**
6269 * Tell the policy that a connection has become unresponsive so that it can start ANR.
6270 * Check whether the connection of interest is a monitor or a window, and add the corresponding
6271 * command entry to the command queue.
6272 */
6273void InputDispatcher::processConnectionUnresponsiveLocked(const Connection& connection,
6274 std::string reason) {
6275 const sp<IBinder>& connectionToken = connection.inputChannel->getConnectionToken();
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00006276 std::optional<gui::Pid> pid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006277 if (connection.monitor) {
6278 ALOGW("Monitor %s is unresponsive: %s", connection.inputChannel->getName().c_str(),
6279 reason.c_str());
Prabir Pradhanedd96402022-02-15 01:46:16 -08006280 pid = findMonitorPidByTokenLocked(connectionToken);
6281 } else {
6282 // The connection is a window
6283 ALOGW("Window %s is unresponsive: %s", connection.inputChannel->getName().c_str(),
6284 reason.c_str());
6285 const sp<WindowInfoHandle> handle = getWindowHandleLocked(connectionToken);
6286 if (handle != nullptr) {
6287 pid = handle->getInfo()->ownerPid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006288 }
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006289 }
Prabir Pradhanedd96402022-02-15 01:46:16 -08006290 sendWindowUnresponsiveCommandLocked(connectionToken, pid, std::move(reason));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006291}
6292
6293/**
6294 * Tell the policy that a connection has become responsive so that it can stop ANR.
6295 */
6296void InputDispatcher::processConnectionResponsiveLocked(const Connection& connection) {
6297 const sp<IBinder>& connectionToken = connection.inputChannel->getConnectionToken();
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00006298 std::optional<gui::Pid> pid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006299 if (connection.monitor) {
Prabir Pradhanedd96402022-02-15 01:46:16 -08006300 pid = findMonitorPidByTokenLocked(connectionToken);
6301 } else {
6302 // The connection is a window
6303 const sp<WindowInfoHandle> handle = getWindowHandleLocked(connectionToken);
6304 if (handle != nullptr) {
6305 pid = handle->getInfo()->ownerPid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006306 }
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006307 }
Prabir Pradhanedd96402022-02-15 01:46:16 -08006308 sendWindowResponsiveCommandLocked(connectionToken, pid);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006309}
6310
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006311bool InputDispatcher::afterKeyEventLockedInterruptable(
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006312 const std::shared_ptr<Connection>& connection, DispatchEntry& dispatchEntry,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006313 KeyEntry& keyEntry, bool handled) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006314 if (keyEntry.flags & AKEY_EVENT_FLAG_FALLBACK) {
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006315 if (!handled) {
6316 // Report the key as unhandled, since the fallback was not handled.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006317 mReporter->reportUnhandledKey(keyEntry.id);
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006318 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006319 return false;
6320 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006321
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006322 // Get the fallback key state.
6323 // Clear it out after dispatching the UP.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006324 int32_t originalKeyCode = keyEntry.keyCode;
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006325 std::optional<int32_t> fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006326 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006327 connection->inputState.removeFallbackKey(originalKeyCode);
6328 }
6329
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006330 if (handled || !dispatchEntry.hasForegroundTarget()) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006331 // If the application handles the original key for which we previously
6332 // generated a fallback or if the window is not a foreground window,
6333 // then cancel the associated fallback key, if any.
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006334 if (fallbackKeyCode) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006335 // Dispatch the unhandled key to the policy with the cancel flag.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006336 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6337 ALOGD("Unhandled key event: Asking policy to cancel fallback action. "
6338 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6339 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount,
6340 keyEntry.policyFlags);
6341 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006342 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006343 event.setFlags(event.getFlags() | AKEY_EVENT_FLAG_CANCELED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006344
6345 mLock.unlock();
6346
Prabir Pradhana41d2442023-04-20 21:30:40 +00006347 if (const auto unhandledKeyFallback =
6348 mPolicy.dispatchUnhandledKey(connection->inputChannel->getConnectionToken(),
6349 event, keyEntry.policyFlags);
6350 unhandledKeyFallback) {
6351 event = *unhandledKeyFallback;
6352 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006353
6354 mLock.lock();
6355
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006356 // Cancel the fallback key.
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006357 if (*fallbackKeyCode != AKEYCODE_UNKNOWN) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00006358 CancelationOptions options(CancelationOptions::Mode::CANCEL_FALLBACK_EVENTS,
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006359 "application handled the original non-fallback key "
6360 "or is no longer a foreground target, "
6361 "canceling previously dispatched fallback key");
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006362 options.keyCode = *fallbackKeyCode;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006363 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006364 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006365 connection->inputState.removeFallbackKey(originalKeyCode);
6366 }
6367 } else {
6368 // If the application did not handle a non-fallback key, first check
6369 // that we are in a good state to perform unhandled key event processing
6370 // Then ask the policy what to do with it.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006371 bool initialDown = keyEntry.action == AKEY_EVENT_ACTION_DOWN && keyEntry.repeatCount == 0;
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006372 if (!fallbackKeyCode && !initialDown) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006373 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6374 ALOGD("Unhandled key event: Skipping unhandled key event processing "
6375 "since this is not an initial down. "
6376 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6377 originalKeyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
6378 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006379 return false;
6380 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006381
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006382 // Dispatch the unhandled key to the policy.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006383 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6384 ALOGD("Unhandled key event: Asking policy to perform fallback action. "
6385 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6386 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
6387 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006388 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006389
6390 mLock.unlock();
6391
Prabir Pradhana41d2442023-04-20 21:30:40 +00006392 bool fallback = false;
6393 if (auto fb = mPolicy.dispatchUnhandledKey(connection->inputChannel->getConnectionToken(),
6394 event, keyEntry.policyFlags);
6395 fb) {
6396 fallback = true;
6397 event = *fb;
6398 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006399
6400 mLock.lock();
6401
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08006402 if (connection->status != Connection::Status::NORMAL) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006403 connection->inputState.removeFallbackKey(originalKeyCode);
6404 return false;
6405 }
6406
6407 // Latch the fallback keycode for this key on an initial down.
6408 // The fallback keycode cannot change at any other point in the lifecycle.
6409 if (initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006410 if (fallback) {
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006411 *fallbackKeyCode = event.getKeyCode();
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006412 } else {
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006413 *fallbackKeyCode = AKEYCODE_UNKNOWN;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006414 }
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006415 connection->inputState.setFallbackKey(originalKeyCode, *fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006416 }
6417
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006418 ALOG_ASSERT(fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006419
6420 // Cancel the fallback key if the policy decides not to send it anymore.
6421 // We will continue to dispatch the key to the policy but we will no
6422 // longer dispatch a fallback key to the application.
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006423 if (*fallbackKeyCode != AKEYCODE_UNKNOWN &&
6424 (!fallback || *fallbackKeyCode != event.getKeyCode())) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006425 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6426 if (fallback) {
6427 ALOGD("Unhandled key event: Policy requested to send key %d"
6428 "as a fallback for %d, but on the DOWN it had requested "
6429 "to send %d instead. Fallback canceled.",
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006430 event.getKeyCode(), originalKeyCode, *fallbackKeyCode);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006431 } else {
6432 ALOGD("Unhandled key event: Policy did not request fallback for %d, "
6433 "but on the DOWN it had requested to send %d. "
6434 "Fallback canceled.",
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006435 originalKeyCode, *fallbackKeyCode);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006436 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006437 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006438
Michael Wrightfb04fd52022-11-24 22:31:11 +00006439 CancelationOptions options(CancelationOptions::Mode::CANCEL_FALLBACK_EVENTS,
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006440 "canceling fallback, policy no longer desires it");
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006441 options.keyCode = *fallbackKeyCode;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006442 synthesizeCancelationEventsForConnectionLocked(connection, options);
6443
6444 fallback = false;
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006445 *fallbackKeyCode = AKEYCODE_UNKNOWN;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006446 if (keyEntry.action != AKEY_EVENT_ACTION_UP) {
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006447 connection->inputState.setFallbackKey(originalKeyCode, *fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006448 }
6449 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006450
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006451 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6452 {
6453 std::string msg;
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006454 const std::map<int32_t, int32_t>& fallbackKeys =
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006455 connection->inputState.getFallbackKeys();
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006456 for (const auto& [key, value] : fallbackKeys) {
6457 msg += StringPrintf(", %d->%d", key, value);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006458 }
6459 ALOGD("Unhandled key event: %zu currently tracked fallback keys%s.",
6460 fallbackKeys.size(), msg.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006461 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006462 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006463
6464 if (fallback) {
6465 // Restart the dispatch cycle using the fallback key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006466 keyEntry.eventTime = event.getEventTime();
6467 keyEntry.deviceId = event.getDeviceId();
6468 keyEntry.source = event.getSource();
6469 keyEntry.displayId = event.getDisplayId();
6470 keyEntry.flags = event.getFlags() | AKEY_EVENT_FLAG_FALLBACK;
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006471 keyEntry.keyCode = *fallbackKeyCode;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006472 keyEntry.scanCode = event.getScanCode();
6473 keyEntry.metaState = event.getMetaState();
6474 keyEntry.repeatCount = event.getRepeatCount();
6475 keyEntry.downTime = event.getDownTime();
6476 keyEntry.syntheticRepeat = false;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006477
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006478 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6479 ALOGD("Unhandled key event: Dispatching fallback key. "
6480 "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006481 originalKeyCode, *fallbackKeyCode, keyEntry.metaState);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006482 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006483 return true; // restart the event
6484 } else {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006485 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6486 ALOGD("Unhandled key event: No fallback key.");
6487 }
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006488
6489 // Report the key as unhandled, since there is no fallback key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006490 mReporter->reportUnhandledKey(keyEntry.id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006491 }
6492 }
6493 return false;
6494}
6495
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006496bool InputDispatcher::afterMotionEventLockedInterruptable(
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006497 const std::shared_ptr<Connection>& connection, DispatchEntry& dispatchEntry,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006498 MotionEntry& motionEntry, bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006499 return false;
6500}
6501
Michael Wrightd02c5b62014-02-10 15:10:22 -08006502void InputDispatcher::traceInboundQueueLengthLocked() {
6503 if (ATRACE_ENABLED()) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07006504 ATRACE_INT("iq", mInboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006505 }
6506}
6507
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006508void InputDispatcher::traceOutboundQueueLength(const Connection& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006509 if (ATRACE_ENABLED()) {
6510 char counterName[40];
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006511 snprintf(counterName, sizeof(counterName), "oq:%s", connection.getWindowName().c_str());
6512 ATRACE_INT(counterName, connection.outboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006513 }
6514}
6515
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006516void InputDispatcher::traceWaitQueueLength(const Connection& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006517 if (ATRACE_ENABLED()) {
6518 char counterName[40];
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006519 snprintf(counterName, sizeof(counterName), "wq:%s", connection.getWindowName().c_str());
6520 ATRACE_INT(counterName, connection.waitQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006521 }
6522}
6523
Siarhei Vishniakou5e20f272023-06-08 17:24:44 -07006524void InputDispatcher::dump(std::string& dump) const {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006525 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006526
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006527 dump += "Input Dispatcher State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08006528 dumpDispatchStateLocked(dump);
6529
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006530 if (!mLastAnrState.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006531 dump += "\nInput Dispatcher State at time of last ANR:\n";
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006532 dump += mLastAnrState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006533 }
6534}
6535
6536void InputDispatcher::monitor() {
6537 // Acquire and release the lock to ensure that the dispatcher has not deadlocked.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006538 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006539 mLooper->wake();
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006540 mDispatcherIsAlive.wait(_l);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006541}
6542
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08006543/**
6544 * Wake up the dispatcher and wait until it processes all events and commands.
6545 * The notification of mDispatcherEnteredIdle is guaranteed to happen after wake(), so
6546 * this method can be safely called from any thread, as long as you've ensured that
6547 * the work you are interested in completing has already been queued.
6548 */
Siarhei Vishniakoua66d65e2023-06-16 10:32:51 -07006549bool InputDispatcher::waitForIdle() const {
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08006550 /**
6551 * Timeout should represent the longest possible time that a device might spend processing
6552 * events and commands.
6553 */
6554 constexpr std::chrono::duration TIMEOUT = 100ms;
6555 std::unique_lock lock(mLock);
6556 mLooper->wake();
6557 std::cv_status result = mDispatcherEnteredIdle.wait_for(lock, TIMEOUT);
6558 return result == std::cv_status::no_timeout;
6559}
6560
Vishnu Naire798b472020-07-23 13:52:21 -07006561/**
6562 * Sets focus to the window identified by the token. This must be called
6563 * after updating any input window handles.
6564 *
6565 * Params:
6566 * request.token - input channel token used to identify the window that should gain focus.
6567 * request.focusedToken - the token that the caller expects currently to be focused. If the
6568 * specified token does not match the currently focused window, this request will be dropped.
6569 * If the specified focused token matches the currently focused window, the call will succeed.
6570 * Set this to "null" if this call should succeed no matter what the currently focused token is.
6571 * request.timestamp - SYSTEM_TIME_MONOTONIC timestamp in nanos set by the client (wm)
6572 * when requesting the focus change. This determines which request gets
6573 * precedence if there is a focus change request from another source such as pointer down.
6574 */
Vishnu Nair958da932020-08-21 17:12:37 -07006575void InputDispatcher::setFocusedWindow(const FocusRequest& request) {
6576 { // acquire lock
6577 std::scoped_lock _l(mLock);
Vishnu Nairc519ff72021-01-21 08:23:08 -08006578 std::optional<FocusResolver::FocusChanges> changes =
6579 mFocusResolver.setFocusedWindow(request, getWindowHandlesLocked(request.displayId));
6580 if (changes) {
6581 onFocusChangedLocked(*changes);
Vishnu Nair958da932020-08-21 17:12:37 -07006582 }
6583 } // release lock
6584 // Wake up poll loop since it may need to make new input dispatching choices.
6585 mLooper->wake();
6586}
6587
Vishnu Nairc519ff72021-01-21 08:23:08 -08006588void InputDispatcher::onFocusChangedLocked(const FocusResolver::FocusChanges& changes) {
6589 if (changes.oldFocus) {
6590 std::shared_ptr<InputChannel> focusedInputChannel = getInputChannelLocked(changes.oldFocus);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006591 if (focusedInputChannel) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00006592 CancelationOptions options(CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS,
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006593 "focus left window");
6594 synthesizeCancelationEventsForInputChannelLocked(focusedInputChannel, options);
Harry Cutts33476232023-01-30 19:57:29 +00006595 enqueueFocusEventLocked(changes.oldFocus, /*hasFocus=*/false, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006596 }
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006597 }
Vishnu Nairc519ff72021-01-21 08:23:08 -08006598 if (changes.newFocus) {
Siarhei Vishniakouc033dfb2023-10-03 10:45:16 -07006599 resetNoFocusedWindowTimeoutLocked();
Harry Cutts33476232023-01-30 19:57:29 +00006600 enqueueFocusEventLocked(changes.newFocus, /*hasFocus=*/true, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006601 }
6602
Prabir Pradhan99987712020-11-10 18:43:05 -08006603 // If a window has pointer capture, then it must have focus. We need to ensure that this
6604 // contract is upheld when pointer capture is being disabled due to a loss of window focus.
6605 // If the window loses focus before it loses pointer capture, then the window can be in a state
6606 // where it has pointer capture but not focus, violating the contract. Therefore we must
6607 // dispatch the pointer capture event before the focus event. Since focus events are added to
6608 // the front of the queue (above), we add the pointer capture event to the front of the queue
6609 // after the focus events are added. This ensures the pointer capture event ends up at the
6610 // front.
6611 disablePointerCaptureForcedLocked();
6612
Vishnu Nairc519ff72021-01-21 08:23:08 -08006613 if (mFocusedDisplayId == changes.displayId) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006614 sendFocusChangedCommandLocked(changes.oldFocus, changes.newFocus);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006615 }
6616}
Vishnu Nair958da932020-08-21 17:12:37 -07006617
Prabir Pradhan99987712020-11-10 18:43:05 -08006618void InputDispatcher::disablePointerCaptureForcedLocked() {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006619 if (!mCurrentPointerCaptureRequest.enable && !mWindowTokenWithPointerCapture) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006620 return;
6621 }
6622
6623 ALOGD_IF(DEBUG_FOCUS, "Disabling Pointer Capture because the window lost focus.");
6624
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006625 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006626 setPointerCaptureLocked(false);
6627 }
6628
6629 if (!mWindowTokenWithPointerCapture) {
6630 // No need to send capture changes because no window has capture.
6631 return;
6632 }
6633
6634 if (mPendingEvent != nullptr) {
6635 // Move the pending event to the front of the queue. This will give the chance
6636 // for the pending event to be dropped if it is a captured event.
6637 mInboundQueue.push_front(mPendingEvent);
6638 mPendingEvent = nullptr;
6639 }
6640
6641 auto entry = std::make_unique<PointerCaptureChangedEntry>(mIdGenerator.nextId(), now(),
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006642 mCurrentPointerCaptureRequest);
Prabir Pradhan99987712020-11-10 18:43:05 -08006643 mInboundQueue.push_front(std::move(entry));
6644}
6645
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006646void InputDispatcher::setPointerCaptureLocked(bool enable) {
6647 mCurrentPointerCaptureRequest.enable = enable;
6648 mCurrentPointerCaptureRequest.seq++;
6649 auto command = [this, request = mCurrentPointerCaptureRequest]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006650 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00006651 mPolicy.setPointerCapture(request);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006652 };
6653 postCommandLocked(std::move(command));
Prabir Pradhan99987712020-11-10 18:43:05 -08006654}
6655
Vishnu Nair599f1412021-06-21 10:39:58 -07006656void InputDispatcher::displayRemoved(int32_t displayId) {
6657 { // acquire lock
6658 std::scoped_lock _l(mLock);
6659 // Set an empty list to remove all handles from the specific display.
Harry Cutts101ee9b2023-07-06 18:04:14 +00006660 setInputWindowsLocked(/*windowInfoHandles=*/{}, displayId);
Vishnu Nair599f1412021-06-21 10:39:58 -07006661 setFocusedApplicationLocked(displayId, nullptr);
6662 // Call focus resolver to clean up stale requests. This must be called after input windows
6663 // have been removed for the removed display.
6664 mFocusResolver.displayRemoved(displayId);
Christine Franksb768bb42021-11-29 12:11:31 -08006665 // Reset pointer capture eligibility, regardless of previous state.
6666 std::erase(mIneligibleDisplaysForPointerCapture, displayId);
Antonio Kantek15beb512022-06-13 22:35:41 +00006667 // Remove the associated touch mode state.
6668 mTouchModePerDisplay.erase(displayId);
Siarhei Vishniakou5c02a712023-05-15 15:45:02 -07006669 mVerifiersByDisplay.erase(displayId);
Vishnu Nair599f1412021-06-21 10:39:58 -07006670 } // release lock
6671
6672 // Wake up poll loop since it may need to make new input dispatching choices.
6673 mLooper->wake();
6674}
6675
Patrick Williamsd828f302023-04-28 17:52:08 -05006676void InputDispatcher::onWindowInfosChanged(const gui::WindowInfosUpdate& update) {
chaviw15fab6f2021-06-07 14:15:52 -05006677 // The listener sends the windows as a flattened array. Separate the windows by display for
6678 // more convenient parsing.
6679 std::unordered_map<int32_t, std::vector<sp<WindowInfoHandle>>> handlesPerDisplay;
Patrick Williamsd828f302023-04-28 17:52:08 -05006680 for (const auto& info : update.windowInfos) {
chaviw15fab6f2021-06-07 14:15:52 -05006681 handlesPerDisplay.emplace(info.displayId, std::vector<sp<WindowInfoHandle>>());
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07006682 handlesPerDisplay[info.displayId].push_back(sp<WindowInfoHandle>::make(info));
chaviw15fab6f2021-06-07 14:15:52 -05006683 }
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006684
6685 { // acquire lock
6686 std::scoped_lock _l(mLock);
Prabir Pradhan814fe082022-07-22 20:22:18 +00006687
6688 // Ensure that we have an entry created for all existing displays so that if a displayId has
6689 // no windows, we can tell that the windows were removed from the display.
6690 for (const auto& [displayId, _] : mWindowHandlesByDisplay) {
6691 handlesPerDisplay[displayId];
6692 }
6693
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006694 mDisplayInfos.clear();
Patrick Williamsd828f302023-04-28 17:52:08 -05006695 for (const auto& displayInfo : update.displayInfos) {
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006696 mDisplayInfos.emplace(displayInfo.displayId, displayInfo);
6697 }
6698
6699 for (const auto& [displayId, handles] : handlesPerDisplay) {
6700 setInputWindowsLocked(handles, displayId);
6701 }
Patrick Williams9464b2c2023-05-23 11:22:04 -05006702
6703 if (update.vsyncId < mWindowInfosVsyncId) {
6704 ALOGE("Received out of order window infos update. Last update vsync id: %" PRId64
6705 ", current update vsync id: %" PRId64,
6706 mWindowInfosVsyncId, update.vsyncId);
6707 }
6708 mWindowInfosVsyncId = update.vsyncId;
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006709 }
6710 // Wake up poll loop since it may need to make new input dispatching choices.
6711 mLooper->wake();
chaviw15fab6f2021-06-07 14:15:52 -05006712}
6713
Vishnu Nair062a8672021-09-03 16:07:44 -07006714bool InputDispatcher::shouldDropInput(
6715 const EventEntry& entry, const sp<android::gui::WindowInfoHandle>& windowHandle) const {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006716 if (windowHandle->getInfo()->inputConfig.test(WindowInfo::InputConfig::DROP_INPUT) ||
6717 (windowHandle->getInfo()->inputConfig.test(
6718 WindowInfo::InputConfig::DROP_INPUT_IF_OBSCURED) &&
Vishnu Nair062a8672021-09-03 16:07:44 -07006719 isWindowObscuredLocked(windowHandle))) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006720 ALOGW("Dropping %s event targeting %s as requested by the input configuration {%s} on "
6721 "display %" PRId32 ".",
Vishnu Nair062a8672021-09-03 16:07:44 -07006722 ftl::enum_string(entry.type).c_str(), windowHandle->getName().c_str(),
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006723 windowHandle->getInfo()->inputConfig.string().c_str(),
Vishnu Nair062a8672021-09-03 16:07:44 -07006724 windowHandle->getInfo()->displayId);
6725 return true;
6726 }
6727 return false;
6728}
6729
Siarhei Vishniakou18050092021-09-01 13:32:49 -07006730void InputDispatcher::DispatcherWindowListener::onWindowInfosChanged(
Patrick Williamsd828f302023-04-28 17:52:08 -05006731 const gui::WindowInfosUpdate& update) {
6732 mDispatcher.onWindowInfosChanged(update);
Siarhei Vishniakou18050092021-09-01 13:32:49 -07006733}
6734
Arthur Hungdfd528e2021-12-08 13:23:04 +00006735void InputDispatcher::cancelCurrentTouch() {
6736 {
6737 std::scoped_lock _l(mLock);
6738 ALOGD("Canceling all ongoing pointer gestures on all displays.");
Michael Wrightfb04fd52022-11-24 22:31:11 +00006739 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
Arthur Hungdfd528e2021-12-08 13:23:04 +00006740 "cancel current touch");
6741 synthesizeCancelationEventsForAllConnectionsLocked(options);
6742
6743 mTouchStatesByDisplay.clear();
Arthur Hungdfd528e2021-12-08 13:23:04 +00006744 }
6745 // Wake up poll loop since there might be work to do.
6746 mLooper->wake();
6747}
6748
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006749void InputDispatcher::setMonitorDispatchingTimeoutForTest(std::chrono::nanoseconds timeout) {
6750 std::scoped_lock _l(mLock);
6751 mMonitorDispatchingTimeout = timeout;
6752}
6753
Arthur Hungc539dbb2022-12-08 07:45:36 +00006754void InputDispatcher::slipWallpaperTouch(ftl::Flags<InputTarget::Flags> targetFlags,
6755 const sp<WindowInfoHandle>& oldWindowHandle,
6756 const sp<WindowInfoHandle>& newWindowHandle,
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07006757 TouchState& state, int32_t deviceId, int32_t pointerId,
Siarhei Vishniakoubf880522023-05-01 11:03:22 -07006758 std::vector<InputTarget>& targets) const {
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08006759 std::bitset<MAX_POINTER_ID + 1> pointerIds;
6760 pointerIds.set(pointerId);
Arthur Hungc539dbb2022-12-08 07:45:36 +00006761 const bool oldHasWallpaper = oldWindowHandle->getInfo()->inputConfig.test(
6762 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
6763 const bool newHasWallpaper = targetFlags.test(InputTarget::Flags::FOREGROUND) &&
6764 newWindowHandle->getInfo()->inputConfig.test(
6765 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
6766 const sp<WindowInfoHandle> oldWallpaper =
6767 oldHasWallpaper ? state.getWallpaperWindow() : nullptr;
6768 const sp<WindowInfoHandle> newWallpaper =
6769 newHasWallpaper ? findWallpaperWindowBelow(newWindowHandle) : nullptr;
6770 if (oldWallpaper == newWallpaper) {
6771 return;
6772 }
6773
6774 if (oldWallpaper != nullptr) {
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08006775 const TouchedWindow& oldTouchedWindow = state.getTouchedWindow(oldWallpaper);
6776 addWindowTargetLocked(oldWallpaper,
6777 oldTouchedWindow.targetFlags |
6778 InputTarget::Flags::DISPATCH_AS_SLIPPERY_EXIT,
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07006779 pointerIds, oldTouchedWindow.getDownTimeInTarget(deviceId), targets);
6780 state.removeTouchingPointerFromWindow(deviceId, pointerId, oldWallpaper);
Arthur Hungc539dbb2022-12-08 07:45:36 +00006781 }
6782
6783 if (newWallpaper != nullptr) {
6784 state.addOrUpdateWindow(newWallpaper,
6785 InputTarget::Flags::DISPATCH_AS_SLIPPERY_ENTER |
6786 InputTarget::Flags::WINDOW_IS_OBSCURED |
6787 InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED,
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07006788 deviceId, pointerIds);
Arthur Hungc539dbb2022-12-08 07:45:36 +00006789 }
6790}
6791
6792void InputDispatcher::transferWallpaperTouch(ftl::Flags<InputTarget::Flags> oldTargetFlags,
6793 ftl::Flags<InputTarget::Flags> newTargetFlags,
6794 const sp<WindowInfoHandle> fromWindowHandle,
6795 const sp<WindowInfoHandle> toWindowHandle,
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07006796 TouchState& state, int32_t deviceId,
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08006797 std::bitset<MAX_POINTER_ID + 1> pointerIds) {
Arthur Hungc539dbb2022-12-08 07:45:36 +00006798 const bool oldHasWallpaper = oldTargetFlags.test(InputTarget::Flags::FOREGROUND) &&
6799 fromWindowHandle->getInfo()->inputConfig.test(
6800 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
6801 const bool newHasWallpaper = newTargetFlags.test(InputTarget::Flags::FOREGROUND) &&
6802 toWindowHandle->getInfo()->inputConfig.test(
6803 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
6804
6805 const sp<WindowInfoHandle> oldWallpaper =
6806 oldHasWallpaper ? state.getWallpaperWindow() : nullptr;
6807 const sp<WindowInfoHandle> newWallpaper =
6808 newHasWallpaper ? findWallpaperWindowBelow(toWindowHandle) : nullptr;
6809 if (oldWallpaper == newWallpaper) {
6810 return;
6811 }
6812
6813 if (oldWallpaper != nullptr) {
6814 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
6815 "transferring touch focus to another window");
6816 state.removeWindowByToken(oldWallpaper->getToken());
6817 synthesizeCancelationEventsForWindowLocked(oldWallpaper, options);
6818 }
6819
6820 if (newWallpaper != nullptr) {
6821 nsecs_t downTimeInTarget = now();
6822 ftl::Flags<InputTarget::Flags> wallpaperFlags =
6823 oldTargetFlags & (InputTarget::Flags::SPLIT | InputTarget::Flags::DISPATCH_AS_IS);
6824 wallpaperFlags |= InputTarget::Flags::WINDOW_IS_OBSCURED |
6825 InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED;
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07006826 state.addOrUpdateWindow(newWallpaper, wallpaperFlags, deviceId, pointerIds,
6827 downTimeInTarget);
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006828 std::shared_ptr<Connection> wallpaperConnection =
6829 getConnectionLocked(newWallpaper->getToken());
Arthur Hungc539dbb2022-12-08 07:45:36 +00006830 if (wallpaperConnection != nullptr) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006831 std::shared_ptr<Connection> toConnection =
6832 getConnectionLocked(toWindowHandle->getToken());
Arthur Hungc539dbb2022-12-08 07:45:36 +00006833 toConnection->inputState.mergePointerStateTo(wallpaperConnection->inputState);
6834 synthesizePointerDownEventsForConnectionLocked(downTimeInTarget, wallpaperConnection,
6835 wallpaperFlags);
6836 }
6837 }
6838}
6839
6840sp<WindowInfoHandle> InputDispatcher::findWallpaperWindowBelow(
6841 const sp<WindowInfoHandle>& windowHandle) const {
6842 const std::vector<sp<WindowInfoHandle>>& windowHandles =
6843 getWindowHandlesLocked(windowHandle->getInfo()->displayId);
6844 bool foundWindow = false;
6845 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
6846 if (!foundWindow && otherHandle != windowHandle) {
6847 continue;
6848 }
6849 if (windowHandle == otherHandle) {
6850 foundWindow = true;
6851 continue;
6852 }
6853
6854 if (otherHandle->getInfo()->inputConfig.test(WindowInfo::InputConfig::IS_WALLPAPER)) {
6855 return otherHandle;
6856 }
6857 }
6858 return nullptr;
6859}
6860
Nergi Rahardi730cf3c2023-04-13 12:41:17 +09006861void InputDispatcher::setKeyRepeatConfiguration(nsecs_t timeout, nsecs_t delay) {
6862 std::scoped_lock _l(mLock);
6863
6864 mConfig.keyRepeatTimeout = timeout;
6865 mConfig.keyRepeatDelay = delay;
6866}
6867
Garfield Tane84e6f92019-08-29 17:28:41 -07006868} // namespace android::inputdispatcher