blob: 1cf2b5ffe0c6fc58282f629241fe66709d54003c [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 Vishniakou31977182022-09-30 08:51:23 -070029#if defined(__ANDROID__)
chaviw15fab6f2021-06-07 14:15:52 -050030#include <gui/SurfaceComposerClient.h>
Siarhei Vishniakou31977182022-09-30 08:51:23 -070031#endif
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -080032#include <input/InputDevice.h>
Siarhei Vishniakou6e1e9872022-11-08 17:51:35 -080033#include <input/PrintTools.h>
tyiu1573a672023-02-21 22:38:32 +000034#include <openssl/mem.h>
Garfield Tan0fc2fa72019-08-29 17:22:15 -070035#include <powermanager/PowerManager.h>
Michael Wright44753b12020-07-08 13:48:11 +010036#include <unistd.h>
Garfield Tan0fc2fa72019-08-29 17:22:15 -070037#include <utils/Trace.h>
Michael Wrightd02c5b62014-02-10 15:10:22 -080038
Michael Wright44753b12020-07-08 13:48:11 +010039#include <cerrno>
40#include <cinttypes>
41#include <climits>
42#include <cstddef>
43#include <ctime>
44#include <queue>
45#include <sstream>
46
47#include "Connection.h"
Arthur Hung1a1007b2022-05-11 07:15:01 +000048#include "DebugConfig.h"
Chris Yef59a2f42020-10-16 12:55:26 -070049#include "InputDispatcher.h"
Michael Wright44753b12020-07-08 13:48:11 +010050
Michael Wrightd02c5b62014-02-10 15:10:22 -080051#define INDENT " "
52#define INDENT2 " "
53#define INDENT3 " "
54#define INDENT4 " "
55
Siarhei Vishniakou253f4642022-11-09 13:42:06 -080056using namespace android::ftl::flag_operators;
Siarhei Vishniakou6773db62023-04-21 11:30:20 -070057using android::base::Error;
Peter Collingbourneb04b9b82021-02-08 12:09:47 -080058using android::base::HwTimeoutMultiplier;
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +000059using android::base::Result;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080060using android::base::StringPrintf;
Prabir Pradhan48f8cb92021-08-26 14:05:36 -070061using android::gui::DisplayInfo;
chaviw98318de2021-05-19 16:45:23 -050062using android::gui::FocusRequest;
63using android::gui::TouchOcclusionMode;
64using android::gui::WindowInfo;
65using android::gui::WindowInfoHandle;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -080066using android::os::InputEventInjectionResult;
67using android::os::InputEventInjectionSync;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080068
Garfield Tane84e6f92019-08-29 17:28:41 -070069namespace android::inputdispatcher {
Michael Wrightd02c5b62014-02-10 15:10:22 -080070
Prabir Pradhancef936d2021-07-21 16:17:52 +000071namespace {
Prabir Pradhancef936d2021-07-21 16:17:52 +000072// Temporarily releases a held mutex for the lifetime of the instance.
73// Named to match std::scoped_lock
74class scoped_unlock {
75public:
76 explicit scoped_unlock(std::mutex& mutex) : mMutex(mutex) { mMutex.unlock(); }
77 ~scoped_unlock() { mMutex.lock(); }
78
79private:
80 std::mutex& mMutex;
81};
82
Michael Wrightd02c5b62014-02-10 15:10:22 -080083// Default input dispatching timeout if there is no focused application or paused window
84// from which to determine an appropriate dispatching timeout.
Peter Collingbourneb04b9b82021-02-08 12:09:47 -080085const std::chrono::duration DEFAULT_INPUT_DISPATCHING_TIMEOUT = std::chrono::milliseconds(
86 android::os::IInputConstants::UNMULTIPLIED_DEFAULT_DISPATCHING_TIMEOUT_MILLIS *
87 HwTimeoutMultiplier());
Michael Wrightd02c5b62014-02-10 15:10:22 -080088
89// Amount of time to allow for all pending events to be processed when an app switch
90// key is on the way. This is used to preempt input dispatch and drop input events
91// when an application takes too long to respond and the user has pressed an app switch key.
Michael Wright2b3c3302018-03-02 17:19:13 +000092constexpr nsecs_t APP_SWITCH_TIMEOUT = 500 * 1000000LL; // 0.5sec
Michael Wrightd02c5b62014-02-10 15:10:22 -080093
Siarhei Vishniakou289e9242022-02-15 14:50:16 -080094const std::chrono::duration STALE_EVENT_TIMEOUT = std::chrono::seconds(10) * HwTimeoutMultiplier();
Michael Wrightd02c5b62014-02-10 15:10:22 -080095
Michael Wrightd02c5b62014-02-10 15:10:22 -080096// 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 +000097constexpr nsecs_t SLOW_EVENT_PROCESSING_WARNING_TIMEOUT = 2000 * 1000000LL; // 2sec
98
99// Log a warning when an interception call takes longer than this to process.
100constexpr std::chrono::milliseconds SLOW_INTERCEPTION_THRESHOLD = 50ms;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800101
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700102// Additional key latency in case a connection is still processing some motion events.
103// This will help with the case when a user touched a button that opens a new window,
104// and gives us the chance to dispatch the key to this new window.
105constexpr std::chrono::nanoseconds KEY_WAITING_FOR_EVENTS_TIMEOUT = 500ms;
106
Michael Wrightd02c5b62014-02-10 15:10:22 -0800107// Number of recent events to keep for debugging purposes.
Michael Wright2b3c3302018-03-02 17:19:13 +0000108constexpr size_t RECENT_QUEUE_MAX_SIZE = 10;
109
Antonio Kantekea47acb2021-12-23 12:41:25 -0800110// Event log tags. See EventLogTags.logtags for reference.
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +0000111constexpr int LOGTAG_INPUT_INTERACTION = 62000;
112constexpr int LOGTAG_INPUT_FOCUS = 62001;
Arthur Hungb3307ee2021-10-14 10:57:37 +0000113constexpr int LOGTAG_INPUT_CANCEL = 62003;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +0000114
Prabir Pradhan33e3baa2022-12-06 20:30:22 +0000115const ui::Transform kIdentityTransform;
116
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000117inline nsecs_t now() {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800118 return systemTime(SYSTEM_TIME_MONOTONIC);
119}
120
Siarhei Vishniakou63b63612023-04-12 11:00:23 -0700121inline const std::string binderToString(const sp<IBinder>& binder) {
Bernardo Rufino49d99e42021-01-18 15:16:59 +0000122 if (binder == nullptr) {
123 return "<null>";
124 }
125 return StringPrintf("%p", binder.get());
126}
127
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000128inline int32_t getMotionEventActionPointerIndex(int32_t action) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700129 return (action & AMOTION_EVENT_ACTION_POINTER_INDEX_MASK) >>
130 AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800131}
132
Siarhei Vishniakou6773db62023-04-21 11:30:20 -0700133Result<void> checkKeyAction(int32_t action) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800134 switch (action) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700135 case AKEY_EVENT_ACTION_DOWN:
136 case AKEY_EVENT_ACTION_UP:
Siarhei Vishniakou6773db62023-04-21 11:30:20 -0700137 return {};
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700138 default:
Siarhei Vishniakou6773db62023-04-21 11:30:20 -0700139 return Error() << "Key event has invalid action code " << action;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800140 }
141}
142
Siarhei Vishniakou6773db62023-04-21 11:30:20 -0700143Result<void> validateKeyEvent(int32_t action) {
144 return checkKeyAction(action);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800145}
146
Siarhei Vishniakou6773db62023-04-21 11:30:20 -0700147Result<void> checkMotionAction(int32_t action, int32_t actionButton, int32_t pointerCount) {
Siarhei Vishniakou2f61bdc2022-12-02 08:55:51 -0800148 switch (MotionEvent::getActionMasked(action)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700149 case AMOTION_EVENT_ACTION_DOWN:
Siarhei Vishniakou6773db62023-04-21 11:30:20 -0700150 case AMOTION_EVENT_ACTION_UP: {
151 if (pointerCount != 1) {
152 return Error() << "invalid pointer count " << pointerCount;
153 }
154 return {};
155 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700156 case AMOTION_EVENT_ACTION_MOVE:
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700157 case AMOTION_EVENT_ACTION_HOVER_ENTER:
158 case AMOTION_EVENT_ACTION_HOVER_MOVE:
Siarhei Vishniakou6773db62023-04-21 11:30:20 -0700159 case AMOTION_EVENT_ACTION_HOVER_EXIT: {
160 if (pointerCount < 1) {
161 return Error() << "invalid pointer count " << pointerCount;
162 }
163 return {};
164 }
Siarhei Vishniakou2f61bdc2022-12-02 08:55:51 -0800165 case AMOTION_EVENT_ACTION_CANCEL:
166 case AMOTION_EVENT_ACTION_OUTSIDE:
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700167 case AMOTION_EVENT_ACTION_SCROLL:
Siarhei Vishniakou6773db62023-04-21 11:30:20 -0700168 return {};
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700169 case AMOTION_EVENT_ACTION_POINTER_DOWN:
170 case AMOTION_EVENT_ACTION_POINTER_UP: {
Siarhei Vishniakou2f61bdc2022-12-02 08:55:51 -0800171 const int32_t index = MotionEvent::getActionIndex(action);
Siarhei Vishniakou6773db62023-04-21 11:30:20 -0700172 if (index < 0) {
173 return Error() << "invalid index " << index << " for "
174 << MotionEvent::actionToString(action);
175 }
176 if (index >= pointerCount) {
177 return Error() << "invalid index " << index << " for pointerCount " << pointerCount;
178 }
179 if (pointerCount <= 1) {
180 return Error() << "invalid pointer count " << pointerCount << " for "
181 << MotionEvent::actionToString(action);
182 }
183 return {};
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700184 }
185 case AMOTION_EVENT_ACTION_BUTTON_PRESS:
Siarhei Vishniakou6773db62023-04-21 11:30:20 -0700186 case AMOTION_EVENT_ACTION_BUTTON_RELEASE: {
187 if (actionButton == 0) {
188 return Error() << "action button should be nonzero for "
189 << MotionEvent::actionToString(action);
190 }
191 return {};
192 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700193 default:
Siarhei Vishniakou6773db62023-04-21 11:30:20 -0700194 return Error() << "invalid action " << action;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800195 }
196}
197
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000198int64_t millis(std::chrono::nanoseconds t) {
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -0500199 return std::chrono::duration_cast<std::chrono::milliseconds>(t).count();
200}
201
Siarhei Vishniakou6773db62023-04-21 11:30:20 -0700202Result<void> validateMotionEvent(int32_t action, int32_t actionButton, size_t pointerCount,
203 const PointerProperties* pointerProperties) {
204 Result<void> actionCheck = checkMotionAction(action, actionButton, pointerCount);
205 if (!actionCheck.ok()) {
206 return actionCheck;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800207 }
208 if (pointerCount < 1 || pointerCount > MAX_POINTERS) {
Siarhei Vishniakou6773db62023-04-21 11:30:20 -0700209 return Error() << "Motion event has invalid pointer count " << pointerCount
210 << "; value must be between 1 and " << MAX_POINTERS << ".";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800211 }
Siarhei Vishniakou8a878352023-01-30 14:05:01 -0800212 std::bitset<MAX_POINTER_ID + 1> pointerIdBits;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800213 for (size_t i = 0; i < pointerCount; i++) {
214 int32_t id = pointerProperties[i].id;
215 if (id < 0 || id > MAX_POINTER_ID) {
Siarhei Vishniakou6773db62023-04-21 11:30:20 -0700216 return Error() << "Motion event has invalid pointer id " << id
217 << "; value must be between 0 and " << MAX_POINTER_ID;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800218 }
Siarhei Vishniakou8a878352023-01-30 14:05:01 -0800219 if (pointerIdBits.test(id)) {
Siarhei Vishniakou6773db62023-04-21 11:30:20 -0700220 return Error() << "Motion event has duplicate pointer id " << id;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800221 }
Siarhei Vishniakou8a878352023-01-30 14:05:01 -0800222 pointerIdBits.set(id);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800223 }
Siarhei Vishniakou6773db62023-04-21 11:30:20 -0700224 return {};
225}
226
227Result<void> validateInputEvent(const InputEvent& event) {
228 switch (event.getType()) {
229 case InputEventType::KEY: {
230 const KeyEvent& key = static_cast<const KeyEvent&>(event);
231 const int32_t action = key.getAction();
232 return validateKeyEvent(action);
233 }
234 case InputEventType::MOTION: {
235 const MotionEvent& motion = static_cast<const MotionEvent&>(event);
236 const int32_t action = motion.getAction();
237 const size_t pointerCount = motion.getPointerCount();
238 const PointerProperties* pointerProperties = motion.getPointerProperties();
239 const int32_t actionButton = motion.getActionButton();
240 return validateMotionEvent(action, actionButton, pointerCount, pointerProperties);
241 }
242 default: {
243 return {};
244 }
245 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800246}
247
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000248std::string dumpRegion(const Region& region) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800249 if (region.isEmpty()) {
Bernardo Rufino53fc31e2020-11-03 11:01:07 +0000250 return "<empty>";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800251 }
252
Bernardo Rufino53fc31e2020-11-03 11:01:07 +0000253 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800254 bool first = true;
255 Region::const_iterator cur = region.begin();
256 Region::const_iterator const tail = region.end();
257 while (cur != tail) {
258 if (first) {
259 first = false;
260 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800261 dump += "|";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800262 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800263 dump += StringPrintf("[%d,%d][%d,%d]", cur->left, cur->top, cur->right, cur->bottom);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800264 cur++;
265 }
Bernardo Rufino53fc31e2020-11-03 11:01:07 +0000266 return dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800267}
268
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000269std::string dumpQueue(const std::deque<DispatchEntry*>& queue, nsecs_t currentTime) {
Siarhei Vishniakou14411c92020-09-18 21:15:05 -0500270 constexpr size_t maxEntries = 50; // max events to print
271 constexpr size_t skipBegin = maxEntries / 2;
272 const size_t skipEnd = queue.size() - maxEntries / 2;
273 // skip from maxEntries / 2 ... size() - maxEntries/2
274 // only print from 0 .. skipBegin and then from skipEnd .. size()
275
276 std::string dump;
277 for (size_t i = 0; i < queue.size(); i++) {
278 const DispatchEntry& entry = *queue[i];
279 if (i >= skipBegin && i < skipEnd) {
280 dump += StringPrintf(INDENT4 "<skipped %zu entries>\n", skipEnd - skipBegin);
281 i = skipEnd - 1; // it will be incremented to "skipEnd" by 'continue'
282 continue;
283 }
284 dump.append(INDENT4);
285 dump += entry.eventEntry->getDescription();
Siarhei Vishniakou253f4642022-11-09 13:42:06 -0800286 dump += StringPrintf(", seq=%" PRIu32 ", targetFlags=%s, resolvedAction=%d, age=%" PRId64
287 "ms",
288 entry.seq, entry.targetFlags.string().c_str(), entry.resolvedAction,
Siarhei Vishniakou14411c92020-09-18 21:15:05 -0500289 ns2ms(currentTime - entry.eventEntry->eventTime));
290 if (entry.deliveryTime != 0) {
291 // This entry was delivered, so add information on how long we've been waiting
292 dump += StringPrintf(", wait=%" PRId64 "ms", ns2ms(currentTime - entry.deliveryTime));
293 }
294 dump.append("\n");
295 }
296 return dump;
297}
298
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -0700299/**
300 * Find the entry in std::unordered_map by key, and return it.
301 * If the entry is not found, return a default constructed entry.
302 *
303 * Useful when the entries are vectors, since an empty vector will be returned
304 * if the entry is not found.
305 * Also useful when the entries are sp<>. If an entry is not found, nullptr is returned.
306 */
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700307template <typename K, typename V>
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000308V getValueByKey(const std::unordered_map<K, V>& map, K key) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -0700309 auto it = map.find(key);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700310 return it != map.end() ? it->second : V{};
Tiger Huang721e26f2018-07-24 22:26:19 +0800311}
312
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000313bool haveSameToken(const sp<WindowInfoHandle>& first, const sp<WindowInfoHandle>& second) {
chaviwaf87b3e2019-10-01 16:59:28 -0700314 if (first == second) {
315 return true;
316 }
317
318 if (first == nullptr || second == nullptr) {
319 return false;
320 }
321
322 return first->getToken() == second->getToken();
323}
324
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000325bool haveSameApplicationToken(const WindowInfo* first, const WindowInfo* second) {
Bernardo Rufino1ff9d592021-01-18 16:58:57 +0000326 if (first == nullptr || second == nullptr) {
327 return false;
328 }
329 return first->applicationInfo.token != nullptr &&
330 first->applicationInfo.token == second->applicationInfo.token;
331}
332
Siarhei Vishniakou8a878352023-01-30 14:05:01 -0800333template <typename T>
334size_t firstMarkedBit(T set) {
335 // TODO: replace with std::countr_zero from <bit> when that's available
336 LOG_ALWAYS_FATAL_IF(set.none());
337 size_t i = 0;
338 while (!set.test(i)) {
339 i++;
340 }
341 return i;
342}
343
Siarhei Vishniakou253f4642022-11-09 13:42:06 -0800344std::unique_ptr<DispatchEntry> createDispatchEntry(
345 const InputTarget& inputTarget, std::shared_ptr<EventEntry> eventEntry,
346 ftl::Flags<InputTarget::Flags> inputTargetFlags) {
chaviw1ff3d1e2020-07-01 15:53:47 -0700347 if (inputTarget.useDefaultPointerTransform()) {
348 const ui::Transform& transform = inputTarget.getDefaultPointerTransform();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700349 return std::make_unique<DispatchEntry>(eventEntry, inputTargetFlags, transform,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700350 inputTarget.displayTransform,
351 inputTarget.globalScaleFactor);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000352 }
353
354 ALOG_ASSERT(eventEntry->type == EventEntry::Type::MOTION);
355 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(*eventEntry);
356
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700357 std::vector<PointerCoords> pointerCoords;
358 pointerCoords.resize(motionEntry.pointerCount);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000359
360 // Use the first pointer information to normalize all other pointers. This could be any pointer
361 // as long as all other pointers are normalized to the same value and the final DispatchEntry
chaviw1ff3d1e2020-07-01 15:53:47 -0700362 // uses the transform for the normalized pointer.
363 const ui::Transform& firstPointerTransform =
Siarhei Vishniakou8a878352023-01-30 14:05:01 -0800364 inputTarget.pointerTransforms[firstMarkedBit(inputTarget.pointerIds)];
chaviw1ff3d1e2020-07-01 15:53:47 -0700365 ui::Transform inverseFirstTransform = firstPointerTransform.inverse();
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000366
367 // Iterate through all pointers in the event to normalize against the first.
368 for (uint32_t pointerIndex = 0; pointerIndex < motionEntry.pointerCount; pointerIndex++) {
369 const PointerProperties& pointerProperties = motionEntry.pointerProperties[pointerIndex];
370 uint32_t pointerId = uint32_t(pointerProperties.id);
chaviw1ff3d1e2020-07-01 15:53:47 -0700371 const ui::Transform& currTransform = inputTarget.pointerTransforms[pointerId];
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000372
373 pointerCoords[pointerIndex].copyFrom(motionEntry.pointerCoords[pointerIndex]);
chaviw1ff3d1e2020-07-01 15:53:47 -0700374 // First, apply the current pointer's transform to update the coordinates into
375 // window space.
376 pointerCoords[pointerIndex].transform(currTransform);
377 // Next, apply the inverse transform of the normalized coordinates so the
378 // current coordinates are transformed into the normalized coordinate space.
379 pointerCoords[pointerIndex].transform(inverseFirstTransform);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000380 }
381
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700382 std::unique_ptr<MotionEntry> combinedMotionEntry =
383 std::make_unique<MotionEntry>(motionEntry.id, motionEntry.eventTime,
384 motionEntry.deviceId, motionEntry.source,
385 motionEntry.displayId, motionEntry.policyFlags,
386 motionEntry.action, motionEntry.actionButton,
387 motionEntry.flags, motionEntry.metaState,
388 motionEntry.buttonState, motionEntry.classification,
389 motionEntry.edgeFlags, motionEntry.xPrecision,
390 motionEntry.yPrecision, motionEntry.xCursorPosition,
391 motionEntry.yCursorPosition, motionEntry.downTime,
392 motionEntry.pointerCount, motionEntry.pointerProperties,
Prabir Pradhan5beda762021-12-10 09:30:08 +0000393 pointerCoords.data());
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000394
395 if (motionEntry.injectionState) {
396 combinedMotionEntry->injectionState = motionEntry.injectionState;
397 combinedMotionEntry->injectionState->refCount += 1;
398 }
399
400 std::unique_ptr<DispatchEntry> dispatchEntry =
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700401 std::make_unique<DispatchEntry>(std::move(combinedMotionEntry), inputTargetFlags,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700402 firstPointerTransform, inputTarget.displayTransform,
403 inputTarget.globalScaleFactor);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000404 return dispatchEntry;
405}
406
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000407status_t openInputChannelPair(const std::string& name, std::shared_ptr<InputChannel>& serverChannel,
408 std::unique_ptr<InputChannel>& clientChannel) {
Garfield Tan15601662020-09-22 15:32:38 -0700409 std::unique_ptr<InputChannel> uniqueServerChannel;
410 status_t result = InputChannel::openInputChannelPair(name, uniqueServerChannel, clientChannel);
411
412 serverChannel = std::move(uniqueServerChannel);
413 return result;
414}
415
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -0500416template <typename T>
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000417bool sharedPointersEqual(const std::shared_ptr<T>& lhs, const std::shared_ptr<T>& rhs) {
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -0500418 if (lhs == nullptr && rhs == nullptr) {
419 return true;
420 }
421 if (lhs == nullptr || rhs == nullptr) {
422 return false;
423 }
424 return *lhs == *rhs;
425}
426
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000427KeyEvent createKeyEvent(const KeyEntry& entry) {
Siarhei Vishniakou2e2ea992020-12-15 02:57:19 +0000428 KeyEvent event;
429 event.initialize(entry.id, entry.deviceId, entry.source, entry.displayId, INVALID_HMAC,
430 entry.action, entry.flags, entry.keyCode, entry.scanCode, entry.metaState,
431 entry.repeatCount, entry.downTime, entry.eventTime);
432 return event;
433}
434
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000435bool shouldReportMetricsForConnection(const Connection& connection) {
Siarhei Vishniakouf2652122021-03-05 21:39:46 +0000436 // Do not keep track of gesture monitors. They receive every event and would disproportionately
437 // affect the statistics.
438 if (connection.monitor) {
439 return false;
440 }
441 // If the connection is experiencing ANR, let's skip it. We have separate ANR metrics
442 if (!connection.responsive) {
443 return false;
444 }
445 return true;
446}
447
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000448bool shouldReportFinishedEvent(const DispatchEntry& dispatchEntry, const Connection& connection) {
Siarhei Vishniakouf2652122021-03-05 21:39:46 +0000449 const EventEntry& eventEntry = *dispatchEntry.eventEntry;
450 const int32_t& inputEventId = eventEntry.id;
451 if (inputEventId != dispatchEntry.resolvedEventId) {
452 // Event was transmuted
453 return false;
454 }
455 if (inputEventId == android::os::IInputConstants::INVALID_INPUT_EVENT_ID) {
456 return false;
457 }
458 // Only track latency for events that originated from hardware
459 if (eventEntry.isSynthesized()) {
460 return false;
461 }
462 const EventEntry::Type& inputEventEntryType = eventEntry.type;
463 if (inputEventEntryType == EventEntry::Type::KEY) {
464 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
465 if (keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) {
466 return false;
467 }
468 } else if (inputEventEntryType == EventEntry::Type::MOTION) {
469 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
470 if (motionEntry.action == AMOTION_EVENT_ACTION_CANCEL ||
471 motionEntry.action == AMOTION_EVENT_ACTION_HOVER_EXIT) {
472 return false;
473 }
474 } else {
475 // Not a key or a motion
476 return false;
477 }
478 if (!shouldReportMetricsForConnection(connection)) {
479 return false;
480 }
481 return true;
482}
483
Prabir Pradhancef936d2021-07-21 16:17:52 +0000484/**
485 * Connection is responsive if it has no events in the waitQueue that are older than the
486 * current time.
487 */
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000488bool isConnectionResponsive(const Connection& connection) {
Prabir Pradhancef936d2021-07-21 16:17:52 +0000489 const nsecs_t currentTime = now();
490 for (const DispatchEntry* entry : connection.waitQueue) {
491 if (entry->timeoutTime < currentTime) {
492 return false;
493 }
494 }
495 return true;
496}
497
Antonio Kantekf16f2832021-09-28 04:39:20 +0000498// Returns true if the event type passed as argument represents a user activity.
499bool isUserActivityEvent(const EventEntry& eventEntry) {
500 switch (eventEntry.type) {
Josep del Riob3981622023-04-18 15:49:45 +0000501 case EventEntry::Type::CONFIGURATION_CHANGED:
502 case EventEntry::Type::DEVICE_RESET:
503 case EventEntry::Type::DRAG:
Antonio Kantekf16f2832021-09-28 04:39:20 +0000504 case EventEntry::Type::FOCUS:
505 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
Antonio Kantekf16f2832021-09-28 04:39:20 +0000506 case EventEntry::Type::SENSOR:
Josep del Riob3981622023-04-18 15:49:45 +0000507 case EventEntry::Type::TOUCH_MODE_CHANGED:
Antonio Kantekf16f2832021-09-28 04:39:20 +0000508 return false;
Antonio Kantekf16f2832021-09-28 04:39:20 +0000509 case EventEntry::Type::KEY:
510 case EventEntry::Type::MOTION:
511 return true;
512 }
513}
514
Prabir Pradhan3f90d312021-11-19 03:57:24 -0800515// Returns true if the given window can accept pointer events at the given display location.
Prabir Pradhan82e081e2022-12-06 09:50:09 +0000516bool windowAcceptsTouchAt(const WindowInfo& windowInfo, int32_t displayId, float x, float y,
Prabir Pradhan33e3baa2022-12-06 20:30:22 +0000517 bool isStylus, const ui::Transform& displayTransform) {
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -0800518 const auto inputConfig = windowInfo.inputConfig;
519 if (windowInfo.displayId != displayId ||
520 inputConfig.test(WindowInfo::InputConfig::NOT_VISIBLE)) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -0800521 return false;
522 }
Prabir Pradhand65552b2021-10-07 11:23:50 -0700523 const bool windowCanInterceptTouch = isStylus && windowInfo.interceptsStylus();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -0800524 if (inputConfig.test(WindowInfo::InputConfig::NOT_TOUCHABLE) && !windowCanInterceptTouch) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -0800525 return false;
526 }
Prabir Pradhan33e3baa2022-12-06 20:30:22 +0000527
528 // Window Manager works in the logical display coordinate space. When it specifies bounds for a
529 // window as (l, t, r, b), the range of x in [l, r) and y in [t, b) are considered to be inside
530 // the window. Points on the right and bottom edges should not be inside the window, so we need
531 // to be careful about performing a hit test when the display is rotated, since the "right" and
532 // "bottom" of the window will be different in the display (un-rotated) space compared to in the
533 // logical display in which WM determined the bounds. Perform the hit test in the logical
534 // display space to ensure these edges are considered correctly in all orientations.
535 const auto touchableRegion = displayTransform.transform(windowInfo.touchableRegion);
536 const auto p = displayTransform.transform(x, y);
537 if (!touchableRegion.contains(std::floor(p.x), std::floor(p.y))) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -0800538 return false;
539 }
540 return true;
541}
542
Prabir Pradhand65552b2021-10-07 11:23:50 -0700543bool isPointerFromStylus(const MotionEntry& entry, int32_t pointerIndex) {
544 return isFromSource(entry.source, AINPUT_SOURCE_STYLUS) &&
Prabir Pradhane5626962022-10-27 20:30:53 +0000545 isStylusToolType(entry.pointerProperties[pointerIndex].toolType);
Prabir Pradhand65552b2021-10-07 11:23:50 -0700546}
547
Siarhei Vishniakou253f4642022-11-09 13:42:06 -0800548// Determines if the given window can be targeted as InputTarget::Flags::FOREGROUND.
Prabir Pradhan6dfbf262022-03-14 15:24:30 +0000549// Foreground events are only sent to "foreground targetable" windows, but not all gestures sent to
550// such window are necessarily targeted with the flag. For example, an event with ACTION_OUTSIDE can
551// be sent to such a window, but it is not a foreground event and doesn't use
Siarhei Vishniakou253f4642022-11-09 13:42:06 -0800552// InputTarget::Flags::FOREGROUND.
Prabir Pradhan6dfbf262022-03-14 15:24:30 +0000553bool canReceiveForegroundTouches(const WindowInfo& info) {
554 // A non-touchable window can still receive touch events (e.g. in the case of
555 // STYLUS_INTERCEPTOR), so prevent such windows from receiving foreground events for touches.
556 return !info.inputConfig.test(gui::WindowInfo::InputConfig::NOT_TOUCHABLE) && !info.isSpy();
557}
558
Antonio Kantek48710e42022-03-24 14:19:30 -0700559bool isWindowOwnedBy(const sp<WindowInfoHandle>& windowHandle, int32_t pid, int32_t uid) {
560 if (windowHandle == nullptr) {
561 return false;
562 }
563 const WindowInfo* windowInfo = windowHandle->getInfo();
564 if (pid == windowInfo->ownerPid && uid == windowInfo->ownerUid) {
565 return true;
566 }
567 return false;
568}
569
Prabir Pradhan5735a322022-04-11 17:23:34 +0000570// Checks targeted injection using the window's owner's uid.
571// Returns an empty string if an entry can be sent to the given window, or an error message if the
572// entry is a targeted injection whose uid target doesn't match the window owner.
573std::optional<std::string> verifyTargetedInjection(const sp<WindowInfoHandle>& window,
574 const EventEntry& entry) {
575 if (entry.injectionState == nullptr || !entry.injectionState->targetUid) {
576 // The event was not injected, or the injected event does not target a window.
577 return {};
578 }
579 const int32_t uid = *entry.injectionState->targetUid;
580 if (window == nullptr) {
581 return StringPrintf("No valid window target for injection into uid %d.", uid);
582 }
583 if (entry.injectionState->targetUid != window->getInfo()->ownerUid) {
584 return StringPrintf("Injected event targeted at uid %d would be dispatched to window '%s' "
585 "owned by uid %d.",
586 uid, window->getName().c_str(), window->getInfo()->ownerUid);
587 }
588 return {};
589}
590
Prabir Pradhan82e081e2022-12-06 09:50:09 +0000591std::pair<float, float> resolveTouchedPosition(const MotionEntry& entry) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -0700592 const bool isFromMouse = isFromSource(entry.source, AINPUT_SOURCE_MOUSE);
593 // Always dispatch mouse events to cursor position.
594 if (isFromMouse) {
Prabir Pradhan82e081e2022-12-06 09:50:09 +0000595 return {entry.xCursorPosition, entry.yCursorPosition};
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -0700596 }
597
598 const int32_t pointerIndex = getMotionEventActionPointerIndex(entry.action);
Prabir Pradhan82e081e2022-12-06 09:50:09 +0000599 return {entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_X),
600 entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_Y)};
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -0700601}
602
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -0700603std::optional<nsecs_t> getDownTime(const EventEntry& eventEntry) {
604 if (eventEntry.type == EventEntry::Type::KEY) {
605 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
606 return keyEntry.downTime;
607 } else if (eventEntry.type == EventEntry::Type::MOTION) {
608 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
609 return motionEntry.downTime;
610 }
611 return std::nullopt;
612}
613
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000614/**
615 * Compare the old touch state to the new touch state, and generate the corresponding touched
616 * windows (== input targets).
617 * If a window had the hovering pointer, but now it doesn't, produce HOVER_EXIT for that window.
618 * If the pointer just entered the new window, produce HOVER_ENTER.
619 * For pointers remaining in the window, produce HOVER_MOVE.
620 */
621std::vector<TouchedWindow> getHoveringWindowsLocked(const TouchState* oldState,
622 const TouchState& newTouchState,
623 const MotionEntry& entry) {
624 std::vector<TouchedWindow> out;
625 const int32_t maskedAction = MotionEvent::getActionMasked(entry.action);
626 if (maskedAction != AMOTION_EVENT_ACTION_HOVER_ENTER &&
627 maskedAction != AMOTION_EVENT_ACTION_HOVER_MOVE &&
628 maskedAction != AMOTION_EVENT_ACTION_HOVER_EXIT) {
629 // Not a hover event - don't need to do anything
630 return out;
631 }
632
633 // We should consider all hovering pointers here. But for now, just use the first one
634 const int32_t pointerId = entry.pointerProperties[0].id;
635
636 std::set<sp<WindowInfoHandle>> oldWindows;
637 if (oldState != nullptr) {
638 oldWindows = oldState->getWindowsWithHoveringPointer(entry.deviceId, pointerId);
639 }
640
641 std::set<sp<WindowInfoHandle>> newWindows =
642 newTouchState.getWindowsWithHoveringPointer(entry.deviceId, pointerId);
643
644 // If the pointer is no longer in the new window set, send HOVER_EXIT.
645 for (const sp<WindowInfoHandle>& oldWindow : oldWindows) {
646 if (newWindows.find(oldWindow) == newWindows.end()) {
647 TouchedWindow touchedWindow;
648 touchedWindow.windowHandle = oldWindow;
649 touchedWindow.targetFlags = InputTarget::Flags::DISPATCH_AS_HOVER_EXIT;
Siarhei Vishniakou8a878352023-01-30 14:05:01 -0800650 touchedWindow.pointerIds.set(pointerId);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000651 out.push_back(touchedWindow);
652 }
653 }
654
655 for (const sp<WindowInfoHandle>& newWindow : newWindows) {
656 TouchedWindow touchedWindow;
657 touchedWindow.windowHandle = newWindow;
658 if (oldWindows.find(newWindow) == oldWindows.end()) {
659 // Any windows that have this pointer now, and didn't have it before, should get
660 // HOVER_ENTER
661 touchedWindow.targetFlags = InputTarget::Flags::DISPATCH_AS_HOVER_ENTER;
662 } else {
663 // This pointer was already sent to the window. Use ACTION_HOVER_MOVE.
Siarhei Vishniakouc2eb8502023-04-11 18:33:36 -0700664 if (CC_UNLIKELY(maskedAction != AMOTION_EVENT_ACTION_HOVER_MOVE)) {
Daniel Norman5fe59da2023-08-02 16:39:45 -0700665 android::base::LogSeverity severity = android::base::LogSeverity::FATAL;
666 if (entry.flags & AMOTION_EVENT_FLAG_IS_ACCESSIBILITY_EVENT) {
667 // The Accessibility injected touch exploration event stream
668 // has known inconsistencies, so log ERROR instead of
669 // crashing the device with FATAL.
670 // TODO(b/286037469): Move a11y severity back to FATAL.
671 severity = android::base::LogSeverity::ERROR;
672 }
673 LOG(severity) << "Expected ACTION_HOVER_MOVE instead of " << entry.getDescription();
Siarhei Vishniakouc2eb8502023-04-11 18:33:36 -0700674 }
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000675 touchedWindow.targetFlags = InputTarget::Flags::DISPATCH_AS_IS;
676 }
Siarhei Vishniakou8a878352023-01-30 14:05:01 -0800677 touchedWindow.pointerIds.set(pointerId);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000678 if (canReceiveForegroundTouches(*newWindow->getInfo())) {
679 touchedWindow.targetFlags |= InputTarget::Flags::FOREGROUND;
680 }
681 out.push_back(touchedWindow);
682 }
683 return out;
684}
685
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -0800686template <typename T>
687std::vector<T>& operator+=(std::vector<T>& left, const std::vector<T>& right) {
688 left.insert(left.end(), right.begin(), right.end());
689 return left;
690}
691
Harry Cuttsb166c002023-05-09 13:06:05 +0000692// Filter windows in a TouchState and targets in a vector to remove untrusted windows/targets from
693// both.
694void filterUntrustedTargets(TouchState& touchState, std::vector<InputTarget>& targets) {
695 std::erase_if(touchState.windows, [&](const TouchedWindow& window) {
696 if (!window.windowHandle->getInfo()->inputConfig.test(
697 WindowInfo::InputConfig::TRUSTED_OVERLAY)) {
698 // In addition to TouchState, erase this window from the input targets! We don't have a
699 // good way to do this today except by adding a nested loop.
700 // TODO(b/282025641): simplify this code once InputTargets are being identified
701 // separately from TouchedWindows.
702 std::erase_if(targets, [&](const InputTarget& target) {
703 return target.inputChannel->getConnectionToken() == window.windowHandle->getToken();
704 });
705 return true;
706 }
707 return false;
708 });
709}
710
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000711} // namespace
712
Michael Wrightd02c5b62014-02-10 15:10:22 -0800713// --- InputDispatcher ---
714
Prabir Pradhana41d2442023-04-20 21:30:40 +0000715InputDispatcher::InputDispatcher(InputDispatcherPolicyInterface& policy)
Siarhei Vishniakou289e9242022-02-15 14:50:16 -0800716 : InputDispatcher(policy, STALE_EVENT_TIMEOUT) {}
717
Prabir Pradhana41d2442023-04-20 21:30:40 +0000718InputDispatcher::InputDispatcher(InputDispatcherPolicyInterface& policy,
Siarhei Vishniakou289e9242022-02-15 14:50:16 -0800719 std::chrono::nanoseconds staleEventTimeout)
Garfield Tan00f511d2019-06-12 16:55:40 -0700720 : mPolicy(policy),
721 mPendingEvent(nullptr),
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700722 mLastDropReason(DropReason::NOT_DROPPED),
Garfield Tanff1f1bb2020-01-28 13:24:04 -0800723 mIdGenerator(IdGenerator::Source::INPUT_DISPATCHER),
Garfield Tan00f511d2019-06-12 16:55:40 -0700724 mAppSwitchSawKeyDown(false),
Colin Cross5b799302022-10-18 21:52:41 -0700725 mAppSwitchDueTime(LLONG_MAX),
Garfield Tan00f511d2019-06-12 16:55:40 -0700726 mNextUnblockedEvent(nullptr),
Prabir Pradhan1376fcd2022-01-21 09:56:35 -0800727 mMonitorDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT),
Garfield Tan00f511d2019-06-12 16:55:40 -0700728 mDispatchEnabled(false),
729 mDispatchFrozen(false),
730 mInputFilterEnabled(false),
Bernardo Rufinoea97d182020-08-19 14:43:14 +0100731 mMaximumObscuringOpacityForTouch(1.0f),
Siarhei Vishniakou2508b872020-12-03 16:33:53 -1000732 mFocusedDisplayId(ADISPLAY_ID_DEFAULT),
Prabir Pradhan99987712020-11-10 18:43:05 -0800733 mWindowTokenWithPointerCapture(nullptr),
Siarhei Vishniakou289e9242022-02-15 14:50:16 -0800734 mStaleEventTimeout(staleEventTimeout),
Siarhei Vishniakoua04181f2021-03-26 05:56:49 +0000735 mLatencyAggregator(),
Antonio Kantek15beb512022-06-13 22:35:41 +0000736 mLatencyTracker(&mLatencyAggregator) {
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -0700737 mLooper = sp<Looper>::make(false);
Prabir Pradhanf93562f2018-11-29 12:13:37 -0800738 mReporter = createInputReporter();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800739
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -0700740 mWindowInfoListener = sp<DispatcherWindowListener>::make(*this);
Siarhei Vishniakou31977182022-09-30 08:51:23 -0700741#if defined(__ANDROID__)
Siarhei Vishniakou18050092021-09-01 13:32:49 -0700742 SurfaceComposerClient::getDefault()->addWindowInfosListener(mWindowInfoListener);
Siarhei Vishniakou31977182022-09-30 08:51:23 -0700743#endif
Yi Kong9b14ac62018-07-17 13:48:38 -0700744 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800745}
746
747InputDispatcher::~InputDispatcher() {
Prabir Pradhancef936d2021-07-21 16:17:52 +0000748 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800749
Prabir Pradhancef936d2021-07-21 16:17:52 +0000750 resetKeyRepeatLocked();
751 releasePendingEventLocked();
752 drainInboundQueueLocked();
753 mCommandQueue.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800754
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +0000755 while (!mConnectionsByToken.empty()) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -0700756 std::shared_ptr<Connection> connection = mConnectionsByToken.begin()->second;
Harry Cutts33476232023-01-30 19:57:29 +0000757 removeInputChannelLocked(connection->inputChannel->getConnectionToken(), /*notify=*/false);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800758 }
759}
760
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700761status_t InputDispatcher::start() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700762 if (mThread) {
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700763 return ALREADY_EXISTS;
764 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700765 mThread = std::make_unique<InputThread>(
766 "InputDispatcher", [this]() { dispatchOnce(); }, [this]() { mLooper->wake(); });
767 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700768}
769
770status_t InputDispatcher::stop() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700771 if (mThread && mThread->isCallingThread()) {
772 ALOGE("InputDispatcher cannot be stopped from its own thread!");
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700773 return INVALID_OPERATION;
774 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700775 mThread.reset();
776 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700777}
778
Michael Wrightd02c5b62014-02-10 15:10:22 -0800779void InputDispatcher::dispatchOnce() {
Colin Cross5b799302022-10-18 21:52:41 -0700780 nsecs_t nextWakeupTime = LLONG_MAX;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800781 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -0800782 std::scoped_lock _l(mLock);
783 mDispatcherIsAlive.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800784
785 // Run a dispatch loop if there are no pending commands.
786 // The dispatch loop might enqueue commands to run afterwards.
787 if (!haveCommandsLocked()) {
788 dispatchOnceInnerLocked(&nextWakeupTime);
789 }
790
791 // Run all pending commands if there are any.
792 // If any commands were run then force the next poll to wake up immediately.
Prabir Pradhancef936d2021-07-21 16:17:52 +0000793 if (runCommandsLockedInterruptable()) {
Colin Cross5b799302022-10-18 21:52:41 -0700794 nextWakeupTime = LLONG_MIN;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800795 }
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800796
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700797 // If we are still waiting for ack on some events,
798 // we might have to wake up earlier to check if an app is anr'ing.
799 const nsecs_t nextAnrCheck = processAnrsLocked();
800 nextWakeupTime = std::min(nextWakeupTime, nextAnrCheck);
801
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800802 // We are about to enter an infinitely long sleep, because we have no commands or
803 // pending or queued events
Colin Cross5b799302022-10-18 21:52:41 -0700804 if (nextWakeupTime == LLONG_MAX) {
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800805 mDispatcherEnteredIdle.notify_all();
806 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800807 } // release lock
808
809 // Wait for callback or timeout or wake. (make sure we round up, not down)
810 nsecs_t currentTime = now();
811 int timeoutMillis = toMillisecondTimeoutDelay(currentTime, nextWakeupTime);
812 mLooper->pollOnce(timeoutMillis);
813}
814
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700815/**
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500816 * Raise ANR if there is no focused window.
817 * Before the ANR is raised, do a final state check:
818 * 1. The currently focused application must be the same one we are waiting for.
819 * 2. Ensure we still don't have a focused window.
820 */
821void InputDispatcher::processNoFocusedWindowAnrLocked() {
822 // Check if the application that we are waiting for is still focused.
823 std::shared_ptr<InputApplicationHandle> focusedApplication =
824 getValueByKey(mFocusedApplicationHandlesByDisplay, mAwaitedApplicationDisplayId);
825 if (focusedApplication == nullptr ||
826 focusedApplication->getApplicationToken() !=
827 mAwaitedFocusedApplication->getApplicationToken()) {
828 // Unexpected because we should have reset the ANR timer when focused application changed
829 ALOGE("Waited for a focused window, but focused application has already changed to %s",
830 focusedApplication->getName().c_str());
831 return; // The focused application has changed.
832 }
833
chaviw98318de2021-05-19 16:45:23 -0500834 const sp<WindowInfoHandle>& focusedWindowHandle =
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500835 getFocusedWindowHandleLocked(mAwaitedApplicationDisplayId);
836 if (focusedWindowHandle != nullptr) {
837 return; // We now have a focused window. No need for ANR.
838 }
839 onAnrLocked(mAwaitedFocusedApplication);
840}
841
842/**
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700843 * Check if any of the connections' wait queues have events that are too old.
844 * If we waited for events to be ack'ed for more than the window timeout, raise an ANR.
845 * Return the time at which we should wake up next.
846 */
847nsecs_t InputDispatcher::processAnrsLocked() {
848 const nsecs_t currentTime = now();
Colin Cross5b799302022-10-18 21:52:41 -0700849 nsecs_t nextAnrCheck = LLONG_MAX;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700850 // Check if we are waiting for a focused window to appear. Raise ANR if waited too long
851 if (mNoFocusedWindowTimeoutTime.has_value() && mAwaitedFocusedApplication != nullptr) {
852 if (currentTime >= *mNoFocusedWindowTimeoutTime) {
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500853 processNoFocusedWindowAnrLocked();
Chris Yea209fde2020-07-22 13:54:51 -0700854 mAwaitedFocusedApplication.reset();
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500855 mNoFocusedWindowTimeoutTime = std::nullopt;
Colin Cross5b799302022-10-18 21:52:41 -0700856 return LLONG_MIN;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700857 } else {
Siarhei Vishniakou38a6d272020-10-20 20:29:33 -0500858 // Keep waiting. We will drop the event when mNoFocusedWindowTimeoutTime comes.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700859 nextAnrCheck = *mNoFocusedWindowTimeoutTime;
860 }
861 }
862
863 // Check if any connection ANRs are due
864 nextAnrCheck = std::min(nextAnrCheck, mAnrTracker.firstTimeout());
865 if (currentTime < nextAnrCheck) { // most likely scenario
866 return nextAnrCheck; // everything is normal. Let's check again at nextAnrCheck
867 }
868
869 // If we reached here, we have an unresponsive connection.
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -0700870 std::shared_ptr<Connection> connection = getConnectionLocked(mAnrTracker.firstToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700871 if (connection == nullptr) {
872 ALOGE("Could not find connection for entry %" PRId64, mAnrTracker.firstTimeout());
873 return nextAnrCheck;
874 }
875 connection->responsive = false;
876 // Stop waking up for this unresponsive connection
877 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000878 onAnrLocked(connection);
Colin Cross5b799302022-10-18 21:52:41 -0700879 return LLONG_MIN;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700880}
881
Prabir Pradhan1376fcd2022-01-21 09:56:35 -0800882std::chrono::nanoseconds InputDispatcher::getDispatchingTimeoutLocked(
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -0700883 const std::shared_ptr<Connection>& connection) {
Prabir Pradhan1376fcd2022-01-21 09:56:35 -0800884 if (connection->monitor) {
885 return mMonitorDispatchingTimeout;
886 }
887 const sp<WindowInfoHandle> window =
888 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700889 if (window != nullptr) {
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500890 return window->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700891 }
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500892 return DEFAULT_INPUT_DISPATCHING_TIMEOUT;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700893}
894
Michael Wrightd02c5b62014-02-10 15:10:22 -0800895void InputDispatcher::dispatchOnceInnerLocked(nsecs_t* nextWakeupTime) {
896 nsecs_t currentTime = now();
897
Jeff Browndc5992e2014-04-11 01:27:26 -0700898 // Reset the key repeat timer whenever normal dispatch is suspended while the
899 // device is in a non-interactive state. This is to ensure that we abort a key
900 // repeat if the device is just coming out of sleep.
901 if (!mDispatchEnabled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800902 resetKeyRepeatLocked();
903 }
904
905 // If dispatching is frozen, do not process timeouts or try to deliver any new events.
906 if (mDispatchFrozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +0100907 if (DEBUG_FOCUS) {
908 ALOGD("Dispatch frozen. Waiting some more.");
909 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800910 return;
911 }
912
913 // Optimize latency of app switches.
914 // Essentially we start a short timeout when an app switch key (HOME / ENDCALL) has
915 // been pressed. When it expires, we preempt dispatch and drop all other pending events.
916 bool isAppSwitchDue = mAppSwitchDueTime <= currentTime;
917 if (mAppSwitchDueTime < *nextWakeupTime) {
918 *nextWakeupTime = mAppSwitchDueTime;
919 }
920
921 // Ready to start a new event.
922 // If we don't already have a pending event, go grab one.
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700923 if (!mPendingEvent) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700924 if (mInboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800925 if (isAppSwitchDue) {
926 // The inbound queue is empty so the app switch key we were waiting
927 // for will never arrive. Stop waiting for it.
928 resetPendingAppSwitchLocked(false);
929 isAppSwitchDue = false;
930 }
931
932 // Synthesize a key repeat if appropriate.
933 if (mKeyRepeatState.lastKeyEntry) {
934 if (currentTime >= mKeyRepeatState.nextRepeatTime) {
935 mPendingEvent = synthesizeKeyRepeatLocked(currentTime);
936 } else {
937 if (mKeyRepeatState.nextRepeatTime < *nextWakeupTime) {
938 *nextWakeupTime = mKeyRepeatState.nextRepeatTime;
939 }
940 }
941 }
942
943 // Nothing to do if there is no pending event.
944 if (!mPendingEvent) {
945 return;
946 }
947 } else {
948 // Inbound queue has at least one entry.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700949 mPendingEvent = mInboundQueue.front();
950 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800951 traceInboundQueueLengthLocked();
952 }
953
954 // Poke user activity for this event.
955 if (mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700956 pokeUserActivityLocked(*mPendingEvent);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800957 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800958 }
959
960 // Now we have an event to dispatch.
961 // All events are eventually dequeued and processed this way, even if we intend to drop them.
Yi Kong9b14ac62018-07-17 13:48:38 -0700962 ALOG_ASSERT(mPendingEvent != nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800963 bool done = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700964 DropReason dropReason = DropReason::NOT_DROPPED;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800965 if (!(mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700966 dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800967 } else if (!mDispatchEnabled) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700968 dropReason = DropReason::DISABLED;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800969 }
970
971 if (mNextUnblockedEvent == mPendingEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -0700972 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800973 }
974
975 switch (mPendingEvent->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700976 case EventEntry::Type::CONFIGURATION_CHANGED: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700977 const ConfigurationChangedEntry& typedEntry =
978 static_cast<const ConfigurationChangedEntry&>(*mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700979 done = dispatchConfigurationChangedLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700980 dropReason = DropReason::NOT_DROPPED; // configuration changes are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700981 break;
982 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800983
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700984 case EventEntry::Type::DEVICE_RESET: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700985 const DeviceResetEntry& typedEntry =
986 static_cast<const DeviceResetEntry&>(*mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700987 done = dispatchDeviceResetLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700988 dropReason = DropReason::NOT_DROPPED; // device resets are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700989 break;
990 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800991
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100992 case EventEntry::Type::FOCUS: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700993 std::shared_ptr<FocusEntry> typedEntry =
994 std::static_pointer_cast<FocusEntry>(mPendingEvent);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100995 dispatchFocusLocked(currentTime, typedEntry);
996 done = true;
997 dropReason = DropReason::NOT_DROPPED; // focus events are never dropped
998 break;
999 }
1000
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001001 case EventEntry::Type::TOUCH_MODE_CHANGED: {
1002 const auto typedEntry = std::static_pointer_cast<TouchModeEntry>(mPendingEvent);
1003 dispatchTouchModeChangeLocked(currentTime, typedEntry);
1004 done = true;
1005 dropReason = DropReason::NOT_DROPPED; // touch mode events are never dropped
1006 break;
1007 }
1008
Prabir Pradhan99987712020-11-10 18:43:05 -08001009 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
1010 const auto typedEntry =
1011 std::static_pointer_cast<PointerCaptureChangedEntry>(mPendingEvent);
1012 dispatchPointerCaptureChangedLocked(currentTime, typedEntry, dropReason);
1013 done = true;
1014 break;
1015 }
1016
arthurhungb89ccb02020-12-30 16:19:01 +08001017 case EventEntry::Type::DRAG: {
1018 std::shared_ptr<DragEntry> typedEntry =
1019 std::static_pointer_cast<DragEntry>(mPendingEvent);
1020 dispatchDragLocked(currentTime, typedEntry);
1021 done = true;
1022 break;
1023 }
1024
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001025 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001026 std::shared_ptr<KeyEntry> keyEntry = std::static_pointer_cast<KeyEntry>(mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001027 if (isAppSwitchDue) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001028 if (isAppSwitchKeyEvent(*keyEntry)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001029 resetPendingAppSwitchLocked(true);
1030 isAppSwitchDue = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001031 } else if (dropReason == DropReason::NOT_DROPPED) {
1032 dropReason = DropReason::APP_SWITCH;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001033 }
1034 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001035 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *keyEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001036 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001037 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001038 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
1039 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001040 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001041 done = dispatchKeyLocked(currentTime, keyEntry, &dropReason, nextWakeupTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001042 break;
1043 }
1044
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001045 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001046 std::shared_ptr<MotionEntry> motionEntry =
1047 std::static_pointer_cast<MotionEntry>(mPendingEvent);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001048 if (dropReason == DropReason::NOT_DROPPED && isAppSwitchDue) {
1049 dropReason = DropReason::APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001050 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001051 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *motionEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001052 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001053 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001054 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
1055 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001056 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001057 done = dispatchMotionLocked(currentTime, motionEntry, &dropReason, nextWakeupTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001058 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001059 }
Chris Yef59a2f42020-10-16 12:55:26 -07001060
1061 case EventEntry::Type::SENSOR: {
1062 std::shared_ptr<SensorEntry> sensorEntry =
1063 std::static_pointer_cast<SensorEntry>(mPendingEvent);
1064 if (dropReason == DropReason::NOT_DROPPED && isAppSwitchDue) {
1065 dropReason = DropReason::APP_SWITCH;
1066 }
1067 // Sensor timestamps use SYSTEM_TIME_BOOTTIME time base, so we can't use
1068 // 'currentTime' here, get SYSTEM_TIME_BOOTTIME instead.
1069 nsecs_t bootTime = systemTime(SYSTEM_TIME_BOOTTIME);
1070 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(bootTime, *sensorEntry)) {
1071 dropReason = DropReason::STALE;
1072 }
1073 dispatchSensorLocked(currentTime, sensorEntry, &dropReason, nextWakeupTime);
1074 done = true;
1075 break;
1076 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001077 }
1078
1079 if (done) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001080 if (dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001081 dropInboundEventLocked(*mPendingEvent, dropReason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001082 }
Michael Wright3a981722015-06-10 15:26:13 +01001083 mLastDropReason = dropReason;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001084
1085 releasePendingEventLocked();
Colin Cross5b799302022-10-18 21:52:41 -07001086 *nextWakeupTime = LLONG_MIN; // force next poll to wake up immediately
Michael Wrightd02c5b62014-02-10 15:10:22 -08001087 }
1088}
1089
Siarhei Vishniakou289e9242022-02-15 14:50:16 -08001090bool InputDispatcher::isStaleEvent(nsecs_t currentTime, const EventEntry& entry) {
1091 return std::chrono::nanoseconds(currentTime - entry.eventTime) >= mStaleEventTimeout;
1092}
1093
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001094/**
1095 * Return true if the events preceding this incoming motion event should be dropped
1096 * Return false otherwise (the default behaviour)
1097 */
1098bool InputDispatcher::shouldPruneInboundQueueLocked(const MotionEntry& motionEntry) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001099 const bool isPointerDownEvent = motionEntry.action == AMOTION_EVENT_ACTION_DOWN &&
Prabir Pradhanaa561d12021-09-24 06:57:33 -07001100 isFromSource(motionEntry.source, AINPUT_SOURCE_CLASS_POINTER);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001101
1102 // Optimize case where the current application is unresponsive and the user
1103 // decides to touch a window in a different application.
1104 // If the application takes too long to catch up then we drop all events preceding
1105 // the touch into the other window.
1106 if (isPointerDownEvent && mAwaitedFocusedApplication != nullptr) {
Siarhei Vishniakou9306c382022-09-30 15:30:31 -07001107 const int32_t displayId = motionEntry.displayId;
1108 const auto [x, y] = resolveTouchedPosition(motionEntry);
Harry Cutts33476232023-01-30 19:57:29 +00001109 const bool isStylus = isPointerFromStylus(motionEntry, /*pointerIndex=*/0);
Siarhei Vishniakou9306c382022-09-30 15:30:31 -07001110
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08001111 auto [touchedWindowHandle, _] = findTouchedWindowAtLocked(displayId, x, y, isStylus);
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001112 if (touchedWindowHandle != nullptr &&
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001113 touchedWindowHandle->getApplicationToken() !=
1114 mAwaitedFocusedApplication->getApplicationToken()) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001115 // User touched a different application than the one we are waiting on.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001116 ALOGI("Pruning input queue because user touched a different application while waiting "
1117 "for %s",
1118 mAwaitedFocusedApplication->getName().c_str());
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001119 return true;
1120 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001121
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08001122 // Alternatively, maybe there's a spy window that could handle this event.
1123 const std::vector<sp<WindowInfoHandle>> touchedSpies =
1124 findTouchedSpyWindowsAtLocked(displayId, x, y, isStylus);
1125 for (const auto& windowHandle : touchedSpies) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07001126 const std::shared_ptr<Connection> connection =
1127 getConnectionLocked(windowHandle->getToken());
Siarhei Vishniakou34ed4d42020-06-18 00:43:02 +00001128 if (connection != nullptr && connection->responsive) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08001129 // This spy window could take more input. Drop all events preceding this
1130 // event, so that the spy window can get a chance to receive the stream.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001131 ALOGW("Pruning the input queue because %s is unresponsive, but we have a "
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08001132 "responsive spy window that may handle the event.",
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001133 mAwaitedFocusedApplication->getName().c_str());
1134 return true;
1135 }
1136 }
1137 }
1138
1139 // Prevent getting stuck: if we have a pending key event, and some motion events that have not
1140 // yet been processed by some connections, the dispatcher will wait for these motion
1141 // events to be processed before dispatching the key event. This is because these motion events
1142 // may cause a new window to be launched, which the user might expect to receive focus.
1143 // To prevent waiting forever for such events, just send the key to the currently focused window
1144 if (isPointerDownEvent && mKeyIsWaitingForEventsTimeout) {
1145 ALOGD("Received a new pointer down event, stop waiting for events to process and "
1146 "just send the pending key event to the focused window.");
1147 mKeyIsWaitingForEventsTimeout = now();
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001148 }
1149 return false;
1150}
1151
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001152bool InputDispatcher::enqueueInboundEventLocked(std::unique_ptr<EventEntry> newEntry) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001153 bool needWake = mInboundQueue.empty();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001154 mInboundQueue.push_back(std::move(newEntry));
1155 EventEntry& entry = *(mInboundQueue.back());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001156 traceInboundQueueLengthLocked();
1157
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001158 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001159 case EventEntry::Type::KEY: {
Prabir Pradhan5735a322022-04-11 17:23:34 +00001160 LOG_ALWAYS_FATAL_IF((entry.policyFlags & POLICY_FLAG_TRUSTED) == 0,
1161 "Unexpected untrusted event.");
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001162 // Optimize app switch latency.
1163 // If the application takes too long to catch up then we drop all events preceding
1164 // the app switch key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001165 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001166 if (isAppSwitchKeyEvent(keyEntry)) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001167 if (keyEntry.action == AKEY_EVENT_ACTION_DOWN) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001168 mAppSwitchSawKeyDown = true;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001169 } else if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001170 if (mAppSwitchSawKeyDown) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001171 if (DEBUG_APP_SWITCH) {
1172 ALOGD("App switch is pending!");
1173 }
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001174 mAppSwitchDueTime = keyEntry.eventTime + APP_SWITCH_TIMEOUT;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001175 mAppSwitchSawKeyDown = false;
1176 needWake = true;
1177 }
1178 }
1179 }
Arthur Hung2ee6d0b2022-03-03 20:19:38 +08001180
1181 // If a new up event comes in, and the pending event with same key code has been asked
1182 // to try again later because of the policy. We have to reset the intercept key wake up
1183 // time for it may have been handled in the policy and could be dropped.
1184 if (keyEntry.action == AKEY_EVENT_ACTION_UP && mPendingEvent &&
1185 mPendingEvent->type == EventEntry::Type::KEY) {
1186 KeyEntry& pendingKey = static_cast<KeyEntry&>(*mPendingEvent);
1187 if (pendingKey.keyCode == keyEntry.keyCode &&
1188 pendingKey.interceptKeyResult ==
Michael Wright5caf55a2022-11-24 22:31:42 +00001189 KeyEntry::InterceptKeyResult::TRY_AGAIN_LATER) {
1190 pendingKey.interceptKeyResult = KeyEntry::InterceptKeyResult::UNKNOWN;
Arthur Hung2ee6d0b2022-03-03 20:19:38 +08001191 pendingKey.interceptKeyWakeupTime = 0;
1192 needWake = true;
1193 }
1194 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001195 break;
1196 }
1197
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001198 case EventEntry::Type::MOTION: {
Prabir Pradhan5735a322022-04-11 17:23:34 +00001199 LOG_ALWAYS_FATAL_IF((entry.policyFlags & POLICY_FLAG_TRUSTED) == 0,
1200 "Unexpected untrusted event.");
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001201 if (shouldPruneInboundQueueLocked(static_cast<MotionEntry&>(entry))) {
1202 mNextUnblockedEvent = mInboundQueue.back();
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001203 needWake = true;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001204 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001205 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001206 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001207 case EventEntry::Type::FOCUS: {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001208 LOG_ALWAYS_FATAL("Focus events should be inserted using enqueueFocusEventLocked");
1209 break;
1210 }
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001211 case EventEntry::Type::TOUCH_MODE_CHANGED:
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001212 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08001213 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07001214 case EventEntry::Type::SENSOR:
arthurhungb89ccb02020-12-30 16:19:01 +08001215 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
1216 case EventEntry::Type::DRAG: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001217 // nothing to do
1218 break;
1219 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001220 }
1221
1222 return needWake;
1223}
1224
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001225void InputDispatcher::addRecentEventLocked(std::shared_ptr<EventEntry> entry) {
Chris Yef59a2f42020-10-16 12:55:26 -07001226 // Do not store sensor event in recent queue to avoid flooding the queue.
1227 if (entry->type != EventEntry::Type::SENSOR) {
1228 mRecentQueue.push_back(entry);
1229 }
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001230 if (mRecentQueue.size() > RECENT_QUEUE_MAX_SIZE) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001231 mRecentQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001232 }
1233}
1234
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08001235std::pair<sp<WindowInfoHandle>, std::vector<InputTarget>>
Prabir Pradhan82e081e2022-12-06 09:50:09 +00001236InputDispatcher::findTouchedWindowAtLocked(int32_t displayId, float x, float y, bool isStylus,
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08001237 bool ignoreDragWindow) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001238 // Traverse windows from front to back to find touched window.
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08001239 std::vector<InputTarget> outsideTargets;
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001240 const auto& windowHandles = getWindowHandlesLocked(displayId);
chaviw98318de2021-05-19 16:45:23 -05001241 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
arthurhung6d4bed92021-03-17 11:59:33 +08001242 if (ignoreDragWindow && haveSameToken(windowHandle, mDragState->dragWindow)) {
arthurhungb89ccb02020-12-30 16:19:01 +08001243 continue;
1244 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001245
Prabir Pradhan3f90d312021-11-19 03:57:24 -08001246 const WindowInfo& info = *windowHandle->getInfo();
Prabir Pradhan33e3baa2022-12-06 20:30:22 +00001247 if (!info.isSpy() &&
1248 windowAcceptsTouchAt(info, displayId, x, y, isStylus, getTransformLocked(displayId))) {
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08001249 return {windowHandle, outsideTargets};
Prabir Pradhan3f90d312021-11-19 03:57:24 -08001250 }
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001251
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08001252 if (info.inputConfig.test(WindowInfo::InputConfig::WATCH_OUTSIDE_TOUCH)) {
1253 addWindowTargetLocked(windowHandle, InputTarget::Flags::DISPATCH_AS_OUTSIDE,
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08001254 /*pointerIds=*/{}, /*firstDownTimeInTarget=*/std::nullopt,
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08001255 outsideTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001256 }
1257 }
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08001258 return {nullptr, {}};
Michael Wrightd02c5b62014-02-10 15:10:22 -08001259}
1260
Prabir Pradhand65552b2021-10-07 11:23:50 -07001261std::vector<sp<WindowInfoHandle>> InputDispatcher::findTouchedSpyWindowsAtLocked(
Prabir Pradhan82e081e2022-12-06 09:50:09 +00001262 int32_t displayId, float x, float y, bool isStylus) const {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001263 // Traverse windows from front to back and gather the touched spy windows.
1264 std::vector<sp<WindowInfoHandle>> spyWindows;
1265 const auto& windowHandles = getWindowHandlesLocked(displayId);
1266 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
1267 const WindowInfo& info = *windowHandle->getInfo();
1268
Prabir Pradhan33e3baa2022-12-06 20:30:22 +00001269 if (!windowAcceptsTouchAt(info, displayId, x, y, isStylus, getTransformLocked(displayId))) {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001270 continue;
1271 }
1272 if (!info.isSpy()) {
1273 // The first touched non-spy window was found, so return the spy windows touched so far.
1274 return spyWindows;
1275 }
1276 spyWindows.push_back(windowHandle);
1277 }
1278 return spyWindows;
1279}
1280
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001281void InputDispatcher::dropInboundEventLocked(const EventEntry& entry, DropReason dropReason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001282 const char* reason;
1283 switch (dropReason) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001284 case DropReason::POLICY:
Prabir Pradhan65613802023-02-22 23:36:58 +00001285 if (debugInboundEventDetails()) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001286 ALOGD("Dropped event because policy consumed it.");
1287 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001288 reason = "inbound event was dropped because the policy consumed it";
1289 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001290 case DropReason::DISABLED:
1291 if (mLastDropReason != DropReason::DISABLED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001292 ALOGI("Dropped event because input dispatch is disabled.");
1293 }
1294 reason = "inbound event was dropped because input dispatch is disabled";
1295 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001296 case DropReason::APP_SWITCH:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001297 ALOGI("Dropped event because of pending overdue app switch.");
1298 reason = "inbound event was dropped because of pending overdue app switch";
1299 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001300 case DropReason::BLOCKED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001301 ALOGI("Dropped event because the current application is not responding and the user "
1302 "has started interacting with a different application.");
1303 reason = "inbound event was dropped because the current application is not responding "
1304 "and the user has started interacting with a different application";
1305 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001306 case DropReason::STALE:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001307 ALOGI("Dropped event because it is stale.");
1308 reason = "inbound event was dropped because it is stale";
1309 break;
Prabir Pradhan99987712020-11-10 18:43:05 -08001310 case DropReason::NO_POINTER_CAPTURE:
1311 ALOGI("Dropped event because there is no window with Pointer Capture.");
1312 reason = "inbound event was dropped because there is no window with Pointer Capture";
1313 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001314 case DropReason::NOT_DROPPED: {
1315 LOG_ALWAYS_FATAL("Should not be dropping a NOT_DROPPED event");
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001316 return;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001317 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001318 }
1319
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001320 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001321 case EventEntry::Type::KEY: {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001322 CancelationOptions options(CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS, reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001323 synthesizeCancelationEventsForAllConnectionsLocked(options);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001324 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001325 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001326 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001327 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
1328 if (motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001329 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS, reason);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001330 synthesizeCancelationEventsForAllConnectionsLocked(options);
1331 } else {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001332 CancelationOptions options(CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS,
1333 reason);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001334 synthesizeCancelationEventsForAllConnectionsLocked(options);
1335 }
1336 break;
1337 }
Chris Yef59a2f42020-10-16 12:55:26 -07001338 case EventEntry::Type::SENSOR: {
1339 break;
1340 }
arthurhungb89ccb02020-12-30 16:19:01 +08001341 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
1342 case EventEntry::Type::DRAG: {
Prabir Pradhan99987712020-11-10 18:43:05 -08001343 break;
1344 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001345 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001346 case EventEntry::Type::TOUCH_MODE_CHANGED:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001347 case EventEntry::Type::CONFIGURATION_CHANGED:
1348 case EventEntry::Type::DEVICE_RESET: {
Dominik Laskowski75788452021-02-09 18:51:25 -08001349 LOG_ALWAYS_FATAL("Should not drop %s events", ftl::enum_string(entry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001350 break;
1351 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001352 }
1353}
1354
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08001355static bool isAppSwitchKeyCode(int32_t keyCode) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001356 return keyCode == AKEYCODE_HOME || keyCode == AKEYCODE_ENDCALL ||
1357 keyCode == AKEYCODE_APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001358}
1359
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001360bool InputDispatcher::isAppSwitchKeyEvent(const KeyEntry& keyEntry) {
1361 return !(keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) && isAppSwitchKeyCode(keyEntry.keyCode) &&
1362 (keyEntry.policyFlags & POLICY_FLAG_TRUSTED) &&
1363 (keyEntry.policyFlags & POLICY_FLAG_PASS_TO_USER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001364}
1365
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07001366bool InputDispatcher::isAppSwitchPendingLocked() const {
Colin Cross5b799302022-10-18 21:52:41 -07001367 return mAppSwitchDueTime != LLONG_MAX;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001368}
1369
1370void InputDispatcher::resetPendingAppSwitchLocked(bool handled) {
Colin Cross5b799302022-10-18 21:52:41 -07001371 mAppSwitchDueTime = LLONG_MAX;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001372
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001373 if (DEBUG_APP_SWITCH) {
1374 if (handled) {
1375 ALOGD("App switch has arrived.");
1376 } else {
1377 ALOGD("App switch was abandoned.");
1378 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001379 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001380}
1381
Michael Wrightd02c5b62014-02-10 15:10:22 -08001382bool InputDispatcher::haveCommandsLocked() const {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001383 return !mCommandQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001384}
1385
Prabir Pradhancef936d2021-07-21 16:17:52 +00001386bool InputDispatcher::runCommandsLockedInterruptable() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001387 if (mCommandQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001388 return false;
1389 }
1390
1391 do {
Prabir Pradhancef936d2021-07-21 16:17:52 +00001392 auto command = std::move(mCommandQueue.front());
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001393 mCommandQueue.pop_front();
Prabir Pradhancef936d2021-07-21 16:17:52 +00001394 // Commands are run with the lock held, but may release and re-acquire the lock from within.
1395 command();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001396 } while (!mCommandQueue.empty());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001397 return true;
1398}
1399
Prabir Pradhancef936d2021-07-21 16:17:52 +00001400void InputDispatcher::postCommandLocked(Command&& command) {
1401 mCommandQueue.push_back(command);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001402}
1403
1404void InputDispatcher::drainInboundQueueLocked() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001405 while (!mInboundQueue.empty()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001406 std::shared_ptr<EventEntry> entry = mInboundQueue.front();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001407 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001408 releaseInboundEventLocked(entry);
1409 }
1410 traceInboundQueueLengthLocked();
1411}
1412
1413void InputDispatcher::releasePendingEventLocked() {
1414 if (mPendingEvent) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001415 releaseInboundEventLocked(mPendingEvent);
Yi Kong9b14ac62018-07-17 13:48:38 -07001416 mPendingEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001417 }
1418}
1419
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001420void InputDispatcher::releaseInboundEventLocked(std::shared_ptr<EventEntry> entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001421 InjectionState* injectionState = entry->injectionState;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001422 if (injectionState && injectionState->injectionResult == InputEventInjectionResult::PENDING) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001423 if (DEBUG_DISPATCH_CYCLE) {
1424 ALOGD("Injected inbound event was dropped.");
1425 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001426 setInjectionResult(*entry, InputEventInjectionResult::FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001427 }
1428 if (entry == mNextUnblockedEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001429 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001430 }
1431 addRecentEventLocked(entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001432}
1433
1434void InputDispatcher::resetKeyRepeatLocked() {
1435 if (mKeyRepeatState.lastKeyEntry) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001436 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001437 }
1438}
1439
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001440std::shared_ptr<KeyEntry> InputDispatcher::synthesizeKeyRepeatLocked(nsecs_t currentTime) {
1441 std::shared_ptr<KeyEntry> entry = mKeyRepeatState.lastKeyEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001442
Michael Wright2e732952014-09-24 13:26:59 -07001443 uint32_t policyFlags = entry->policyFlags &
1444 (POLICY_FLAG_RAW_MASK | POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_TRUSTED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001445
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001446 std::shared_ptr<KeyEntry> newEntry =
1447 std::make_unique<KeyEntry>(mIdGenerator.nextId(), currentTime, entry->deviceId,
1448 entry->source, entry->displayId, policyFlags, entry->action,
1449 entry->flags, entry->keyCode, entry->scanCode,
1450 entry->metaState, entry->repeatCount + 1, entry->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001451
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001452 newEntry->syntheticRepeat = true;
1453 mKeyRepeatState.lastKeyEntry = newEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001454 mKeyRepeatState.nextRepeatTime = currentTime + mConfig.keyRepeatDelay;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001455 return newEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001456}
1457
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001458bool InputDispatcher::dispatchConfigurationChangedLocked(nsecs_t currentTime,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001459 const ConfigurationChangedEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001460 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1461 ALOGD("dispatchConfigurationChanged - eventTime=%" PRId64, entry.eventTime);
1462 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001463
1464 // Reset key repeating in case a keyboard device was added or removed or something.
1465 resetKeyRepeatLocked();
1466
1467 // Enqueue a command to run outside the lock to tell the policy that the configuration changed.
Prabir Pradhancef936d2021-07-21 16:17:52 +00001468 auto command = [this, eventTime = entry.eventTime]() REQUIRES(mLock) {
1469 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00001470 mPolicy.notifyConfigurationChanged(eventTime);
Prabir Pradhancef936d2021-07-21 16:17:52 +00001471 };
1472 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001473 return true;
1474}
1475
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001476bool InputDispatcher::dispatchDeviceResetLocked(nsecs_t currentTime,
1477 const DeviceResetEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001478 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1479 ALOGD("dispatchDeviceReset - eventTime=%" PRId64 ", deviceId=%d", entry.eventTime,
1480 entry.deviceId);
1481 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001482
liushenxiang42232912021-05-21 20:24:09 +08001483 // Reset key repeating in case a keyboard device was disabled or enabled.
1484 if (mKeyRepeatState.lastKeyEntry && mKeyRepeatState.lastKeyEntry->deviceId == entry.deviceId) {
1485 resetKeyRepeatLocked();
1486 }
1487
Michael Wrightfb04fd52022-11-24 22:31:11 +00001488 CancelationOptions options(CancelationOptions::Mode::CANCEL_ALL_EVENTS, "device was reset");
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001489 options.deviceId = entry.deviceId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001490 synthesizeCancelationEventsForAllConnectionsLocked(options);
Siarhei Vishniakou0686f0c2023-05-02 11:56:15 -07001491
1492 // Remove all active pointers from this device
1493 for (auto& [_, touchState] : mTouchStatesByDisplay) {
1494 touchState.removeAllPointersForDevice(entry.deviceId);
1495 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001496 return true;
1497}
1498
Vishnu Nairad321cd2020-08-20 16:40:21 -07001499void InputDispatcher::enqueueFocusEventLocked(const sp<IBinder>& windowToken, bool hasFocus,
Vishnu Nairc519ff72021-01-21 08:23:08 -08001500 const std::string& reason) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001501 if (mPendingEvent != nullptr) {
1502 // Move the pending event to the front of the queue. This will give the chance
1503 // for the pending event to get dispatched to the newly focused window
1504 mInboundQueue.push_front(mPendingEvent);
1505 mPendingEvent = nullptr;
1506 }
1507
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001508 std::unique_ptr<FocusEntry> focusEntry =
1509 std::make_unique<FocusEntry>(mIdGenerator.nextId(), now(), windowToken, hasFocus,
1510 reason);
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001511
1512 // This event should go to the front of the queue, but behind all other focus events
1513 // Find the last focus event, and insert right after it
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001514 std::deque<std::shared_ptr<EventEntry>>::reverse_iterator it =
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001515 std::find_if(mInboundQueue.rbegin(), mInboundQueue.rend(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001516 [](const std::shared_ptr<EventEntry>& event) {
1517 return event->type == EventEntry::Type::FOCUS;
1518 });
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001519
1520 // Maintain the order of focus events. Insert the entry after all other focus events.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001521 mInboundQueue.insert(it.base(), std::move(focusEntry));
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001522}
1523
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001524void InputDispatcher::dispatchFocusLocked(nsecs_t currentTime, std::shared_ptr<FocusEntry> entry) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05001525 std::shared_ptr<InputChannel> channel = getInputChannelLocked(entry->connectionToken);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001526 if (channel == nullptr) {
1527 return; // Window has gone away
1528 }
1529 InputTarget target;
1530 target.inputChannel = channel;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08001531 target.flags = InputTarget::Flags::DISPATCH_AS_IS;
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001532 entry->dispatchInProgress = true;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00001533 std::string message = std::string("Focus ") + (entry->hasFocus ? "entering " : "leaving ") +
1534 channel->getName();
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07001535 std::string reason = std::string("reason=").append(entry->reason);
1536 android_log_event_list(LOGTAG_INPUT_FOCUS) << message << reason << LOG_ID_EVENTS;
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001537 dispatchEventLocked(currentTime, entry, {target});
1538}
1539
Prabir Pradhan99987712020-11-10 18:43:05 -08001540void InputDispatcher::dispatchPointerCaptureChangedLocked(
1541 nsecs_t currentTime, const std::shared_ptr<PointerCaptureChangedEntry>& entry,
1542 DropReason& dropReason) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001543 dropReason = DropReason::NOT_DROPPED;
1544
Prabir Pradhan99987712020-11-10 18:43:05 -08001545 const bool haveWindowWithPointerCapture = mWindowTokenWithPointerCapture != nullptr;
Prabir Pradhan99987712020-11-10 18:43:05 -08001546 sp<IBinder> token;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001547
1548 if (entry->pointerCaptureRequest.enable) {
1549 // Enable Pointer Capture.
1550 if (haveWindowWithPointerCapture &&
1551 (entry->pointerCaptureRequest == mCurrentPointerCaptureRequest)) {
Prabir Pradhan7092e262022-05-03 16:51:09 +00001552 // This can happen if pointer capture is disabled and re-enabled before we notify the
1553 // app of the state change, so there is no need to notify the app.
1554 ALOGI("Skipping dispatch of Pointer Capture being enabled: no state change.");
1555 return;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001556 }
1557 if (!mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08001558 // This can happen if a window requests capture and immediately releases capture.
1559 ALOGW("No window requested Pointer Capture.");
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001560 dropReason = DropReason::NO_POINTER_CAPTURE;
Prabir Pradhan99987712020-11-10 18:43:05 -08001561 return;
1562 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001563 if (entry->pointerCaptureRequest.seq != mCurrentPointerCaptureRequest.seq) {
1564 ALOGI("Skipping dispatch of Pointer Capture being enabled: sequence number mismatch.");
1565 return;
1566 }
1567
Vishnu Nairc519ff72021-01-21 08:23:08 -08001568 token = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Prabir Pradhan99987712020-11-10 18:43:05 -08001569 LOG_ALWAYS_FATAL_IF(!token, "Cannot find focused window for Pointer Capture.");
1570 mWindowTokenWithPointerCapture = token;
1571 } else {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001572 // Disable Pointer Capture.
1573 // We do not check if the sequence number matches for requests to disable Pointer Capture
1574 // for two reasons:
1575 // 1. Pointer Capture can be disabled by a focus change, which means we can get two entries
1576 // to disable capture with the same sequence number: one generated by
1577 // disablePointerCaptureForcedLocked() and another as an acknowledgement of Pointer
1578 // Capture being disabled in InputReader.
1579 // 2. We respect any request to disable Pointer Capture generated by InputReader, since the
1580 // actual Pointer Capture state that affects events being generated by input devices is
1581 // in InputReader.
1582 if (!haveWindowWithPointerCapture) {
1583 // Pointer capture was already forcefully disabled because of focus change.
1584 dropReason = DropReason::NOT_DROPPED;
1585 return;
1586 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001587 token = mWindowTokenWithPointerCapture;
1588 mWindowTokenWithPointerCapture = nullptr;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001589 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan7d030382020-12-21 07:58:35 -08001590 setPointerCaptureLocked(false);
1591 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001592 }
1593
1594 auto channel = getInputChannelLocked(token);
1595 if (channel == nullptr) {
1596 // Window has gone away, clean up Pointer Capture state.
1597 mWindowTokenWithPointerCapture = nullptr;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001598 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan7d030382020-12-21 07:58:35 -08001599 setPointerCaptureLocked(false);
1600 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001601 return;
1602 }
1603 InputTarget target;
1604 target.inputChannel = channel;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08001605 target.flags = InputTarget::Flags::DISPATCH_AS_IS;
Prabir Pradhan99987712020-11-10 18:43:05 -08001606 entry->dispatchInProgress = true;
1607 dispatchEventLocked(currentTime, entry, {target});
1608
1609 dropReason = DropReason::NOT_DROPPED;
1610}
1611
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001612void InputDispatcher::dispatchTouchModeChangeLocked(nsecs_t currentTime,
1613 const std::shared_ptr<TouchModeEntry>& entry) {
1614 const std::vector<sp<WindowInfoHandle>>& windowHandles =
Antonio Kantek15beb512022-06-13 22:35:41 +00001615 getWindowHandlesLocked(entry->displayId);
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001616 if (windowHandles.empty()) {
1617 return;
1618 }
1619 const std::vector<InputTarget> inputTargets =
1620 getInputTargetsFromWindowHandlesLocked(windowHandles);
1621 if (inputTargets.empty()) {
1622 return;
1623 }
1624 entry->dispatchInProgress = true;
1625 dispatchEventLocked(currentTime, entry, inputTargets);
1626}
1627
1628std::vector<InputTarget> InputDispatcher::getInputTargetsFromWindowHandlesLocked(
1629 const std::vector<sp<WindowInfoHandle>>& windowHandles) const {
1630 std::vector<InputTarget> inputTargets;
1631 for (const sp<WindowInfoHandle>& handle : windowHandles) {
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001632 const sp<IBinder>& token = handle->getToken();
1633 if (token == nullptr) {
1634 continue;
1635 }
1636 std::shared_ptr<InputChannel> channel = getInputChannelLocked(token);
1637 if (channel == nullptr) {
1638 continue; // Window has gone away
1639 }
1640 InputTarget target;
1641 target.inputChannel = channel;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08001642 target.flags = InputTarget::Flags::DISPATCH_AS_IS;
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001643 inputTargets.push_back(target);
1644 }
1645 return inputTargets;
1646}
1647
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001648bool InputDispatcher::dispatchKeyLocked(nsecs_t currentTime, std::shared_ptr<KeyEntry> entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001649 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001650 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001651 if (!entry->dispatchInProgress) {
1652 if (entry->repeatCount == 0 && entry->action == AKEY_EVENT_ACTION_DOWN &&
1653 (entry->policyFlags & POLICY_FLAG_TRUSTED) &&
1654 (!(entry->policyFlags & POLICY_FLAG_DISABLE_KEY_REPEAT))) {
1655 if (mKeyRepeatState.lastKeyEntry &&
Chris Ye2ad95392020-09-01 13:44:44 -07001656 mKeyRepeatState.lastKeyEntry->keyCode == entry->keyCode &&
Michael Wrightd02c5b62014-02-10 15:10:22 -08001657 // We have seen two identical key downs in a row which indicates that the device
1658 // driver is automatically generating key repeats itself. We take note of the
1659 // repeat here, but we disable our own next key repeat timer since it is clear that
1660 // we will not need to synthesize key repeats ourselves.
Chris Ye2ad95392020-09-01 13:44:44 -07001661 mKeyRepeatState.lastKeyEntry->deviceId == entry->deviceId) {
1662 // Make sure we don't get key down from a different device. If a different
1663 // device Id has same key pressed down, the new device Id will replace the
1664 // current one to hold the key repeat with repeat count reset.
1665 // In the future when got a KEY_UP on the device id, drop it and do not
1666 // stop the key repeat on current device.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001667 entry->repeatCount = mKeyRepeatState.lastKeyEntry->repeatCount + 1;
1668 resetKeyRepeatLocked();
Colin Cross5b799302022-10-18 21:52:41 -07001669 mKeyRepeatState.nextRepeatTime = LLONG_MAX; // don't generate repeats ourselves
Michael Wrightd02c5b62014-02-10 15:10:22 -08001670 } else {
1671 // Not a repeat. Save key down state in case we do see a repeat later.
1672 resetKeyRepeatLocked();
1673 mKeyRepeatState.nextRepeatTime = entry->eventTime + mConfig.keyRepeatTimeout;
1674 }
1675 mKeyRepeatState.lastKeyEntry = entry;
Chris Ye2ad95392020-09-01 13:44:44 -07001676 } else if (entry->action == AKEY_EVENT_ACTION_UP && mKeyRepeatState.lastKeyEntry &&
1677 mKeyRepeatState.lastKeyEntry->deviceId != entry->deviceId) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001678 // The key on device 'deviceId' is still down, do not stop key repeat
Prabir Pradhan65613802023-02-22 23:36:58 +00001679 if (debugInboundEventDetails()) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001680 ALOGD("deviceId=%d got KEY_UP as stale", entry->deviceId);
1681 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001682 } else if (!entry->syntheticRepeat) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001683 resetKeyRepeatLocked();
1684 }
1685
1686 if (entry->repeatCount == 1) {
1687 entry->flags |= AKEY_EVENT_FLAG_LONG_PRESS;
1688 } else {
1689 entry->flags &= ~AKEY_EVENT_FLAG_LONG_PRESS;
1690 }
1691
1692 entry->dispatchInProgress = true;
1693
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001694 logOutboundKeyDetails("dispatchKey - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001695 }
1696
1697 // Handle case where the policy asked us to try again later last time.
Michael Wright5caf55a2022-11-24 22:31:42 +00001698 if (entry->interceptKeyResult == KeyEntry::InterceptKeyResult::TRY_AGAIN_LATER) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001699 if (currentTime < entry->interceptKeyWakeupTime) {
1700 if (entry->interceptKeyWakeupTime < *nextWakeupTime) {
1701 *nextWakeupTime = entry->interceptKeyWakeupTime;
1702 }
1703 return false; // wait until next wakeup
1704 }
Michael Wright5caf55a2022-11-24 22:31:42 +00001705 entry->interceptKeyResult = KeyEntry::InterceptKeyResult::UNKNOWN;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001706 entry->interceptKeyWakeupTime = 0;
1707 }
1708
1709 // Give the policy a chance to intercept the key.
Michael Wright5caf55a2022-11-24 22:31:42 +00001710 if (entry->interceptKeyResult == KeyEntry::InterceptKeyResult::UNKNOWN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001711 if (entry->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07001712 sp<IBinder> focusedWindowToken =
Vishnu Nairc519ff72021-01-21 08:23:08 -08001713 mFocusResolver.getFocusedWindowToken(getTargetDisplayId(*entry));
Prabir Pradhancef936d2021-07-21 16:17:52 +00001714
1715 auto command = [this, focusedWindowToken, entry]() REQUIRES(mLock) {
1716 doInterceptKeyBeforeDispatchingCommand(focusedWindowToken, *entry);
1717 };
1718 postCommandLocked(std::move(command));
Josep del Riob3981622023-04-18 15:49:45 +00001719 // Poke user activity for keys not passed to user
1720 pokeUserActivityLocked(*entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001721 return false; // wait for the command to run
1722 } else {
Michael Wright5caf55a2022-11-24 22:31:42 +00001723 entry->interceptKeyResult = KeyEntry::InterceptKeyResult::CONTINUE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001724 }
Michael Wright5caf55a2022-11-24 22:31:42 +00001725 } else if (entry->interceptKeyResult == KeyEntry::InterceptKeyResult::SKIP) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001726 if (*dropReason == DropReason::NOT_DROPPED) {
1727 *dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001728 }
1729 }
1730
1731 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001732 if (*dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001733 setInjectionResult(*entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001734 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
1735 : InputEventInjectionResult::FAILED);
Garfield Tan6a5a14e2020-01-28 13:24:04 -08001736 mReporter->reportDroppedKey(entry->id);
Josep del Riob3981622023-04-18 15:49:45 +00001737 // Poke user activity for undispatched keys
1738 pokeUserActivityLocked(*entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001739 return true;
1740 }
1741
1742 // Identify targets.
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001743 InputEventInjectionResult injectionResult;
1744 sp<WindowInfoHandle> focusedWindow =
1745 findFocusedWindowTargetLocked(currentTime, *entry, nextWakeupTime,
1746 /*byref*/ injectionResult);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001747 if (injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001748 return false;
1749 }
1750
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001751 setInjectionResult(*entry, injectionResult);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001752 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001753 return true;
1754 }
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001755 LOG_ALWAYS_FATAL_IF(focusedWindow == nullptr);
1756
1757 std::vector<InputTarget> inputTargets;
1758 addWindowTargetLocked(focusedWindow,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08001759 InputTarget::Flags::FOREGROUND | InputTarget::Flags::DISPATCH_AS_IS,
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08001760 /*pointerIds=*/{}, getDownTime(*entry), inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001761
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001762 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001763 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001764
1765 // Dispatch the key.
1766 dispatchEventLocked(currentTime, entry, inputTargets);
1767 return true;
1768}
1769
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001770void InputDispatcher::logOutboundKeyDetails(const char* prefix, const KeyEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001771 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1772 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32 ", "
1773 "policyFlags=0x%x, action=0x%x, flags=0x%x, keyCode=0x%x, scanCode=0x%x, "
1774 "metaState=0x%x, repeatCount=%d, downTime=%" PRId64,
1775 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId,
1776 entry.policyFlags, entry.action, entry.flags, entry.keyCode, entry.scanCode,
1777 entry.metaState, entry.repeatCount, entry.downTime);
1778 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001779}
1780
Prabir Pradhancef936d2021-07-21 16:17:52 +00001781void InputDispatcher::dispatchSensorLocked(nsecs_t currentTime,
1782 const std::shared_ptr<SensorEntry>& entry,
Chris Yef59a2f42020-10-16 12:55:26 -07001783 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001784 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1785 ALOGD("notifySensorEvent eventTime=%" PRId64 ", hwTimestamp=%" PRId64 ", deviceId=%d, "
1786 "source=0x%x, sensorType=%s",
1787 entry->eventTime, entry->hwTimestamp, entry->deviceId, entry->source,
Dominik Laskowski75788452021-02-09 18:51:25 -08001788 ftl::enum_string(entry->sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001789 }
Prabir Pradhancef936d2021-07-21 16:17:52 +00001790 auto command = [this, entry]() REQUIRES(mLock) {
1791 scoped_unlock unlock(mLock);
1792
1793 if (entry->accuracyChanged) {
Prabir Pradhana41d2442023-04-20 21:30:40 +00001794 mPolicy.notifySensorAccuracy(entry->deviceId, entry->sensorType, entry->accuracy);
Prabir Pradhancef936d2021-07-21 16:17:52 +00001795 }
Prabir Pradhana41d2442023-04-20 21:30:40 +00001796 mPolicy.notifySensorEvent(entry->deviceId, entry->sensorType, entry->accuracy,
1797 entry->hwTimestamp, entry->values);
Prabir Pradhancef936d2021-07-21 16:17:52 +00001798 };
1799 postCommandLocked(std::move(command));
Chris Yef59a2f42020-10-16 12:55:26 -07001800}
1801
1802bool InputDispatcher::flushSensor(int deviceId, InputDeviceSensorType sensorType) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001803 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1804 ALOGD("flushSensor deviceId=%d, sensorType=%s", deviceId,
Dominik Laskowski75788452021-02-09 18:51:25 -08001805 ftl::enum_string(sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001806 }
Chris Yef59a2f42020-10-16 12:55:26 -07001807 { // acquire lock
1808 std::scoped_lock _l(mLock);
1809
1810 for (auto it = mInboundQueue.begin(); it != mInboundQueue.end(); it++) {
1811 std::shared_ptr<EventEntry> entry = *it;
1812 if (entry->type == EventEntry::Type::SENSOR) {
1813 it = mInboundQueue.erase(it);
1814 releaseInboundEventLocked(entry);
1815 }
1816 }
1817 }
1818 return true;
1819}
1820
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001821bool InputDispatcher::dispatchMotionLocked(nsecs_t currentTime, std::shared_ptr<MotionEntry> entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001822 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001823 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001824 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001825 if (!entry->dispatchInProgress) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001826 entry->dispatchInProgress = true;
1827
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001828 logOutboundMotionDetails("dispatchMotion - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001829 }
1830
1831 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001832 if (*dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001833 setInjectionResult(*entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001834 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
1835 : InputEventInjectionResult::FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001836 return true;
1837 }
1838
Prabir Pradhanaa561d12021-09-24 06:57:33 -07001839 const bool isPointerEvent = isFromSource(entry->source, AINPUT_SOURCE_CLASS_POINTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001840
1841 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001842 std::vector<InputTarget> inputTargets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001843
1844 bool conflictingPointerActions = false;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001845 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001846 if (isPointerEvent) {
1847 // Pointer event. (eg. touchscreen)
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00001848
1849 if (mDragState &&
1850 (entry->action & AMOTION_EVENT_ACTION_MASK) == AMOTION_EVENT_ACTION_POINTER_DOWN) {
1851 // If drag and drop ongoing and pointer down occur: pilfer drag window pointers
1852 pilferPointersLocked(mDragState->dragWindow->getToken());
1853 }
1854
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08001855 inputTargets =
Siarhei Vishniakou4fe57392022-10-25 13:44:30 -07001856 findTouchedWindowTargetsLocked(currentTime, *entry, &conflictingPointerActions,
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001857 /*byref*/ injectionResult);
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08001858 LOG_ALWAYS_FATAL_IF(injectionResult != InputEventInjectionResult::SUCCEEDED &&
1859 !inputTargets.empty());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001860 } else {
1861 // Non touch event. (eg. trackball)
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001862 sp<WindowInfoHandle> focusedWindow =
1863 findFocusedWindowTargetLocked(currentTime, *entry, nextWakeupTime, injectionResult);
1864 if (injectionResult == InputEventInjectionResult::SUCCEEDED) {
1865 LOG_ALWAYS_FATAL_IF(focusedWindow == nullptr);
1866 addWindowTargetLocked(focusedWindow,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08001867 InputTarget::Flags::FOREGROUND |
1868 InputTarget::Flags::DISPATCH_AS_IS,
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08001869 /*pointerIds=*/{}, getDownTime(*entry), inputTargets);
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001870 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001871 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001872 if (injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001873 return false;
1874 }
1875
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001876 setInjectionResult(*entry, injectionResult);
Prabir Pradhan5735a322022-04-11 17:23:34 +00001877 if (injectionResult == InputEventInjectionResult::TARGET_MISMATCH) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001878 return true;
1879 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001880 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001881 CancelationOptions::Mode mode(
1882 isPointerEvent ? CancelationOptions::Mode::CANCEL_POINTER_EVENTS
1883 : CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS);
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001884 CancelationOptions options(mode, "input event injection failed");
1885 synthesizeCancelationEventsForMonitorsLocked(options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001886 return true;
1887 }
1888
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001889 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001890 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001891
1892 // Dispatch the motion.
1893 if (conflictingPointerActions) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001894 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001895 "conflicting pointer actions");
Michael Wrightd02c5b62014-02-10 15:10:22 -08001896 synthesizeCancelationEventsForAllConnectionsLocked(options);
1897 }
1898 dispatchEventLocked(currentTime, entry, inputTargets);
1899 return true;
1900}
1901
chaviw98318de2021-05-19 16:45:23 -05001902void InputDispatcher::enqueueDragEventLocked(const sp<WindowInfoHandle>& windowHandle,
Arthur Hung54745652022-04-20 07:17:41 +00001903 bool isExiting, const int32_t rawX,
1904 const int32_t rawY) {
1905 const vec2 xy = windowHandle->getInfo()->transform.transform(vec2(rawX, rawY));
arthurhungb89ccb02020-12-30 16:19:01 +08001906 std::unique_ptr<DragEntry> dragEntry =
Arthur Hung54745652022-04-20 07:17:41 +00001907 std::make_unique<DragEntry>(mIdGenerator.nextId(), now(), windowHandle->getToken(),
1908 isExiting, xy.x, xy.y);
arthurhungb89ccb02020-12-30 16:19:01 +08001909
1910 enqueueInboundEventLocked(std::move(dragEntry));
1911}
1912
1913void InputDispatcher::dispatchDragLocked(nsecs_t currentTime, std::shared_ptr<DragEntry> entry) {
1914 std::shared_ptr<InputChannel> channel = getInputChannelLocked(entry->connectionToken);
1915 if (channel == nullptr) {
1916 return; // Window has gone away
1917 }
1918 InputTarget target;
1919 target.inputChannel = channel;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08001920 target.flags = InputTarget::Flags::DISPATCH_AS_IS;
arthurhungb89ccb02020-12-30 16:19:01 +08001921 entry->dispatchInProgress = true;
1922 dispatchEventLocked(currentTime, entry, {target});
1923}
1924
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001925void InputDispatcher::logOutboundMotionDetails(const char* prefix, const MotionEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001926 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -08001927 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=%s, displayId=%" PRId32
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001928 ", policyFlags=0x%x, "
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001929 "action=%s, actionButton=0x%x, flags=0x%x, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001930 "metaState=0x%x, buttonState=0x%x,"
1931 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%" PRId64,
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -08001932 prefix, entry.eventTime, entry.deviceId,
1933 inputEventSourceToString(entry.source).c_str(), entry.displayId, entry.policyFlags,
1934 MotionEvent::actionToString(entry.action).c_str(), entry.actionButton, entry.flags,
1935 entry.metaState, entry.buttonState, entry.edgeFlags, entry.xPrecision,
1936 entry.yPrecision, entry.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001937
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001938 for (uint32_t i = 0; i < entry.pointerCount; i++) {
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07001939 ALOGD(" Pointer %d: id=%d, toolType=%s, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001940 "x=%f, y=%f, pressure=%f, size=%f, "
1941 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
1942 "orientation=%f",
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07001943 i, entry.pointerProperties[i].id,
1944 ftl::enum_string(entry.pointerProperties[i].toolType).c_str(),
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001945 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
1946 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
1947 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
1948 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
1949 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
1950 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
1951 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
1952 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
1953 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
1954 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001955 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001956}
1957
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001958void InputDispatcher::dispatchEventLocked(nsecs_t currentTime,
1959 std::shared_ptr<EventEntry> eventEntry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001960 const std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001961 ATRACE_CALL();
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001962 if (DEBUG_DISPATCH_CYCLE) {
1963 ALOGD("dispatchEventToCurrentInputTargets");
1964 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001965
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00001966 updateInteractionTokensLocked(*eventEntry, inputTargets);
1967
Michael Wrightd02c5b62014-02-10 15:10:22 -08001968 ALOG_ASSERT(eventEntry->dispatchInProgress); // should already have been set to true
1969
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001970 pokeUserActivityLocked(*eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001971
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001972 for (const InputTarget& inputTarget : inputTargets) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07001973 std::shared_ptr<Connection> connection =
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07001974 getConnectionLocked(inputTarget.inputChannel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07001975 if (connection != nullptr) {
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08001976 prepareDispatchCycleLocked(currentTime, connection, eventEntry, inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001977 } else {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001978 if (DEBUG_FOCUS) {
1979 ALOGD("Dropping event delivery to target with channel '%s' because it "
1980 "is no longer registered with the input dispatcher.",
1981 inputTarget.inputChannel->getName().c_str());
1982 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001983 }
1984 }
1985}
1986
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07001987void InputDispatcher::cancelEventsForAnrLocked(const std::shared_ptr<Connection>& connection) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001988 // We will not be breaking any connections here, even if the policy wants us to abort dispatch.
1989 // If the policy decides to close the app, we will get a channel removal event via
1990 // unregisterInputChannel, and will clean up the connection that way. We are already not
1991 // sending new pointers to the connection when it blocked, but focused events will continue to
1992 // pile up.
1993 ALOGW("Canceling events for %s because it is unresponsive",
1994 connection->inputChannel->getName().c_str());
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08001995 if (connection->status == Connection::Status::NORMAL) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001996 CancelationOptions options(CancelationOptions::Mode::CANCEL_ALL_EVENTS,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001997 "application not responding");
1998 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001999 }
2000}
2001
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002002void InputDispatcher::resetNoFocusedWindowTimeoutLocked() {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002003 if (DEBUG_FOCUS) {
2004 ALOGD("Resetting ANR timeouts.");
2005 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002006
2007 // Reset input target wait timeout.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002008 mNoFocusedWindowTimeoutTime = std::nullopt;
Chris Yea209fde2020-07-22 13:54:51 -07002009 mAwaitedFocusedApplication.reset();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002010}
2011
Tiger Huang721e26f2018-07-24 22:26:19 +08002012/**
2013 * Get the display id that the given event should go to. If this event specifies a valid display id,
2014 * then it should be dispatched to that display. Otherwise, the event goes to the focused display.
2015 * Focused display is the display that the user most recently interacted with.
2016 */
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002017int32_t InputDispatcher::getTargetDisplayId(const EventEntry& entry) {
Tiger Huang721e26f2018-07-24 22:26:19 +08002018 int32_t displayId;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002019 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002020 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002021 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
2022 displayId = keyEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002023 break;
2024 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002025 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002026 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
2027 displayId = motionEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002028 break;
2029 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00002030 case EventEntry::Type::TOUCH_MODE_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08002031 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002032 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002033 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07002034 case EventEntry::Type::DEVICE_RESET:
arthurhungb89ccb02020-12-30 16:19:01 +08002035 case EventEntry::Type::SENSOR:
2036 case EventEntry::Type::DRAG: {
Dominik Laskowski75788452021-02-09 18:51:25 -08002037 ALOGE("%s events do not have a target display", ftl::enum_string(entry.type).c_str());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002038 return ADISPLAY_ID_NONE;
2039 }
Tiger Huang721e26f2018-07-24 22:26:19 +08002040 }
2041 return displayId == ADISPLAY_ID_NONE ? mFocusedDisplayId : displayId;
2042}
2043
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002044bool InputDispatcher::shouldWaitToSendKeyLocked(nsecs_t currentTime,
2045 const char* focusedWindowName) {
2046 if (mAnrTracker.empty()) {
2047 // already processed all events that we waited for
2048 mKeyIsWaitingForEventsTimeout = std::nullopt;
2049 return false;
2050 }
2051
2052 if (!mKeyIsWaitingForEventsTimeout.has_value()) {
2053 // Start the timer
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00002054 // Wait to send key because there are unprocessed events that may cause focus to change
Siarhei Vishniakou70622952020-07-30 11:17:23 -05002055 mKeyIsWaitingForEventsTimeout = currentTime +
2056 std::chrono::duration_cast<std::chrono::nanoseconds>(KEY_WAITING_FOR_EVENTS_TIMEOUT)
2057 .count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002058 return true;
2059 }
2060
2061 // We still have pending events, and already started the timer
2062 if (currentTime < *mKeyIsWaitingForEventsTimeout) {
2063 return true; // Still waiting
2064 }
2065
2066 // Waited too long, and some connection still hasn't processed all motions
2067 // Just send the key to the focused window
2068 ALOGW("Dispatching key to %s even though there are other unprocessed events",
2069 focusedWindowName);
2070 mKeyIsWaitingForEventsTimeout = std::nullopt;
2071 return false;
2072}
2073
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002074sp<WindowInfoHandle> InputDispatcher::findFocusedWindowTargetLocked(
2075 nsecs_t currentTime, const EventEntry& entry, nsecs_t* nextWakeupTime,
2076 InputEventInjectionResult& outInjectionResult) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002077 std::string reason;
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002078 outInjectionResult = InputEventInjectionResult::FAILED; // Default result
Michael Wrightd02c5b62014-02-10 15:10:22 -08002079
Tiger Huang721e26f2018-07-24 22:26:19 +08002080 int32_t displayId = getTargetDisplayId(entry);
chaviw98318de2021-05-19 16:45:23 -05002081 sp<WindowInfoHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Chris Yea209fde2020-07-22 13:54:51 -07002082 std::shared_ptr<InputApplicationHandle> focusedApplicationHandle =
Tiger Huang721e26f2018-07-24 22:26:19 +08002083 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
2084
Michael Wrightd02c5b62014-02-10 15:10:22 -08002085 // If there is no currently focused window and no focused application
2086 // then drop the event.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002087 if (focusedWindowHandle == nullptr && focusedApplicationHandle == nullptr) {
2088 ALOGI("Dropping %s event because there is no focused window or focused application in "
2089 "display %" PRId32 ".",
Dominik Laskowski75788452021-02-09 18:51:25 -08002090 ftl::enum_string(entry.type).c_str(), displayId);
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002091 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002092 }
2093
Vishnu Nair062a8672021-09-03 16:07:44 -07002094 // Drop key events if requested by input feature
2095 if (focusedWindowHandle != nullptr && shouldDropInput(entry, focusedWindowHandle)) {
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002096 return nullptr;
Vishnu Nair062a8672021-09-03 16:07:44 -07002097 }
2098
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002099 // Compatibility behavior: raise ANR if there is a focused application, but no focused window.
2100 // Only start counting when we have a focused event to dispatch. The ANR is canceled if we
2101 // start interacting with another application via touch (app switch). This code can be removed
2102 // if the "no focused window ANR" is moved to the policy. Input doesn't know whether
2103 // an app is expected to have a focused window.
2104 if (focusedWindowHandle == nullptr && focusedApplicationHandle != nullptr) {
2105 if (!mNoFocusedWindowTimeoutTime.has_value()) {
2106 // We just discovered that there's no focused window. Start the ANR timer
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05002107 std::chrono::nanoseconds timeout = focusedApplicationHandle->getDispatchingTimeout(
2108 DEFAULT_INPUT_DISPATCHING_TIMEOUT);
2109 mNoFocusedWindowTimeoutTime = currentTime + timeout.count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002110 mAwaitedFocusedApplication = focusedApplicationHandle;
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05002111 mAwaitedApplicationDisplayId = displayId;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002112 ALOGW("Waiting because no window has focus but %s may eventually add a "
2113 "window when it finishes starting up. Will wait for %" PRId64 "ms",
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05002114 mAwaitedFocusedApplication->getName().c_str(), millis(timeout));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002115 *nextWakeupTime = *mNoFocusedWindowTimeoutTime;
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002116 outInjectionResult = InputEventInjectionResult::PENDING;
2117 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002118 } else if (currentTime > *mNoFocusedWindowTimeoutTime) {
2119 // Already raised ANR. Drop the event
2120 ALOGE("Dropping %s event because there is no focused window",
Dominik Laskowski75788452021-02-09 18:51:25 -08002121 ftl::enum_string(entry.type).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002122 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002123 } else {
2124 // Still waiting for the focused window
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002125 outInjectionResult = InputEventInjectionResult::PENDING;
2126 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002127 }
2128 }
2129
2130 // we have a valid, non-null focused window
2131 resetNoFocusedWindowTimeoutLocked();
2132
Prabir Pradhan5735a322022-04-11 17:23:34 +00002133 // Verify targeted injection.
2134 if (const auto err = verifyTargetedInjection(focusedWindowHandle, entry); err) {
2135 ALOGW("Dropping injected event: %s", (*err).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002136 outInjectionResult = InputEventInjectionResult::TARGET_MISMATCH;
2137 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002138 }
2139
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002140 if (focusedWindowHandle->getInfo()->inputConfig.test(
2141 WindowInfo::InputConfig::PAUSE_DISPATCHING)) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002142 ALOGI("Waiting because %s is paused", focusedWindowHandle->getName().c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002143 outInjectionResult = InputEventInjectionResult::PENDING;
2144 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002145 }
2146
2147 // If the event is a key event, then we must wait for all previous events to
2148 // complete before delivering it because previous events may have the
2149 // side-effect of transferring focus to a different window and we want to
2150 // ensure that the following keys are sent to the new window.
2151 //
2152 // Suppose the user touches a button in a window then immediately presses "A".
2153 // If the button causes a pop-up window to appear then we want to ensure that
2154 // the "A" key is delivered to the new pop-up window. This is because users
2155 // often anticipate pending UI changes when typing on a keyboard.
2156 // To obtain this behavior, we must serialize key events with respect to all
2157 // prior input events.
2158 if (entry.type == EventEntry::Type::KEY) {
2159 if (shouldWaitToSendKeyLocked(currentTime, focusedWindowHandle->getName().c_str())) {
2160 *nextWakeupTime = *mKeyIsWaitingForEventsTimeout;
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002161 outInjectionResult = InputEventInjectionResult::PENDING;
2162 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002163 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002164 }
2165
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002166 outInjectionResult = InputEventInjectionResult::SUCCEEDED;
2167 return focusedWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002168}
2169
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002170/**
2171 * Given a list of monitors, remove the ones we cannot find a connection for, and the ones
2172 * that are currently unresponsive.
2173 */
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002174std::vector<Monitor> InputDispatcher::selectResponsiveMonitorsLocked(
2175 const std::vector<Monitor>& monitors) const {
2176 std::vector<Monitor> responsiveMonitors;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002177 std::copy_if(monitors.begin(), monitors.end(), std::back_inserter(responsiveMonitors),
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002178 [this](const Monitor& monitor) REQUIRES(mLock) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07002179 std::shared_ptr<Connection> connection =
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002180 getConnectionLocked(monitor.inputChannel->getConnectionToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002181 if (connection == nullptr) {
2182 ALOGE("Could not find connection for monitor %s",
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002183 monitor.inputChannel->getName().c_str());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002184 return false;
2185 }
2186 if (!connection->responsive) {
2187 ALOGW("Unresponsive monitor %s will not get the new gesture",
2188 connection->inputChannel->getName().c_str());
2189 return false;
2190 }
2191 return true;
2192 });
2193 return responsiveMonitors;
2194}
2195
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07002196/**
2197 * In general, touch should be always split between windows. Some exceptions:
2198 * 1. Don't split touch is if we have an active pointer down, and a new pointer is going down that's
2199 * from the same device, *and* the window that's receiving the current pointer does not support
2200 * split touch.
2201 * 2. Don't split mouse events
2202 */
2203bool InputDispatcher::shouldSplitTouch(const TouchState& touchState,
2204 const MotionEntry& entry) const {
2205 if (isFromSource(entry.source, AINPUT_SOURCE_MOUSE)) {
2206 // We should never split mouse events
2207 return false;
2208 }
2209 for (const TouchedWindow& touchedWindow : touchState.windows) {
2210 if (touchedWindow.windowHandle->getInfo()->isSpy()) {
2211 // Spy windows should not affect whether or not touch is split.
2212 continue;
2213 }
2214 if (touchedWindow.windowHandle->getInfo()->supportsSplitTouch()) {
2215 continue;
2216 }
Arthur Hungc539dbb2022-12-08 07:45:36 +00002217 if (touchedWindow.windowHandle->getInfo()->inputConfig.test(
2218 gui::WindowInfo::InputConfig::IS_WALLPAPER)) {
2219 // Wallpaper window should not affect whether or not touch is split
2220 continue;
2221 }
2222
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07002223 // Eventually, touchedWindow will contain the deviceId of each pointer that's currently
2224 // being sent there. For now, use deviceId from touch state.
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08002225 if (entry.deviceId == touchState.deviceId && touchedWindow.pointerIds.any()) {
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07002226 return false;
2227 }
2228 }
2229 return true;
2230}
2231
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002232std::vector<InputTarget> InputDispatcher::findTouchedWindowTargetsLocked(
Siarhei Vishniakou4fe57392022-10-25 13:44:30 -07002233 nsecs_t currentTime, const MotionEntry& entry, bool* outConflictingPointerActions,
2234 InputEventInjectionResult& outInjectionResult) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002235 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002236
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002237 std::vector<InputTarget> targets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002238 // For security reasons, we defer updating the touch state until we are sure that
2239 // event injection will be allowed.
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002240 const int32_t displayId = entry.displayId;
2241 const int32_t action = entry.action;
Siarhei Vishniakoubf880522023-05-01 11:03:22 -07002242 const int32_t maskedAction = MotionEvent::getActionMasked(action);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002243
2244 // Update the touch state as needed based on the properties of the touch event.
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002245 outInjectionResult = InputEventInjectionResult::PENDING;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002246
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002247 // Copy current touch state into tempTouchState.
2248 // This state will be used to update mTouchStatesByDisplay at the end of this function.
2249 // If no state for the specified display exists, then our initial state will be empty.
Yi Kong9b14ac62018-07-17 13:48:38 -07002250 const TouchState* oldState = nullptr;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002251 TouchState tempTouchState;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002252 if (const auto it = mTouchStatesByDisplay.find(displayId); it != mTouchStatesByDisplay.end()) {
2253 oldState = &(it->second);
Prabir Pradhane680f9b2022-02-04 04:24:00 -08002254 tempTouchState = *oldState;
Jeff Brownf086ddb2014-02-11 14:28:48 -08002255 }
2256
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07002257 bool isSplit = shouldSplitTouch(tempTouchState, entry);
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07002258 const bool switchedDevice = (oldState != nullptr) &&
Siarhei Vishniakou5cee1e32022-11-29 12:35:39 -08002259 (oldState->deviceId != entry.deviceId || oldState->source != entry.source);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002260
2261 const bool isHoverAction = (maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE ||
2262 maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2263 maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT);
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002264 // A DOWN could be generated from POINTER_DOWN if the initial pointers did not land into any
2265 // touchable windows.
2266 const bool wasDown = oldState != nullptr && oldState->isDown();
2267 const bool isDown = (maskedAction == AMOTION_EVENT_ACTION_DOWN) ||
2268 (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN && !wasDown);
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07002269 const bool newGesture = isDown || maskedAction == AMOTION_EVENT_ACTION_SCROLL ||
2270 maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2271 maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE;
Prabir Pradhanaa561d12021-09-24 06:57:33 -07002272 const bool isFromMouse = isFromSource(entry.source, AINPUT_SOURCE_MOUSE);
Siarhei Vishniakou5cee1e32022-11-29 12:35:39 -08002273
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002274 // If pointers are already down, let's finish the current gesture and ignore the new events
2275 // from another device. However, if the new event is a down event, let's cancel the current
2276 // touch and let the new one take over.
2277 if (switchedDevice && wasDown && !isDown) {
2278 LOG(INFO) << "Dropping event because a pointer for device " << oldState->deviceId
2279 << " is already down in display " << displayId << ": " << entry.getDescription();
2280 // TODO(b/211379801): test multiple simultaneous input streams.
2281 outInjectionResult = InputEventInjectionResult::FAILED;
2282 return {}; // wrong device
2283 }
2284
Michael Wrightd02c5b62014-02-10 15:10:22 -08002285 if (newGesture) {
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002286 // If a new gesture is starting, clear the touch state completely.
2287 tempTouchState.reset();
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002288 tempTouchState.deviceId = entry.deviceId;
2289 tempTouchState.source = entry.source;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002290 isSplit = false;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04002291 } else if (switchedDevice && maskedAction == AMOTION_EVENT_ACTION_MOVE) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07002292 ALOGI("Dropping move event because a pointer for a different device is already active "
2293 "in display %" PRId32,
2294 displayId);
Siarhei Vishniakou16e4fa02023-02-16 17:48:56 -08002295 // TODO(b/211379801): test multiple simultaneous input streams.
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002296 outInjectionResult = InputEventInjectionResult::FAILED;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002297 return {}; // wrong device
Michael Wrightd02c5b62014-02-10 15:10:22 -08002298 }
2299
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002300 if (isHoverAction) {
2301 // For hover actions, we will treat 'tempTouchState' as a new state, so let's erase
2302 // all of the existing hovering pointers and recompute.
2303 tempTouchState.clearHoveringPointers();
2304 }
2305
Michael Wrightd02c5b62014-02-10 15:10:22 -08002306 if (newGesture || (isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN)) {
2307 /* Case 1: New splittable pointer going down, or need target for hover or scroll. */
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07002308 const auto [x, y] = resolveTouchedPosition(entry);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002309 const int32_t pointerIndex = getMotionEventActionPointerIndex(action);
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002310 // Outside targets should be added upon first dispatched DOWN event. That means, this should
2311 // be a pointer that would generate ACTION_DOWN, *and* touch should not already be down.
Prabir Pradhand65552b2021-10-07 11:23:50 -07002312 const bool isStylus = isPointerFromStylus(entry, pointerIndex);
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002313 auto [newTouchedWindowHandle, outsideTargets] =
2314 findTouchedWindowAtLocked(displayId, x, y, isStylus);
Michael Wright3dd60e22019-03-27 22:06:44 +00002315
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002316 if (isDown) {
2317 targets += outsideTargets;
2318 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002319 // Handle the case where we did not find a window.
Yi Kong9b14ac62018-07-17 13:48:38 -07002320 if (newTouchedWindowHandle == nullptr) {
Prabir Pradhan82e081e2022-12-06 09:50:09 +00002321 ALOGD("No new touched window at (%.1f, %.1f) in display %" PRId32, x, y, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002322 // Try to assign the pointer to the first foreground window we find, if there is one.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002323 newTouchedWindowHandle = tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002324 }
2325
Prabir Pradhan5735a322022-04-11 17:23:34 +00002326 // Verify targeted injection.
2327 if (const auto err = verifyTargetedInjection(newTouchedWindowHandle, entry); err) {
2328 ALOGW("Dropping injected touch event: %s", (*err).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002329 outInjectionResult = os::InputEventInjectionResult::TARGET_MISMATCH;
Prabir Pradhan5735a322022-04-11 17:23:34 +00002330 newTouchedWindowHandle = nullptr;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002331 return {};
Prabir Pradhan5735a322022-04-11 17:23:34 +00002332 }
2333
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002334 // Figure out whether splitting will be allowed for this window.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002335 if (newTouchedWindowHandle != nullptr) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002336 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
2337 // New window supports splitting, but we should never split mouse events.
2338 isSplit = !isFromMouse;
2339 } else if (isSplit) {
2340 // New window does not support splitting but we have already split events.
2341 // Ignore the new window.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002342 newTouchedWindowHandle = nullptr;
2343 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002344 } else {
2345 // No window is touched, so set split to true. This will allow the next pointer down to
Prabir Pradhan713bb3e2021-12-20 02:07:40 -08002346 // be delivered to a new window which supports split touch. Pointers from a mouse device
2347 // should never be split.
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07002348 isSplit = !isFromMouse;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002349 }
2350
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002351 std::vector<sp<WindowInfoHandle>> newTouchedWindows =
Prabir Pradhand65552b2021-10-07 11:23:50 -07002352 findTouchedSpyWindowsAtLocked(displayId, x, y, isStylus);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002353 if (newTouchedWindowHandle != nullptr) {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002354 // Process the foreground window first so that it is the first to receive the event.
2355 newTouchedWindows.insert(newTouchedWindows.begin(), newTouchedWindowHandle);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002356 }
2357
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002358 if (newTouchedWindows.empty()) {
Prabir Pradhan82e081e2022-12-06 09:50:09 +00002359 ALOGI("Dropping event because there is no touchable window at (%.1f, %.1f) on display "
2360 "%d.",
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002361 x, y, displayId);
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002362 outInjectionResult = InputEventInjectionResult::FAILED;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002363 return {};
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002364 }
2365
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002366 for (const sp<WindowInfoHandle>& windowHandle : newTouchedWindows) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07002367 if (!canWindowReceiveMotionLocked(windowHandle, entry)) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002368 continue;
2369 }
2370
Siarhei Vishniakoub681c202023-05-01 11:22:33 -07002371 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2372 maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE) {
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002373 const int32_t pointerId = entry.pointerProperties[0].id;
Siarhei Vishniakoub681c202023-05-01 11:22:33 -07002374 // The "windowHandle" is the target of this hovering pointer.
2375 tempTouchState.addHoveringPointerToWindow(windowHandle, entry.deviceId, pointerId);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002376 }
2377
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002378 // Set target flags.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002379 ftl::Flags<InputTarget::Flags> targetFlags = InputTarget::Flags::DISPATCH_AS_IS;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002380
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002381 if (canReceiveForegroundTouches(*windowHandle->getInfo())) {
2382 // There should only be one touched window that can be "foreground" for the pointer.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002383 targetFlags |= InputTarget::Flags::FOREGROUND;
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002384 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002385
2386 if (isSplit) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002387 targetFlags |= InputTarget::Flags::SPLIT;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002388 }
2389 if (isWindowObscuredAtPointLocked(windowHandle, x, y)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002390 targetFlags |= InputTarget::Flags::WINDOW_IS_OBSCURED;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002391 } else if (isWindowObscuredLocked(windowHandle)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002392 targetFlags |= InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002393 }
Michael Wright3dd60e22019-03-27 22:06:44 +00002394
2395 // Update the temporary touch state.
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08002396 std::bitset<MAX_POINTER_ID + 1> pointerIds;
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002397 if (!isHoverAction) {
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08002398 pointerIds.set(entry.pointerProperties[pointerIndex].id);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002399 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002400
Siarhei Vishniakoue0431e42023-01-28 17:01:39 -08002401 const bool isDownOrPointerDown = maskedAction == AMOTION_EVENT_ACTION_DOWN ||
2402 maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN;
2403
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002404 // TODO(b/211379801): Currently, even if pointerIds are empty (hover case), we would
2405 // still add a window to the touch state. We should avoid doing that, but some of the
2406 // later checks ("at least one foreground window") rely on this in order to dispatch
2407 // the event properly, so that needs to be updated, possibly by looking at InputTargets.
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002408 tempTouchState.addOrUpdateWindow(windowHandle, targetFlags, pointerIds,
Siarhei Vishniakoue0431e42023-01-28 17:01:39 -08002409 isDownOrPointerDown
2410 ? std::make_optional(entry.eventTime)
2411 : std::nullopt);
Arthur Hungc539dbb2022-12-08 07:45:36 +00002412
2413 // If this is the pointer going down and the touched window has a wallpaper
2414 // then also add the touched wallpaper windows so they are locked in for the duration
2415 // of the touch gesture.
2416 // We do not collect wallpapers during HOVER_MOVE or SCROLL because the wallpaper
2417 // engine only supports touch events. We would need to add a mechanism similar
2418 // to View.onGenericMotionEvent to enable wallpapers to handle these events.
Siarhei Vishniakoue0431e42023-01-28 17:01:39 -08002419 if (isDownOrPointerDown) {
Arthur Hungc539dbb2022-12-08 07:45:36 +00002420 if (targetFlags.test(InputTarget::Flags::FOREGROUND) &&
2421 windowHandle->getInfo()->inputConfig.test(
2422 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER)) {
2423 sp<WindowInfoHandle> wallpaper = findWallpaperWindowBelow(windowHandle);
2424 if (wallpaper != nullptr) {
2425 ftl::Flags<InputTarget::Flags> wallpaperFlags =
2426 InputTarget::Flags::WINDOW_IS_OBSCURED |
2427 InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED |
2428 InputTarget::Flags::DISPATCH_AS_IS;
2429 if (isSplit) {
2430 wallpaperFlags |= InputTarget::Flags::SPLIT;
2431 }
2432 tempTouchState.addOrUpdateWindow(wallpaper, wallpaperFlags, pointerIds,
2433 entry.eventTime);
2434 }
2435 }
2436 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002437 }
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00002438
Siarhei Vishniakou060f82b2023-01-27 06:39:14 -08002439 // If a window is already pilfering some pointers, give it this new pointer as well and
2440 // make it pilfering. This will prevent other non-spy windows from getting this pointer,
2441 // which is a specific behaviour that we want.
2442 const int32_t pointerId = entry.pointerProperties[pointerIndex].id;
2443 for (TouchedWindow& touchedWindow : tempTouchState.windows) {
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08002444 if (touchedWindow.pointerIds.test(pointerId) &&
Siarhei Vishniakou060f82b2023-01-27 06:39:14 -08002445 touchedWindow.pilferedPointerIds.count() > 0) {
2446 // This window is already pilfering some pointers, and this new pointer is also
2447 // going to it. Therefore, take over this pointer and don't give it to anyone
2448 // else.
2449 touchedWindow.pilferedPointerIds.set(pointerId);
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00002450 }
2451 }
Siarhei Vishniakou060f82b2023-01-27 06:39:14 -08002452
2453 // Restrict all pilfered pointers to the pilfering windows.
2454 tempTouchState.cancelPointersForNonPilferingWindows();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002455 } else {
2456 /* Case 2: Pointer move, up, cancel or non-splittable pointer down. */
2457
2458 // If the pointer is not currently down, then ignore the event.
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07002459 if (!tempTouchState.isDown() && maskedAction != AMOTION_EVENT_ACTION_HOVER_EXIT) {
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002460 LOG(INFO) << "Dropping event because the pointer is not down or we previously "
2461 "dropped the pointer down event in display "
2462 << displayId << ": " << entry.getDescription();
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002463 outInjectionResult = InputEventInjectionResult::FAILED;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002464 return {};
Michael Wrightd02c5b62014-02-10 15:10:22 -08002465 }
2466
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07002467 // If the pointer is not currently hovering, then ignore the event.
2468 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT) {
2469 const int32_t pointerId = entry.pointerProperties[0].id;
2470 if (oldState == nullptr ||
2471 oldState->getWindowsWithHoveringPointer(entry.deviceId, pointerId).empty()) {
2472 LOG(INFO) << "Dropping event because the hovering pointer is not in any windows in "
2473 "display "
2474 << displayId << ": " << entry.getDescription();
2475 outInjectionResult = InputEventInjectionResult::FAILED;
2476 return {};
2477 }
2478 tempTouchState.removeHoveringPointer(entry.deviceId, pointerId);
2479 }
2480
arthurhung6d4bed92021-03-17 11:59:33 +08002481 addDragEventLocked(entry);
arthurhungb89ccb02020-12-30 16:19:01 +08002482
Michael Wrightd02c5b62014-02-10 15:10:22 -08002483 // Check whether touches should slip outside of the current foreground window.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002484 if (maskedAction == AMOTION_EVENT_ACTION_MOVE && entry.pointerCount == 1 &&
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002485 tempTouchState.isSlippery()) {
Siarhei Vishniakou9306c382022-09-30 15:30:31 -07002486 const auto [x, y] = resolveTouchedPosition(entry);
Harry Cutts33476232023-01-30 19:57:29 +00002487 const bool isStylus = isPointerFromStylus(entry, /*pointerIndex=*/0);
chaviw98318de2021-05-19 16:45:23 -05002488 sp<WindowInfoHandle> oldTouchedWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002489 tempTouchState.getFirstForegroundWindowHandle();
Siarhei Vishniakou0f6558d2023-04-21 12:05:13 -07002490 LOG_ALWAYS_FATAL_IF(oldTouchedWindowHandle == nullptr);
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002491 auto [newTouchedWindowHandle, _] = findTouchedWindowAtLocked(displayId, x, y, isStylus);
Vishnu Nair062a8672021-09-03 16:07:44 -07002492
Prabir Pradhan5735a322022-04-11 17:23:34 +00002493 // Verify targeted injection.
2494 if (const auto err = verifyTargetedInjection(newTouchedWindowHandle, entry); err) {
2495 ALOGW("Dropping injected event: %s", (*err).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002496 outInjectionResult = os::InputEventInjectionResult::TARGET_MISMATCH;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002497 return {};
Prabir Pradhan5735a322022-04-11 17:23:34 +00002498 }
2499
Vishnu Nair062a8672021-09-03 16:07:44 -07002500 // Drop touch events if requested by input feature
2501 if (newTouchedWindowHandle != nullptr &&
2502 shouldDropInput(entry, newTouchedWindowHandle)) {
2503 newTouchedWindowHandle = nullptr;
2504 }
2505
Siarhei Vishniakouafa08cc2023-05-08 22:35:50 -07002506 if (newTouchedWindowHandle != nullptr &&
2507 !haveSameToken(oldTouchedWindowHandle, newTouchedWindowHandle)) {
Siarhei Vishniakou0f6558d2023-04-21 12:05:13 -07002508 ALOGD("Touch is slipping out of window %s into window %s in display %" PRId32,
2509 oldTouchedWindowHandle->getName().c_str(),
2510 newTouchedWindowHandle->getName().c_str(), displayId);
2511
Michael Wrightd02c5b62014-02-10 15:10:22 -08002512 // Make a slippery exit from the old window.
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08002513 std::bitset<MAX_POINTER_ID + 1> pointerIds;
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002514 const int32_t pointerId = entry.pointerProperties[0].id;
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08002515 pointerIds.set(pointerId);
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002516
2517 const TouchedWindow& touchedWindow =
2518 tempTouchState.getTouchedWindow(oldTouchedWindowHandle);
2519 addWindowTargetLocked(oldTouchedWindowHandle,
2520 InputTarget::Flags::DISPATCH_AS_SLIPPERY_EXIT, pointerIds,
2521 touchedWindow.firstDownTimeInTarget, targets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002522
2523 // Make a slippery entrance into the new window.
2524 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
Prabir Pradhan713bb3e2021-12-20 02:07:40 -08002525 isSplit = !isFromMouse;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002526 }
2527
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002528 ftl::Flags<InputTarget::Flags> targetFlags =
2529 InputTarget::Flags::DISPATCH_AS_SLIPPERY_ENTER;
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002530 if (canReceiveForegroundTouches(*newTouchedWindowHandle->getInfo())) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002531 targetFlags |= InputTarget::Flags::FOREGROUND;
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002532 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002533 if (isSplit) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002534 targetFlags |= InputTarget::Flags::SPLIT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002535 }
2536 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002537 targetFlags |= InputTarget::Flags::WINDOW_IS_OBSCURED;
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002538 } else if (isWindowObscuredLocked(newTouchedWindowHandle)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002539 targetFlags |= InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002540 }
2541
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002542 tempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds,
2543 entry.eventTime);
Arthur Hungc539dbb2022-12-08 07:45:36 +00002544
2545 // Check if the wallpaper window should deliver the corresponding event.
2546 slipWallpaperTouch(targetFlags, oldTouchedWindowHandle, newTouchedWindowHandle,
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002547 tempTouchState, pointerId, targets);
2548 tempTouchState.removeTouchedPointerFromWindow(pointerId, oldTouchedWindowHandle);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002549 }
2550 }
Arthur Hung96483742022-11-15 03:30:48 +00002551
2552 // Update the pointerIds for non-splittable when it received pointer down.
2553 if (!isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN) {
2554 // If no split, we suppose all touched windows should receive pointer down.
2555 const int32_t pointerIndex = getMotionEventActionPointerIndex(action);
2556 for (size_t i = 0; i < tempTouchState.windows.size(); i++) {
2557 TouchedWindow& touchedWindow = tempTouchState.windows[i];
2558 // Ignore drag window for it should just track one pointer.
2559 if (mDragState && mDragState->dragWindow == touchedWindow.windowHandle) {
2560 continue;
2561 }
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08002562 touchedWindow.pointerIds.set(entry.pointerProperties[pointerIndex].id);
Arthur Hung96483742022-11-15 03:30:48 +00002563 }
2564 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002565 }
2566
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002567 // Update dispatching for hover enter and exit.
Sam Dubeyf886dec2023-01-27 13:28:19 +00002568 {
2569 std::vector<TouchedWindow> hoveringWindows =
2570 getHoveringWindowsLocked(oldState, tempTouchState, entry);
2571 for (const TouchedWindow& touchedWindow : hoveringWindows) {
Siarhei Vishniakoud5876ba2023-05-15 17:58:34 -07002572 std::optional<InputTarget> target =
2573 createInputTargetLocked(touchedWindow.windowHandle, touchedWindow.targetFlags,
2574 touchedWindow.firstDownTimeInTarget);
2575 if (!target) {
2576 continue;
2577 }
2578 // Hardcode to single hovering pointer for now.
2579 std::bitset<MAX_POINTER_ID + 1> pointerIds;
2580 pointerIds.set(entry.pointerProperties[0].id);
2581 target->addPointers(pointerIds, touchedWindow.windowHandle->getInfo()->transform);
2582 targets.push_back(*target);
Sam Dubeyf886dec2023-01-27 13:28:19 +00002583 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002584 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002585
Prabir Pradhan5735a322022-04-11 17:23:34 +00002586 // Ensure that all touched windows are valid for injection.
2587 if (entry.injectionState != nullptr) {
2588 std::string errs;
2589 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002590 if (touchedWindow.targetFlags.test(InputTarget::Flags::DISPATCH_AS_OUTSIDE)) {
Prabir Pradhan5735a322022-04-11 17:23:34 +00002591 // Allow ACTION_OUTSIDE events generated by targeted injection to be
2592 // dispatched to any uid, since the coords will be zeroed out later.
2593 continue;
2594 }
2595 const auto err = verifyTargetedInjection(touchedWindow.windowHandle, entry);
2596 if (err) errs += "\n - " + *err;
2597 }
2598 if (!errs.empty()) {
2599 ALOGW("Dropping targeted injection: At least one touched window is not owned by uid "
2600 "%d:%s",
2601 *entry.injectionState->targetUid, errs.c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002602 outInjectionResult = InputEventInjectionResult::TARGET_MISMATCH;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002603 return {};
Prabir Pradhan5735a322022-04-11 17:23:34 +00002604 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002605 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002606
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002607 // Check whether windows listening for outside touches are owned by the same UID. If the owner
2608 // has a different UID, then we will not reveal coordinate information to this window.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002609 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
chaviw98318de2021-05-19 16:45:23 -05002610 sp<WindowInfoHandle> foregroundWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002611 tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002612 if (foregroundWindowHandle) {
2613 const int32_t foregroundWindowUid = foregroundWindowHandle->getInfo()->ownerUid;
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002614 for (InputTarget& target : targets) {
2615 if (target.flags.test(InputTarget::Flags::DISPATCH_AS_OUTSIDE)) {
2616 sp<WindowInfoHandle> targetWindow =
2617 getWindowHandleLocked(target.inputChannel->getConnectionToken());
2618 if (targetWindow->getInfo()->ownerUid != foregroundWindowUid) {
2619 target.flags |= InputTarget::Flags::ZERO_COORDS;
Michael Wright3dd60e22019-03-27 22:06:44 +00002620 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002621 }
2622 }
2623 }
2624 }
2625
Harry Cuttsb166c002023-05-09 13:06:05 +00002626 // If this is a touchpad navigation gesture, it needs to only be sent to trusted targets, as we
2627 // only want the system UI to handle these gestures.
2628 const bool isTouchpadNavGesture = isFromSource(entry.source, AINPUT_SOURCE_MOUSE) &&
2629 entry.classification == MotionClassification::MULTI_FINGER_SWIPE;
2630 if (isTouchpadNavGesture) {
2631 filterUntrustedTargets(/* byref */ tempTouchState, /* byref */ targets);
2632 }
2633
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07002634 // Output targets from the touch state.
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002635 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08002636 if (touchedWindow.pointerIds.none() && !touchedWindow.hasHoveringPointers(entry.deviceId)) {
Siarhei Vishniakoue0431e42023-01-28 17:01:39 -08002637 // Windows with hovering pointers are getting persisted inside TouchState.
2638 // Do not send this event to those windows.
2639 continue;
2640 }
Harry Cuttsb166c002023-05-09 13:06:05 +00002641
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002642 addWindowTargetLocked(touchedWindow.windowHandle, touchedWindow.targetFlags,
2643 touchedWindow.pointerIds, touchedWindow.firstDownTimeInTarget,
2644 targets);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002645 }
Sam Dubey39d37cf2022-12-07 18:05:35 +00002646
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07002647 if (targets.empty()) {
2648 LOG(INFO) << "Dropping event because no targets were found: " << entry.getDescription();
2649 outInjectionResult = InputEventInjectionResult::FAILED;
2650 return {};
2651 }
2652
2653 // If we only have windows getting ACTION_OUTSIDE, then drop the event, because there is no
2654 // window that is actually receiving the entire gesture.
2655 if (std::all_of(targets.begin(), targets.end(), [](const InputTarget& target) {
2656 return target.flags.test(InputTarget::Flags::DISPATCH_AS_OUTSIDE);
2657 })) {
2658 LOG(INFO) << "Dropping event because all windows would just receive ACTION_OUTSIDE: "
2659 << entry.getDescription();
2660 outInjectionResult = InputEventInjectionResult::FAILED;
2661 return {};
2662 }
2663
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002664 outInjectionResult = InputEventInjectionResult::SUCCEEDED;
Sam Dubeyf886dec2023-01-27 13:28:19 +00002665 // Drop the outside or hover touch windows since we will not care about them
2666 // in the next iteration.
2667 tempTouchState.filterNonAsIsTouchWindows();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002668
Michael Wrightd02c5b62014-02-10 15:10:22 -08002669 // Update final pieces of touch state if the injector had permission.
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002670 if (switchedDevice) {
2671 if (DEBUG_FOCUS) {
2672 ALOGD("Conflicting pointer actions: Switched to a different device.");
2673 }
2674 *outConflictingPointerActions = true;
2675 }
2676
2677 if (isHoverAction) {
2678 // Started hovering, therefore no longer down.
Siarhei Vishniakou3ad385b2022-11-04 10:09:53 -07002679 if (oldState && oldState->isDown()) {
Siarhei Vishniakou6e1e9872022-11-08 17:51:35 -08002680 ALOGD_IF(DEBUG_FOCUS,
2681 "Conflicting pointer actions: Hover received while pointer was down.");
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002682 *outConflictingPointerActions = true;
2683 }
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002684 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2685 maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE) {
2686 tempTouchState.deviceId = entry.deviceId;
2687 tempTouchState.source = entry.source;
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002688 }
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002689 } else if (maskedAction == AMOTION_EVENT_ACTION_UP) {
2690 // Pointer went up.
2691 tempTouchState.removeTouchedPointer(entry.pointerProperties[0].id);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002692 } else if (maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002693 // All pointers up or canceled.
2694 tempTouchState.reset();
2695 } else if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
2696 // First pointer went down.
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002697 if (oldState && (oldState->isDown() || oldState->hasHoveringPointers())) {
2698 ALOGD("Conflicting pointer actions: Down received while already down or hovering.");
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002699 *outConflictingPointerActions = true;
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002700 }
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002701 } else if (maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
2702 // One pointer went up.
2703 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
2704 uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002705
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002706 for (size_t i = 0; i < tempTouchState.windows.size();) {
2707 TouchedWindow& touchedWindow = tempTouchState.windows[i];
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08002708 touchedWindow.pointerIds.reset(pointerId);
2709 if (touchedWindow.pointerIds.none()) {
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002710 tempTouchState.windows.erase(tempTouchState.windows.begin() + i);
2711 continue;
2712 }
2713 i += 1;
2714 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002715 }
2716
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002717 // Save changes unless the action was scroll in which case the temporary touch
2718 // state was only valid for this one action.
2719 if (maskedAction != AMOTION_EVENT_ACTION_SCROLL) {
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07002720 if (displayId >= 0) {
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002721 tempTouchState.clearWindowsWithoutPointers();
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002722 mTouchStatesByDisplay[displayId] = tempTouchState;
2723 } else {
2724 mTouchStatesByDisplay.erase(displayId);
2725 }
2726 }
2727
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -08002728 if (tempTouchState.windows.empty()) {
2729 mTouchStatesByDisplay.erase(displayId);
2730 }
2731
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002732 return targets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002733}
2734
arthurhung6d4bed92021-03-17 11:59:33 +08002735void InputDispatcher::finishDragAndDrop(int32_t displayId, float x, float y) {
Prabir Pradhand65552b2021-10-07 11:23:50 -07002736 // Prevent stylus interceptor windows from affecting drag and drop behavior for now, until we
2737 // have an explicit reason to support it.
2738 constexpr bool isStylus = false;
2739
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002740 auto [dropWindow, _] =
Harry Cutts33476232023-01-30 19:57:29 +00002741 findTouchedWindowAtLocked(displayId, x, y, isStylus, /*ignoreDragWindow=*/true);
arthurhung6d4bed92021-03-17 11:59:33 +08002742 if (dropWindow) {
2743 vec2 local = dropWindow->getInfo()->transform.transform(x, y);
Prabir Pradhancef936d2021-07-21 16:17:52 +00002744 sendDropWindowCommandLocked(dropWindow->getToken(), local.x, local.y);
Arthur Hung6d0571e2021-04-09 20:18:16 +08002745 } else {
Arthur Hung54745652022-04-20 07:17:41 +00002746 ALOGW("No window found when drop.");
Prabir Pradhancef936d2021-07-21 16:17:52 +00002747 sendDropWindowCommandLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08002748 }
2749 mDragState.reset();
2750}
2751
2752void InputDispatcher::addDragEventLocked(const MotionEntry& entry) {
Arthur Hung3915c1f2022-05-31 07:17:17 +00002753 if (!mDragState || mDragState->dragWindow->getInfo()->displayId != entry.displayId) {
arthurhungb89ccb02020-12-30 16:19:01 +08002754 return;
2755 }
2756
arthurhung6d4bed92021-03-17 11:59:33 +08002757 if (!mDragState->isStartDrag) {
2758 mDragState->isStartDrag = true;
2759 mDragState->isStylusButtonDownAtStart =
2760 (entry.buttonState & AMOTION_EVENT_BUTTON_STYLUS_PRIMARY) != 0;
2761 }
2762
Arthur Hung54745652022-04-20 07:17:41 +00002763 // Find the pointer index by id.
2764 int32_t pointerIndex = 0;
2765 for (; static_cast<uint32_t>(pointerIndex) < entry.pointerCount; pointerIndex++) {
2766 const PointerProperties& pointerProperties = entry.pointerProperties[pointerIndex];
2767 if (pointerProperties.id == mDragState->pointerId) {
2768 break;
arthurhung6d4bed92021-03-17 11:59:33 +08002769 }
Arthur Hung54745652022-04-20 07:17:41 +00002770 }
arthurhung6d4bed92021-03-17 11:59:33 +08002771
Arthur Hung54745652022-04-20 07:17:41 +00002772 if (uint32_t(pointerIndex) == entry.pointerCount) {
2773 LOG_ALWAYS_FATAL("Should find a valid pointer index by id %d", mDragState->pointerId);
Arthur Hung54745652022-04-20 07:17:41 +00002774 }
2775
2776 const int32_t maskedAction = entry.action & AMOTION_EVENT_ACTION_MASK;
2777 const int32_t x = entry.pointerCoords[pointerIndex].getX();
2778 const int32_t y = entry.pointerCoords[pointerIndex].getY();
2779
2780 switch (maskedAction) {
2781 case AMOTION_EVENT_ACTION_MOVE: {
2782 // Handle the special case : stylus button no longer pressed.
2783 bool isStylusButtonDown =
2784 (entry.buttonState & AMOTION_EVENT_BUTTON_STYLUS_PRIMARY) != 0;
2785 if (mDragState->isStylusButtonDownAtStart && !isStylusButtonDown) {
2786 finishDragAndDrop(entry.displayId, x, y);
2787 return;
2788 }
2789
2790 // Prevent stylus interceptor windows from affecting drag and drop behavior for now,
2791 // until we have an explicit reason to support it.
2792 constexpr bool isStylus = false;
2793
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002794 auto [hoverWindowHandle, _] = findTouchedWindowAtLocked(entry.displayId, x, y, isStylus,
Harry Cutts33476232023-01-30 19:57:29 +00002795 /*ignoreDragWindow=*/true);
Arthur Hung54745652022-04-20 07:17:41 +00002796 // enqueue drag exit if needed.
2797 if (hoverWindowHandle != mDragState->dragHoverWindowHandle &&
2798 !haveSameToken(hoverWindowHandle, mDragState->dragHoverWindowHandle)) {
2799 if (mDragState->dragHoverWindowHandle != nullptr) {
Harry Cutts33476232023-01-30 19:57:29 +00002800 enqueueDragEventLocked(mDragState->dragHoverWindowHandle, /*isExiting=*/true, x,
Arthur Hung54745652022-04-20 07:17:41 +00002801 y);
2802 }
2803 mDragState->dragHoverWindowHandle = hoverWindowHandle;
2804 }
2805 // enqueue drag location if needed.
2806 if (hoverWindowHandle != nullptr) {
Harry Cutts33476232023-01-30 19:57:29 +00002807 enqueueDragEventLocked(hoverWindowHandle, /*isExiting=*/false, x, y);
Arthur Hung54745652022-04-20 07:17:41 +00002808 }
2809 break;
2810 }
2811
2812 case AMOTION_EVENT_ACTION_POINTER_UP:
2813 if (getMotionEventActionPointerIndex(entry.action) != pointerIndex) {
2814 break;
2815 }
2816 // The drag pointer is up.
2817 [[fallthrough]];
2818 case AMOTION_EVENT_ACTION_UP:
2819 finishDragAndDrop(entry.displayId, x, y);
2820 break;
2821 case AMOTION_EVENT_ACTION_CANCEL: {
2822 ALOGD("Receiving cancel when drag and drop.");
2823 sendDropWindowCommandLocked(nullptr, 0, 0);
2824 mDragState.reset();
2825 break;
2826 }
arthurhungb89ccb02020-12-30 16:19:01 +08002827 }
2828}
2829
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002830std::optional<InputTarget> InputDispatcher::createInputTargetLocked(
2831 const sp<android::gui::WindowInfoHandle>& windowHandle,
2832 ftl::Flags<InputTarget::Flags> targetFlags,
2833 std::optional<nsecs_t> firstDownTimeInTarget) const {
2834 std::shared_ptr<InputChannel> inputChannel = getInputChannelLocked(windowHandle->getToken());
2835 if (inputChannel == nullptr) {
2836 ALOGW("Not creating InputTarget for %s, no input channel", windowHandle->getName().c_str());
2837 return {};
2838 }
2839 InputTarget inputTarget;
2840 inputTarget.inputChannel = inputChannel;
2841 inputTarget.flags = targetFlags;
2842 inputTarget.globalScaleFactor = windowHandle->getInfo()->globalScaleFactor;
2843 inputTarget.firstDownTimeInTarget = firstDownTimeInTarget;
2844 const auto& displayInfoIt = mDisplayInfos.find(windowHandle->getInfo()->displayId);
2845 if (displayInfoIt != mDisplayInfos.end()) {
2846 inputTarget.displayTransform = displayInfoIt->second.transform;
2847 } else {
2848 // DisplayInfo not found for this window on display windowInfo->displayId.
2849 // TODO(b/198444055): Make this an error message after 'setInputWindows' API is removed.
2850 }
2851 return inputTarget;
2852}
2853
chaviw98318de2021-05-19 16:45:23 -05002854void InputDispatcher::addWindowTargetLocked(const sp<WindowInfoHandle>& windowHandle,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002855 ftl::Flags<InputTarget::Flags> targetFlags,
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08002856 std::bitset<MAX_POINTER_ID + 1> pointerIds,
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002857 std::optional<nsecs_t> firstDownTimeInTarget,
Siarhei Vishniakouf75cddb2022-10-25 10:42:16 -07002858 std::vector<InputTarget>& inputTargets) const {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002859 std::vector<InputTarget>::iterator it =
2860 std::find_if(inputTargets.begin(), inputTargets.end(),
2861 [&windowHandle](const InputTarget& inputTarget) {
2862 return inputTarget.inputChannel->getConnectionToken() ==
2863 windowHandle->getToken();
2864 });
Chavi Weingarten97b8eec2020-01-09 18:09:08 +00002865
chaviw98318de2021-05-19 16:45:23 -05002866 const WindowInfo* windowInfo = windowHandle->getInfo();
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002867
2868 if (it == inputTargets.end()) {
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002869 std::optional<InputTarget> target =
2870 createInputTargetLocked(windowHandle, targetFlags, firstDownTimeInTarget);
2871 if (!target) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002872 return;
2873 }
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002874 inputTargets.push_back(*target);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002875 it = inputTargets.end() - 1;
2876 }
2877
2878 ALOG_ASSERT(it->flags == targetFlags);
2879 ALOG_ASSERT(it->globalScaleFactor == windowInfo->globalScaleFactor);
2880
chaviw1ff3d1e2020-07-01 15:53:47 -07002881 it->addPointers(pointerIds, windowInfo->transform);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002882}
2883
Michael Wright3dd60e22019-03-27 22:06:44 +00002884void InputDispatcher::addGlobalMonitoringTargetsLocked(std::vector<InputTarget>& inputTargets,
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002885 int32_t displayId) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002886 auto monitorsIt = mGlobalMonitorsByDisplay.find(displayId);
2887 if (monitorsIt == mGlobalMonitorsByDisplay.end()) return;
Michael Wright3dd60e22019-03-27 22:06:44 +00002888
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002889 for (const Monitor& monitor : selectResponsiveMonitorsLocked(monitorsIt->second)) {
2890 InputTarget target;
2891 target.inputChannel = monitor.inputChannel;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002892 target.flags = InputTarget::Flags::DISPATCH_AS_IS;
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002893 // target.firstDownTimeInTarget is not set for global monitors. It is only required in split
2894 // touch and global monitoring works as intended even without setting firstDownTimeInTarget
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002895 if (const auto& it = mDisplayInfos.find(displayId); it != mDisplayInfos.end()) {
2896 target.displayTransform = it->second.transform;
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002897 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002898 target.setDefaultPointerTransform(target.displayTransform);
2899 inputTargets.push_back(target);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002900 }
2901}
2902
Robert Carrc9bf1d32020-04-13 17:21:08 -07002903/**
2904 * Indicate whether one window handle should be considered as obscuring
2905 * another window handle. We only check a few preconditions. Actually
2906 * checking the bounds is left to the caller.
2907 */
chaviw98318de2021-05-19 16:45:23 -05002908static bool canBeObscuredBy(const sp<WindowInfoHandle>& windowHandle,
2909 const sp<WindowInfoHandle>& otherHandle) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002910 // Compare by token so cloned layers aren't counted
2911 if (haveSameToken(windowHandle, otherHandle)) {
2912 return false;
2913 }
2914 auto info = windowHandle->getInfo();
2915 auto otherInfo = otherHandle->getInfo();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002916 if (otherInfo->inputConfig.test(WindowInfo::InputConfig::NOT_VISIBLE)) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002917 return false;
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002918 } else if (otherInfo->alpha == 0 &&
2919 otherInfo->inputConfig.test(WindowInfo::InputConfig::NOT_TOUCHABLE)) {
Bernardo Rufino653d2e02020-10-20 17:32:40 +00002920 // Those act as if they were invisible, so we don't need to flag them.
2921 // We do want to potentially flag touchable windows even if they have 0
2922 // opacity, since they can consume touches and alter the effects of the
2923 // user interaction (eg. apps that rely on
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002924 // Flags::WINDOW_IS_PARTIALLY_OBSCURED should still be told about those
Bernardo Rufino653d2e02020-10-20 17:32:40 +00002925 // windows), hence we also check for FLAG_NOT_TOUCHABLE.
2926 return false;
Bernardo Rufino8007daf2020-09-22 09:40:01 +00002927 } else if (info->ownerUid == otherInfo->ownerUid) {
2928 // If ownerUid is the same we don't generate occlusion events as there
2929 // is no security boundary within an uid.
Robert Carrc9bf1d32020-04-13 17:21:08 -07002930 return false;
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002931 } else if (otherInfo->inputConfig.test(gui::WindowInfo::InputConfig::TRUSTED_OVERLAY)) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002932 return false;
2933 } else if (otherInfo->displayId != info->displayId) {
2934 return false;
2935 }
2936 return true;
2937}
2938
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002939/**
2940 * Returns touch occlusion information in the form of TouchOcclusionInfo. To check if the touch is
2941 * untrusted, one should check:
2942 *
2943 * 1. If result.hasBlockingOcclusion is true.
2944 * If it's, it means the touch should be blocked due to a window with occlusion mode of
2945 * BLOCK_UNTRUSTED.
2946 *
2947 * 2. If result.obscuringOpacity > mMaximumObscuringOpacityForTouch.
2948 * If it is (and 1 is false), then the touch should be blocked because a stack of windows
2949 * (possibly only one) with occlusion mode of USE_OPACITY from one UID resulted in a composed
2950 * obscuring opacity above the threshold. Note that if there was no window of occlusion mode
2951 * USE_OPACITY, result.obscuringOpacity would've been 0 and since
2952 * mMaximumObscuringOpacityForTouch >= 0, the condition above would never be true.
2953 *
2954 * If neither of those is true, then it means the touch can be allowed.
2955 */
2956InputDispatcher::TouchOcclusionInfo InputDispatcher::computeTouchOcclusionInfoLocked(
chaviw98318de2021-05-19 16:45:23 -05002957 const sp<WindowInfoHandle>& windowHandle, int32_t x, int32_t y) const {
2958 const WindowInfo* windowInfo = windowHandle->getInfo();
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002959 int32_t displayId = windowInfo->displayId;
chaviw98318de2021-05-19 16:45:23 -05002960 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002961 TouchOcclusionInfo info;
2962 info.hasBlockingOcclusion = false;
2963 info.obscuringOpacity = 0;
2964 info.obscuringUid = -1;
2965 std::map<int32_t, float> opacityByUid;
chaviw98318de2021-05-19 16:45:23 -05002966 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002967 if (windowHandle == otherHandle) {
2968 break; // All future windows are below us. Exit early.
2969 }
chaviw98318de2021-05-19 16:45:23 -05002970 const WindowInfo* otherInfo = otherHandle->getInfo();
Bernardo Rufino1ff9d592021-01-18 16:58:57 +00002971 if (canBeObscuredBy(windowHandle, otherHandle) && otherInfo->frameContainsPoint(x, y) &&
2972 !haveSameApplicationToken(windowInfo, otherInfo)) {
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002973 if (DEBUG_TOUCH_OCCLUSION) {
2974 info.debugInfo.push_back(
2975 dumpWindowForTouchOcclusion(otherInfo, /* isTouchedWindow */ false));
2976 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002977 // canBeObscuredBy() has returned true above, which means this window is untrusted, so
2978 // we perform the checks below to see if the touch can be propagated or not based on the
2979 // window's touch occlusion mode
2980 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::BLOCK_UNTRUSTED) {
2981 info.hasBlockingOcclusion = true;
2982 info.obscuringUid = otherInfo->ownerUid;
2983 info.obscuringPackage = otherInfo->packageName;
2984 break;
2985 }
2986 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::USE_OPACITY) {
2987 uint32_t uid = otherInfo->ownerUid;
2988 float opacity =
2989 (opacityByUid.find(uid) == opacityByUid.end()) ? 0 : opacityByUid[uid];
2990 // Given windows A and B:
2991 // opacity(A, B) = 1 - [1 - opacity(A)] * [1 - opacity(B)]
2992 opacity = 1 - (1 - opacity) * (1 - otherInfo->alpha);
2993 opacityByUid[uid] = opacity;
2994 if (opacity > info.obscuringOpacity) {
2995 info.obscuringOpacity = opacity;
2996 info.obscuringUid = uid;
2997 info.obscuringPackage = otherInfo->packageName;
2998 }
2999 }
3000 }
3001 }
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00003002 if (DEBUG_TOUCH_OCCLUSION) {
3003 info.debugInfo.push_back(
3004 dumpWindowForTouchOcclusion(windowInfo, /* isTouchedWindow */ true));
3005 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003006 return info;
3007}
3008
chaviw98318de2021-05-19 16:45:23 -05003009std::string InputDispatcher::dumpWindowForTouchOcclusion(const WindowInfo* info,
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00003010 bool isTouchedWindow) const {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08003011 return StringPrintf(INDENT2 "* %spackage=%s/%" PRId32 ", id=%" PRId32 ", mode=%s, alpha=%.2f, "
3012 "frame=[%" PRId32 ",%" PRId32 "][%" PRId32 ",%" PRId32
3013 "], touchableRegion=%s, window={%s}, inputConfig={%s}, "
3014 "hasToken=%s, applicationInfo.name=%s, applicationInfo.token=%s\n",
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08003015 isTouchedWindow ? "[TOUCHED] " : "", info->packageName.c_str(),
3016 info->ownerUid, info->id, toString(info->touchOcclusionMode).c_str(),
3017 info->alpha, info->frameLeft, info->frameTop, info->frameRight,
3018 info->frameBottom, dumpRegion(info->touchableRegion).c_str(),
3019 info->name.c_str(), info->inputConfig.string().c_str(),
Prabir Pradhan51e7db02022-02-07 06:02:57 -08003020 toString(info->token != nullptr), info->applicationInfo.name.c_str(),
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07003021 binderToString(info->applicationInfo.token).c_str());
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00003022}
3023
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003024bool InputDispatcher::isTouchTrustedLocked(const TouchOcclusionInfo& occlusionInfo) const {
3025 if (occlusionInfo.hasBlockingOcclusion) {
3026 ALOGW("Untrusted touch due to occlusion by %s/%d", occlusionInfo.obscuringPackage.c_str(),
3027 occlusionInfo.obscuringUid);
3028 return false;
3029 }
3030 if (occlusionInfo.obscuringOpacity > mMaximumObscuringOpacityForTouch) {
3031 ALOGW("Untrusted touch due to occlusion by %s/%d (obscuring opacity = "
3032 "%.2f, maximum allowed = %.2f)",
3033 occlusionInfo.obscuringPackage.c_str(), occlusionInfo.obscuringUid,
3034 occlusionInfo.obscuringOpacity, mMaximumObscuringOpacityForTouch);
3035 return false;
3036 }
3037 return true;
3038}
3039
chaviw98318de2021-05-19 16:45:23 -05003040bool InputDispatcher::isWindowObscuredAtPointLocked(const sp<WindowInfoHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003041 int32_t x, int32_t y) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003042 int32_t displayId = windowHandle->getInfo()->displayId;
chaviw98318de2021-05-19 16:45:23 -05003043 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
3044 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07003045 if (windowHandle == otherHandle) {
3046 break; // All future windows are below us. Exit early.
Michael Wrightd02c5b62014-02-10 15:10:22 -08003047 }
chaviw98318de2021-05-19 16:45:23 -05003048 const WindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07003049 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08003050 otherInfo->frameContainsPoint(x, y)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003051 return true;
3052 }
3053 }
3054 return false;
3055}
3056
chaviw98318de2021-05-19 16:45:23 -05003057bool InputDispatcher::isWindowObscuredLocked(const sp<WindowInfoHandle>& windowHandle) const {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07003058 int32_t displayId = windowHandle->getInfo()->displayId;
chaviw98318de2021-05-19 16:45:23 -05003059 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
3060 const WindowInfo* windowInfo = windowHandle->getInfo();
3061 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07003062 if (windowHandle == otherHandle) {
3063 break; // All future windows are below us. Exit early.
Michael Wrightcdcd8f22016-03-22 16:52:13 -07003064 }
chaviw98318de2021-05-19 16:45:23 -05003065 const WindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07003066 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08003067 otherInfo->overlaps(windowInfo)) {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07003068 return true;
3069 }
3070 }
3071 return false;
3072}
3073
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08003074std::string InputDispatcher::getApplicationWindowLabel(
chaviw98318de2021-05-19 16:45:23 -05003075 const InputApplicationHandle* applicationHandle, const sp<WindowInfoHandle>& windowHandle) {
Yi Kong9b14ac62018-07-17 13:48:38 -07003076 if (applicationHandle != nullptr) {
3077 if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07003078 return applicationHandle->getName() + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003079 } else {
3080 return applicationHandle->getName();
3081 }
Yi Kong9b14ac62018-07-17 13:48:38 -07003082 } else if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07003083 return windowHandle->getInfo()->applicationInfo.name + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003084 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003085 return "<unknown application or window>";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003086 }
3087}
3088
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003089void InputDispatcher::pokeUserActivityLocked(const EventEntry& eventEntry) {
Antonio Kantekf16f2832021-09-28 04:39:20 +00003090 if (!isUserActivityEvent(eventEntry)) {
3091 // Not poking user activity if the event type does not represent a user activity
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003092 return;
3093 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003094 int32_t displayId = getTargetDisplayId(eventEntry);
chaviw98318de2021-05-19 16:45:23 -05003095 sp<WindowInfoHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Josep del Riob3981622023-04-18 15:49:45 +00003096 const WindowInfo* windowDisablingUserActivityInfo = nullptr;
Tiger Huang721e26f2018-07-24 22:26:19 +08003097 if (focusedWindowHandle != nullptr) {
chaviw98318de2021-05-19 16:45:23 -05003098 const WindowInfo* info = focusedWindowHandle->getInfo();
Prabir Pradhan51e7db02022-02-07 06:02:57 -08003099 if (info->inputConfig.test(WindowInfo::InputConfig::DISABLE_USER_ACTIVITY)) {
Josep del Riob3981622023-04-18 15:49:45 +00003100 windowDisablingUserActivityInfo = info;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003101 }
3102 }
3103
3104 int32_t eventType = USER_ACTIVITY_EVENT_OTHER;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003105 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003106 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003107 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
3108 if (motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003109 return;
3110 }
Josep del Riob3981622023-04-18 15:49:45 +00003111 if (windowDisablingUserActivityInfo != nullptr) {
3112 if (DEBUG_DISPATCH_CYCLE) {
3113 ALOGD("Not poking user activity: disabled by window '%s'.",
3114 windowDisablingUserActivityInfo->name.c_str());
3115 }
3116 return;
3117 }
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003118 if (MotionEvent::isTouchEvent(motionEntry.source, motionEntry.action)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003119 eventType = USER_ACTIVITY_EVENT_TOUCH;
3120 }
3121 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003122 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003123 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003124 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
3125 if (keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003126 return;
3127 }
Josep del Riob3981622023-04-18 15:49:45 +00003128 // If the key code is unknown, we don't consider it user activity
3129 if (keyEntry.keyCode == AKEYCODE_UNKNOWN) {
3130 return;
3131 }
3132 // Don't inhibit events that were intercepted or are not passed to
3133 // the apps, like system shortcuts
3134 if (windowDisablingUserActivityInfo != nullptr &&
3135 keyEntry.interceptKeyResult != KeyEntry::InterceptKeyResult::SKIP &&
3136 keyEntry.policyFlags & POLICY_FLAG_PASS_TO_USER) {
3137 if (DEBUG_DISPATCH_CYCLE) {
3138 ALOGD("Not poking user activity: disabled by window '%s'.",
3139 windowDisablingUserActivityInfo->name.c_str());
3140 }
3141 return;
3142 }
3143
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003144 eventType = USER_ACTIVITY_EVENT_BUTTON;
3145 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003146 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00003147 default: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003148 LOG_ALWAYS_FATAL("%s events are not user activity",
Dominik Laskowski75788452021-02-09 18:51:25 -08003149 ftl::enum_string(eventEntry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003150 break;
3151 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003152 }
3153
Prabir Pradhancef936d2021-07-21 16:17:52 +00003154 auto command = [this, eventTime = eventEntry.eventTime, eventType, displayId]()
3155 REQUIRES(mLock) {
3156 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00003157 mPolicy.pokeUserActivity(eventTime, eventType, displayId);
Prabir Pradhancef936d2021-07-21 16:17:52 +00003158 };
3159 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003160}
3161
3162void InputDispatcher::prepareDispatchCycleLocked(nsecs_t currentTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003163 const std::shared_ptr<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003164 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003165 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003166 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003167 std::string message =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003168 StringPrintf("prepareDispatchCycleLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003169 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00003170 ATRACE_NAME(message.c_str());
3171 }
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003172 if (DEBUG_DISPATCH_CYCLE) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003173 ALOGD("channel '%s' ~ prepareDispatchCycle - flags=%s, "
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08003174 "globalScaleFactor=%f, pointerIds=%s %s",
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003175 connection->getInputChannelName().c_str(), inputTarget.flags.string().c_str(),
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08003176 inputTarget.globalScaleFactor, bitsetToString(inputTarget.pointerIds).c_str(),
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003177 inputTarget.getPointerInfoString().c_str());
3178 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003179
3180 // Skip this event if the connection status is not normal.
3181 // We don't want to enqueue additional outbound events if the connection is broken.
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003182 if (connection->status != Connection::Status::NORMAL) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003183 if (DEBUG_DISPATCH_CYCLE) {
3184 ALOGD("channel '%s' ~ Dropping event because the channel status is %s",
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003185 connection->getInputChannelName().c_str(),
3186 ftl::enum_string(connection->status).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003187 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003188 return;
3189 }
3190
3191 // Split a motion event if needed.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003192 if (inputTarget.flags.test(InputTarget::Flags::SPLIT)) {
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003193 LOG_ALWAYS_FATAL_IF(eventEntry->type != EventEntry::Type::MOTION,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003194 "Entry type %s should not have Flags::SPLIT",
Dominik Laskowski75788452021-02-09 18:51:25 -08003195 ftl::enum_string(eventEntry->type).c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003196
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003197 const MotionEntry& originalMotionEntry = static_cast<const MotionEntry&>(*eventEntry);
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003198 if (inputTarget.pointerIds.count() != originalMotionEntry.pointerCount) {
Siarhei Vishniakou16e4fa02023-02-16 17:48:56 -08003199 if (!inputTarget.firstDownTimeInTarget.has_value()) {
3200 logDispatchStateLocked();
3201 LOG(FATAL) << "Splitting motion events requires a down time to be set for the "
3202 "target on connection "
3203 << connection->getInputChannelName() << " for "
3204 << originalMotionEntry.getDescription();
3205 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003206 std::unique_ptr<MotionEntry> splitMotionEntry =
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00003207 splitMotionEvent(originalMotionEntry, inputTarget.pointerIds,
3208 inputTarget.firstDownTimeInTarget.value());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003209 if (!splitMotionEntry) {
3210 return; // split event was dropped
3211 }
Arthur Hungb3307ee2021-10-14 10:57:37 +00003212 if (splitMotionEntry->action == AMOTION_EVENT_ACTION_CANCEL) {
3213 std::string reason = std::string("reason=pointer cancel on split window");
3214 android_log_event_list(LOGTAG_INPUT_CANCEL)
3215 << connection->getInputChannelName().c_str() << reason << LOG_ID_EVENTS;
3216 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003217 if (DEBUG_FOCUS) {
3218 ALOGD("channel '%s' ~ Split motion event.",
3219 connection->getInputChannelName().c_str());
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003220 logOutboundMotionDetails(" ", *splitMotionEntry);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003221 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003222 enqueueDispatchEntriesLocked(currentTime, connection, std::move(splitMotionEntry),
3223 inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003224 return;
3225 }
3226 }
3227
3228 // Not splitting. Enqueue dispatch entries for the event as is.
3229 enqueueDispatchEntriesLocked(currentTime, connection, eventEntry, inputTarget);
3230}
3231
3232void InputDispatcher::enqueueDispatchEntriesLocked(nsecs_t currentTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003233 const std::shared_ptr<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003234 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003235 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003236 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003237 std::string message =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003238 StringPrintf("enqueueDispatchEntriesLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003239 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00003240 ATRACE_NAME(message.c_str());
3241 }
Siarhei Vishniakou5cee1e32022-11-29 12:35:39 -08003242 LOG_ALWAYS_FATAL_IF(!inputTarget.flags.any(InputTarget::DISPATCH_MASK),
3243 "No dispatch flags are set for %s", eventEntry->getDescription().c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00003244
hongzuo liu95785e22022-09-06 02:51:35 +00003245 const bool wasEmpty = connection->outboundQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003246
3247 // Enqueue dispatch entries for the requested modes.
chaviw8c9cf542019-03-25 13:02:48 -07003248 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003249 InputTarget::Flags::DISPATCH_AS_HOVER_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07003250 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003251 InputTarget::Flags::DISPATCH_AS_OUTSIDE);
chaviw8c9cf542019-03-25 13:02:48 -07003252 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003253 InputTarget::Flags::DISPATCH_AS_HOVER_ENTER);
chaviw8c9cf542019-03-25 13:02:48 -07003254 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003255 InputTarget::Flags::DISPATCH_AS_IS);
chaviw8c9cf542019-03-25 13:02:48 -07003256 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003257 InputTarget::Flags::DISPATCH_AS_SLIPPERY_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07003258 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003259 InputTarget::Flags::DISPATCH_AS_SLIPPERY_ENTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003260
3261 // If the outbound queue was previously empty, start the dispatch cycle going.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003262 if (wasEmpty && !connection->outboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003263 startDispatchCycleLocked(currentTime, connection);
3264 }
3265}
3266
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003267void InputDispatcher::enqueueDispatchEntryLocked(const std::shared_ptr<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003268 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003269 const InputTarget& inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003270 ftl::Flags<InputTarget::Flags> dispatchMode) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003271 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003272 std::string message = StringPrintf("enqueueDispatchEntry(inputChannel=%s, dispatchMode=%s)",
3273 connection->getInputChannelName().c_str(),
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003274 dispatchMode.string().c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00003275 ATRACE_NAME(message.c_str());
3276 }
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003277 ftl::Flags<InputTarget::Flags> inputTargetFlags = inputTarget.flags;
3278 if (!inputTargetFlags.any(dispatchMode)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003279 return;
3280 }
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003281
3282 inputTargetFlags.clear(InputTarget::DISPATCH_MASK);
3283 inputTargetFlags |= dispatchMode;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003284
3285 // This is a new event.
3286 // Enqueue a new dispatch entry onto the outbound queue for this connection.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003287 std::unique_ptr<DispatchEntry> dispatchEntry =
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003288 createDispatchEntry(inputTarget, eventEntry, inputTargetFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003289
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003290 // Use the eventEntry from dispatchEntry since the entry may have changed and can now be a
3291 // different EventEntry than what was passed in.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003292 EventEntry& newEntry = *(dispatchEntry->eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003293 // Apply target flags and update the connection's input state.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003294 switch (newEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003295 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003296 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003297 dispatchEntry->resolvedEventId = keyEntry.id;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003298 dispatchEntry->resolvedAction = keyEntry.action;
3299 dispatchEntry->resolvedFlags = keyEntry.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003300
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003301 if (!connection->inputState.trackKey(keyEntry, dispatchEntry->resolvedAction,
3302 dispatchEntry->resolvedFlags)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003303 if (DEBUG_DISPATCH_CYCLE) {
3304 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent key "
3305 "event",
3306 connection->getInputChannelName().c_str());
3307 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003308 return; // skip the inconsistent event
3309 }
3310 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003311 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003312
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003313 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003314 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003315 // Assign a default value to dispatchEntry that will never be generated by InputReader,
3316 // and assign a InputDispatcher value if it doesn't change in the if-else chain below.
3317 constexpr int32_t DEFAULT_RESOLVED_EVENT_ID =
3318 static_cast<int32_t>(IdGenerator::Source::OTHER);
3319 dispatchEntry->resolvedEventId = DEFAULT_RESOLVED_EVENT_ID;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003320 if (dispatchMode.test(InputTarget::Flags::DISPATCH_AS_OUTSIDE)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003321 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_OUTSIDE;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003322 } else if (dispatchMode.test(InputTarget::Flags::DISPATCH_AS_HOVER_EXIT)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003323 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_EXIT;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003324 } else if (dispatchMode.test(InputTarget::Flags::DISPATCH_AS_HOVER_ENTER)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003325 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003326 } else if (dispatchMode.test(InputTarget::Flags::DISPATCH_AS_SLIPPERY_EXIT)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003327 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_CANCEL;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003328 } else if (dispatchMode.test(InputTarget::Flags::DISPATCH_AS_SLIPPERY_ENTER)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003329 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_DOWN;
3330 } else {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003331 dispatchEntry->resolvedAction = motionEntry.action;
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003332 dispatchEntry->resolvedEventId = motionEntry.id;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003333 }
3334 if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_HOVER_MOVE &&
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003335 !connection->inputState.isHovering(motionEntry.deviceId, motionEntry.source,
3336 motionEntry.displayId)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003337 if (DEBUG_DISPATCH_CYCLE) {
3338 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: filling in missing hover "
3339 "enter event",
3340 connection->getInputChannelName().c_str());
3341 }
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00003342 // We keep the 'resolvedEventId' here equal to the original 'motionEntry.id' because
3343 // this is a one-to-one event conversion.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003344 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
3345 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003346
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003347 dispatchEntry->resolvedFlags = motionEntry.flags;
Siarhei Vishniakou1ae72f12023-01-29 12:55:30 -08003348 if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_CANCEL) {
3349 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_CANCELED;
3350 }
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003351 if (dispatchEntry->targetFlags.test(InputTarget::Flags::WINDOW_IS_OBSCURED)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003352 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED;
3353 }
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003354 if (dispatchEntry->targetFlags.test(InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003355 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
3356 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003357
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003358 if (!connection->inputState.trackMotion(motionEntry, dispatchEntry->resolvedAction,
3359 dispatchEntry->resolvedFlags)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003360 if (DEBUG_DISPATCH_CYCLE) {
3361 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent motion "
3362 "event",
3363 connection->getInputChannelName().c_str());
3364 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003365 return; // skip the inconsistent event
3366 }
3367
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003368 dispatchEntry->resolvedEventId =
3369 dispatchEntry->resolvedEventId == DEFAULT_RESOLVED_EVENT_ID
3370 ? mIdGenerator.nextId()
3371 : motionEntry.id;
3372 if (ATRACE_ENABLED() && dispatchEntry->resolvedEventId != motionEntry.id) {
3373 std::string message = StringPrintf("Transmute MotionEvent(id=0x%" PRIx32
3374 ") to MotionEvent(id=0x%" PRIx32 ").",
3375 motionEntry.id, dispatchEntry->resolvedEventId);
3376 ATRACE_NAME(message.c_str());
3377 }
3378
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08003379 if ((motionEntry.flags & AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE) &&
3380 (motionEntry.policyFlags & POLICY_FLAG_TRUSTED)) {
3381 // Skip reporting pointer down outside focus to the policy.
3382 break;
3383 }
3384
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003385 dispatchPointerDownOutsideFocus(motionEntry.source, dispatchEntry->resolvedAction,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003386 inputTarget.inputChannel->getConnectionToken());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003387
3388 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003389 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003390 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003391 case EventEntry::Type::TOUCH_MODE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08003392 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
3393 case EventEntry::Type::DRAG: {
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003394 break;
3395 }
Chris Yef59a2f42020-10-16 12:55:26 -07003396 case EventEntry::Type::SENSOR: {
3397 LOG_ALWAYS_FATAL("SENSOR events should not go to apps via input channel");
3398 break;
3399 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003400 case EventEntry::Type::CONFIGURATION_CHANGED:
3401 case EventEntry::Type::DEVICE_RESET: {
3402 LOG_ALWAYS_FATAL("%s events should not go to apps",
Dominik Laskowski75788452021-02-09 18:51:25 -08003403 ftl::enum_string(newEntry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003404 break;
3405 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003406 }
3407
3408 // Remember that we are waiting for this dispatch to complete.
3409 if (dispatchEntry->hasForegroundTarget()) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003410 incrementPendingForegroundDispatches(newEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003411 }
3412
3413 // Enqueue the dispatch entry.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003414 connection->outboundQueue.push_back(dispatchEntry.release());
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003415 traceOutboundQueueLength(*connection);
chaviw8c9cf542019-03-25 13:02:48 -07003416}
3417
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003418/**
3419 * This function is purely for debugging. It helps us understand where the user interaction
3420 * was taking place. For example, if user is touching launcher, we will see a log that user
3421 * started interacting with launcher. In that example, the event would go to the wallpaper as well.
3422 * We will see both launcher and wallpaper in that list.
3423 * Once the interaction with a particular set of connections starts, no new logs will be printed
3424 * until the set of interacted connections changes.
3425 *
3426 * The following items are skipped, to reduce the logspam:
3427 * ACTION_OUTSIDE: any windows that are receiving ACTION_OUTSIDE are not logged
3428 * ACTION_UP: any windows that receive ACTION_UP are not logged (for both keys and motions).
3429 * This includes situations like the soft BACK button key. When the user releases (lifts up the
3430 * finger) the back button, then navigation bar will inject KEYCODE_BACK with ACTION_UP.
3431 * Both of those ACTION_UP events would not be logged
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003432 */
3433void InputDispatcher::updateInteractionTokensLocked(const EventEntry& entry,
3434 const std::vector<InputTarget>& targets) {
3435 // Skip ACTION_UP events, and all events other than keys and motions
3436 if (entry.type == EventEntry::Type::KEY) {
3437 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
3438 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
3439 return;
3440 }
3441 } else if (entry.type == EventEntry::Type::MOTION) {
3442 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
3443 if (motionEntry.action == AMOTION_EVENT_ACTION_UP ||
3444 motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
3445 return;
3446 }
3447 } else {
3448 return; // Not a key or a motion
3449 }
3450
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07003451 std::unordered_set<sp<IBinder>, StrongPointerHash<IBinder>> newConnectionTokens;
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003452 std::vector<std::shared_ptr<Connection>> newConnections;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003453 for (const InputTarget& target : targets) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003454 if (target.flags.test(InputTarget::Flags::DISPATCH_AS_OUTSIDE)) {
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003455 continue; // Skip windows that receive ACTION_OUTSIDE
3456 }
3457
3458 sp<IBinder> token = target.inputChannel->getConnectionToken();
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003459 std::shared_ptr<Connection> connection = getConnectionLocked(token);
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003460 if (connection == nullptr) {
3461 continue;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003462 }
3463 newConnectionTokens.insert(std::move(token));
3464 newConnections.emplace_back(connection);
3465 }
3466 if (newConnectionTokens == mInteractionConnectionTokens) {
3467 return; // no change
3468 }
3469 mInteractionConnectionTokens = newConnectionTokens;
3470
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003471 std::string targetList;
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003472 for (const std::shared_ptr<Connection>& connection : newConnections) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003473 targetList += connection->getWindowName() + ", ";
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003474 }
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003475 std::string message = "Interaction with: " + targetList;
3476 if (targetList.empty()) {
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003477 message += "<none>";
3478 }
3479 android_log_event_list(LOGTAG_INPUT_INTERACTION) << message << LOG_ID_EVENTS;
3480}
3481
chaviwfd6d3512019-03-25 13:23:49 -07003482void InputDispatcher::dispatchPointerDownOutsideFocus(uint32_t source, int32_t action,
Vishnu Nairad321cd2020-08-20 16:40:21 -07003483 const sp<IBinder>& token) {
chaviw8c9cf542019-03-25 13:02:48 -07003484 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
chaviwfd6d3512019-03-25 13:23:49 -07003485 uint32_t maskedSource = source & AINPUT_SOURCE_CLASS_MASK;
3486 if (maskedSource != AINPUT_SOURCE_CLASS_POINTER || maskedAction != AMOTION_EVENT_ACTION_DOWN) {
chaviw8c9cf542019-03-25 13:02:48 -07003487 return;
3488 }
3489
Vishnu Nairc519ff72021-01-21 08:23:08 -08003490 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07003491 if (focusedToken == token) {
3492 // ignore since token is focused
chaviw8c9cf542019-03-25 13:02:48 -07003493 return;
3494 }
3495
Prabir Pradhancef936d2021-07-21 16:17:52 +00003496 auto command = [this, token]() REQUIRES(mLock) {
3497 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00003498 mPolicy.onPointerDownOutsideFocus(token);
Prabir Pradhancef936d2021-07-21 16:17:52 +00003499 };
3500 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003501}
3502
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003503status_t InputDispatcher::publishMotionEvent(Connection& connection,
3504 DispatchEntry& dispatchEntry) const {
3505 const EventEntry& eventEntry = *(dispatchEntry.eventEntry);
3506 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
3507
3508 PointerCoords scaledCoords[MAX_POINTERS];
3509 const PointerCoords* usingCoords = motionEntry.pointerCoords;
3510
3511 // Set the X and Y offset and X and Y scale depending on the input source.
3512 if ((motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) &&
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003513 !(dispatchEntry.targetFlags.test(InputTarget::Flags::ZERO_COORDS))) {
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003514 float globalScaleFactor = dispatchEntry.globalScaleFactor;
3515 if (globalScaleFactor != 1.0f) {
3516 for (uint32_t i = 0; i < motionEntry.pointerCount; i++) {
3517 scaledCoords[i] = motionEntry.pointerCoords[i];
3518 // Don't apply window scale here since we don't want scale to affect raw
3519 // coordinates. The scale will be sent back to the client and applied
3520 // later when requesting relative coordinates.
Harry Cutts33476232023-01-30 19:57:29 +00003521 scaledCoords[i].scale(globalScaleFactor, /*windowXScale=*/1, /*windowYScale=*/1);
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003522 }
3523 usingCoords = scaledCoords;
3524 }
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003525 } else if (dispatchEntry.targetFlags.test(InputTarget::Flags::ZERO_COORDS)) {
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003526 // We don't want the dispatch target to know the coordinates
3527 for (uint32_t i = 0; i < motionEntry.pointerCount; i++) {
3528 scaledCoords[i].clear();
3529 }
3530 usingCoords = scaledCoords;
3531 }
3532
3533 std::array<uint8_t, 32> hmac = getSignature(motionEntry, dispatchEntry);
3534
3535 // Publish the motion event.
3536 return connection.inputPublisher
3537 .publishMotionEvent(dispatchEntry.seq, dispatchEntry.resolvedEventId,
3538 motionEntry.deviceId, motionEntry.source, motionEntry.displayId,
3539 std::move(hmac), dispatchEntry.resolvedAction,
3540 motionEntry.actionButton, dispatchEntry.resolvedFlags,
3541 motionEntry.edgeFlags, motionEntry.metaState,
3542 motionEntry.buttonState, motionEntry.classification,
3543 dispatchEntry.transform, motionEntry.xPrecision,
3544 motionEntry.yPrecision, motionEntry.xCursorPosition,
3545 motionEntry.yCursorPosition, dispatchEntry.rawTransform,
3546 motionEntry.downTime, motionEntry.eventTime,
3547 motionEntry.pointerCount, motionEntry.pointerProperties,
3548 usingCoords);
3549}
3550
Michael Wrightd02c5b62014-02-10 15:10:22 -08003551void InputDispatcher::startDispatchCycleLocked(nsecs_t currentTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003552 const std::shared_ptr<Connection>& connection) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003553 if (ATRACE_ENABLED()) {
3554 std::string message = StringPrintf("startDispatchCycleLocked(inputChannel=%s)",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003555 connection->getInputChannelName().c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00003556 ATRACE_NAME(message.c_str());
3557 }
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003558 if (DEBUG_DISPATCH_CYCLE) {
3559 ALOGD("channel '%s' ~ startDispatchCycle", connection->getInputChannelName().c_str());
3560 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003561
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003562 while (connection->status == Connection::Status::NORMAL && !connection->outboundQueue.empty()) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003563 DispatchEntry* dispatchEntry = connection->outboundQueue.front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003564 dispatchEntry->deliveryTime = currentTime;
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003565 const std::chrono::nanoseconds timeout = getDispatchingTimeoutLocked(connection);
Siarhei Vishniakou70622952020-07-30 11:17:23 -05003566 dispatchEntry->timeoutTime = currentTime + timeout.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003567
3568 // Publish the event.
3569 status_t status;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003570 const EventEntry& eventEntry = *(dispatchEntry->eventEntry);
3571 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003572 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003573 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
3574 std::array<uint8_t, 32> hmac = getSignature(keyEntry, *dispatchEntry);
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08003575 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
3576 LOG(DEBUG) << "Publishing " << *dispatchEntry << " to "
3577 << connection->getInputChannelName();
3578 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003579
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003580 // Publish the key event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003581 status = connection->inputPublisher
3582 .publishKeyEvent(dispatchEntry->seq,
3583 dispatchEntry->resolvedEventId, keyEntry.deviceId,
3584 keyEntry.source, keyEntry.displayId,
3585 std::move(hmac), dispatchEntry->resolvedAction,
3586 dispatchEntry->resolvedFlags, keyEntry.keyCode,
3587 keyEntry.scanCode, keyEntry.metaState,
3588 keyEntry.repeatCount, keyEntry.downTime,
3589 keyEntry.eventTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003590 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003591 }
3592
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003593 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08003594 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
3595 LOG(DEBUG) << "Publishing " << *dispatchEntry << " to "
3596 << connection->getInputChannelName();
3597 }
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003598 status = publishMotionEvent(*connection, *dispatchEntry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003599 break;
3600 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003601
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003602 case EventEntry::Type::FOCUS: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003603 const FocusEntry& focusEntry = static_cast<const FocusEntry&>(eventEntry);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003604 status = connection->inputPublisher.publishFocusEvent(dispatchEntry->seq,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003605 focusEntry.id,
Antonio Kantek3cfec7b2021-11-05 18:26:17 -07003606 focusEntry.hasFocus);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003607 break;
3608 }
3609
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003610 case EventEntry::Type::TOUCH_MODE_CHANGED: {
3611 const TouchModeEntry& touchModeEntry =
3612 static_cast<const TouchModeEntry&>(eventEntry);
3613 status = connection->inputPublisher
3614 .publishTouchModeEvent(dispatchEntry->seq, touchModeEntry.id,
3615 touchModeEntry.inTouchMode);
3616
3617 break;
3618 }
3619
Prabir Pradhan99987712020-11-10 18:43:05 -08003620 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
3621 const auto& captureEntry =
3622 static_cast<const PointerCaptureChangedEntry&>(eventEntry);
3623 status = connection->inputPublisher
3624 .publishCaptureEvent(dispatchEntry->seq, captureEntry.id,
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00003625 captureEntry.pointerCaptureRequest.enable);
Prabir Pradhan99987712020-11-10 18:43:05 -08003626 break;
3627 }
3628
arthurhungb89ccb02020-12-30 16:19:01 +08003629 case EventEntry::Type::DRAG: {
3630 const DragEntry& dragEntry = static_cast<const DragEntry&>(eventEntry);
3631 status = connection->inputPublisher.publishDragEvent(dispatchEntry->seq,
3632 dragEntry.id, dragEntry.x,
3633 dragEntry.y,
3634 dragEntry.isExiting);
3635 break;
3636 }
3637
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003638 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07003639 case EventEntry::Type::DEVICE_RESET:
3640 case EventEntry::Type::SENSOR: {
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003641 LOG_ALWAYS_FATAL("Should never start dispatch cycles for %s events",
Dominik Laskowski75788452021-02-09 18:51:25 -08003642 ftl::enum_string(eventEntry.type).c_str());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003643 return;
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003644 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003645 }
3646
3647 // Check the result.
3648 if (status) {
3649 if (status == WOULD_BLOCK) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003650 if (connection->waitQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003651 ALOGE("channel '%s' ~ Could not publish event because the pipe is full. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003652 "This is unexpected because the wait queue is empty, so the pipe "
3653 "should be empty and we shouldn't have any problems writing an "
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +00003654 "event to it, status=%s(%d)",
3655 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3656 status);
Harry Cutts33476232023-01-30 19:57:29 +00003657 abortBrokenDispatchCycleLocked(currentTime, connection, /*notify=*/true);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003658 } else {
3659 // Pipe is full and we are waiting for the app to finish process some events
3660 // before sending more events to it.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003661 if (DEBUG_DISPATCH_CYCLE) {
3662 ALOGD("channel '%s' ~ Could not publish event because the pipe is full, "
3663 "waiting for the application to catch up",
3664 connection->getInputChannelName().c_str());
3665 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003666 }
3667 } else {
3668 ALOGE("channel '%s' ~ Could not publish event due to an unexpected error, "
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +00003669 "status=%s(%d)",
3670 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3671 status);
Harry Cutts33476232023-01-30 19:57:29 +00003672 abortBrokenDispatchCycleLocked(currentTime, connection, /*notify=*/true);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003673 }
3674 return;
3675 }
3676
3677 // Re-enqueue the event on the wait queue.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003678 connection->outboundQueue.erase(std::remove(connection->outboundQueue.begin(),
3679 connection->outboundQueue.end(),
3680 dispatchEntry));
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003681 traceOutboundQueueLength(*connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003682 connection->waitQueue.push_back(dispatchEntry);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003683 if (connection->responsive) {
3684 mAnrTracker.insert(dispatchEntry->timeoutTime,
3685 connection->inputChannel->getConnectionToken());
3686 }
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003687 traceWaitQueueLength(*connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003688 }
3689}
3690
chaviw09c8d2d2020-08-24 15:48:26 -07003691std::array<uint8_t, 32> InputDispatcher::sign(const VerifiedInputEvent& event) const {
3692 size_t size;
3693 switch (event.type) {
3694 case VerifiedInputEvent::Type::KEY: {
3695 size = sizeof(VerifiedKeyEvent);
3696 break;
3697 }
3698 case VerifiedInputEvent::Type::MOTION: {
3699 size = sizeof(VerifiedMotionEvent);
3700 break;
3701 }
3702 }
3703 const uint8_t* start = reinterpret_cast<const uint8_t*>(&event);
3704 return mHmacKeyManager.sign(start, size);
3705}
3706
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003707const std::array<uint8_t, 32> InputDispatcher::getSignature(
3708 const MotionEntry& motionEntry, const DispatchEntry& dispatchEntry) const {
Siarhei Vishniakoubf880522023-05-01 11:03:22 -07003709 const int32_t actionMasked = MotionEvent::getActionMasked(dispatchEntry.resolvedAction);
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003710 if (actionMasked != AMOTION_EVENT_ACTION_UP && actionMasked != AMOTION_EVENT_ACTION_DOWN) {
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003711 // Only sign events up and down events as the purely move events
3712 // are tied to their up/down counterparts so signing would be redundant.
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003713 return INVALID_HMAC;
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003714 }
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003715
3716 VerifiedMotionEvent verifiedEvent =
3717 verifiedMotionEventFromMotionEntry(motionEntry, dispatchEntry.rawTransform);
3718 verifiedEvent.actionMasked = actionMasked;
3719 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_MOTION_EVENT_FLAGS;
3720 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003721}
3722
3723const std::array<uint8_t, 32> InputDispatcher::getSignature(
3724 const KeyEntry& keyEntry, const DispatchEntry& dispatchEntry) const {
3725 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEntry(keyEntry);
3726 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_KEY_EVENT_FLAGS;
3727 verifiedEvent.action = dispatchEntry.resolvedAction;
chaviw09c8d2d2020-08-24 15:48:26 -07003728 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003729}
3730
Michael Wrightd02c5b62014-02-10 15:10:22 -08003731void InputDispatcher::finishDispatchCycleLocked(nsecs_t currentTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003732 const std::shared_ptr<Connection>& connection,
3733 uint32_t seq, bool handled, nsecs_t consumeTime) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003734 if (DEBUG_DISPATCH_CYCLE) {
3735 ALOGD("channel '%s' ~ finishDispatchCycle - seq=%u, handled=%s",
3736 connection->getInputChannelName().c_str(), seq, toString(handled));
3737 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003738
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003739 if (connection->status == Connection::Status::BROKEN ||
3740 connection->status == Connection::Status::ZOMBIE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003741 return;
3742 }
3743
3744 // Notify other system components and prepare to start the next dispatch cycle.
Prabir Pradhancef936d2021-07-21 16:17:52 +00003745 auto command = [this, currentTime, connection, seq, handled, consumeTime]() REQUIRES(mLock) {
3746 doDispatchCycleFinishedCommand(currentTime, connection, seq, handled, consumeTime);
3747 };
3748 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003749}
3750
3751void InputDispatcher::abortBrokenDispatchCycleLocked(nsecs_t currentTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003752 const std::shared_ptr<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003753 bool notify) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003754 if (DEBUG_DISPATCH_CYCLE) {
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07003755 LOG(DEBUG) << "channel '" << connection->getInputChannelName() << "'~ " << __func__
3756 << " - notify=" << toString(notify);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003757 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003758
3759 // Clear the dispatch queues.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003760 drainDispatchQueue(connection->outboundQueue);
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003761 traceOutboundQueueLength(*connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003762 drainDispatchQueue(connection->waitQueue);
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003763 traceWaitQueueLength(*connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003764
3765 // The connection appears to be unrecoverably broken.
3766 // Ignore already broken or zombie connections.
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003767 if (connection->status == Connection::Status::NORMAL) {
3768 connection->status = Connection::Status::BROKEN;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003769
3770 if (notify) {
3771 // Notify other system components.
Prabir Pradhancef936d2021-07-21 16:17:52 +00003772 ALOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
3773 connection->getInputChannelName().c_str());
3774
3775 auto command = [this, connection]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00003776 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00003777 mPolicy.notifyInputChannelBroken(connection->inputChannel->getConnectionToken());
Prabir Pradhancef936d2021-07-21 16:17:52 +00003778 };
3779 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003780 }
3781 }
3782}
3783
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003784void InputDispatcher::drainDispatchQueue(std::deque<DispatchEntry*>& queue) {
3785 while (!queue.empty()) {
3786 DispatchEntry* dispatchEntry = queue.front();
3787 queue.pop_front();
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003788 releaseDispatchEntry(dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003789 }
3790}
3791
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003792void InputDispatcher::releaseDispatchEntry(DispatchEntry* dispatchEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003793 if (dispatchEntry->hasForegroundTarget()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003794 decrementPendingForegroundDispatches(*(dispatchEntry->eventEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003795 }
3796 delete dispatchEntry;
3797}
3798
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003799int InputDispatcher::handleReceiveCallback(int events, sp<IBinder> connectionToken) {
3800 std::scoped_lock _l(mLock);
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003801 std::shared_ptr<Connection> connection = getConnectionLocked(connectionToken);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003802 if (connection == nullptr) {
3803 ALOGW("Received looper callback for unknown input channel token %p. events=0x%x",
3804 connectionToken.get(), events);
3805 return 0; // remove the callback
3806 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003807
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003808 bool notify;
3809 if (!(events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP))) {
3810 if (!(events & ALOOPER_EVENT_INPUT)) {
3811 ALOGW("channel '%s' ~ Received spurious callback for unhandled poll event. "
3812 "events=0x%x",
3813 connection->getInputChannelName().c_str(), events);
3814 return 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003815 }
3816
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003817 nsecs_t currentTime = now();
3818 bool gotOne = false;
3819 status_t status = OK;
3820 for (;;) {
3821 Result<InputPublisher::ConsumerResponse> result =
3822 connection->inputPublisher.receiveConsumerResponse();
3823 if (!result.ok()) {
3824 status = result.error().code();
3825 break;
3826 }
3827
3828 if (std::holds_alternative<InputPublisher::Finished>(*result)) {
3829 const InputPublisher::Finished& finish =
3830 std::get<InputPublisher::Finished>(*result);
3831 finishDispatchCycleLocked(currentTime, connection, finish.seq, finish.handled,
3832 finish.consumeTime);
3833 } else if (std::holds_alternative<InputPublisher::Timeline>(*result)) {
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00003834 if (shouldReportMetricsForConnection(*connection)) {
3835 const InputPublisher::Timeline& timeline =
3836 std::get<InputPublisher::Timeline>(*result);
3837 mLatencyTracker
3838 .trackGraphicsLatency(timeline.inputEventId,
3839 connection->inputChannel->getConnectionToken(),
3840 std::move(timeline.graphicsTimeline));
3841 }
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003842 }
3843 gotOne = true;
3844 }
3845 if (gotOne) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00003846 runCommandsLockedInterruptable();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003847 if (status == WOULD_BLOCK) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003848 return 1;
3849 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003850 }
3851
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003852 notify = status != DEAD_OBJECT || !connection->monitor;
3853 if (notify) {
3854 ALOGE("channel '%s' ~ Failed to receive finished signal. status=%s(%d)",
3855 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3856 status);
3857 }
3858 } else {
3859 // Monitor channels are never explicitly unregistered.
3860 // We do it automatically when the remote endpoint is closed so don't warn about them.
3861 const bool stillHaveWindowHandle =
3862 getWindowHandleLocked(connection->inputChannel->getConnectionToken()) != nullptr;
3863 notify = !connection->monitor && stillHaveWindowHandle;
3864 if (notify) {
3865 ALOGW("channel '%s' ~ Consumer closed input channel or an error occurred. events=0x%x",
3866 connection->getInputChannelName().c_str(), events);
3867 }
3868 }
3869
3870 // Remove the channel.
3871 removeInputChannelLocked(connection->inputChannel->getConnectionToken(), notify);
3872 return 0; // remove the callback
Michael Wrightd02c5b62014-02-10 15:10:22 -08003873}
3874
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003875void InputDispatcher::synthesizeCancelationEventsForAllConnectionsLocked(
Michael Wrightd02c5b62014-02-10 15:10:22 -08003876 const CancelationOptions& options) {
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003877 for (const auto& [token, connection] : mConnectionsByToken) {
Siarhei Vishniakou2e2ea992020-12-15 02:57:19 +00003878 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003879 }
3880}
3881
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003882void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
Michael Wrightfa13dcf2015-06-12 13:25:11 +01003883 const CancelationOptions& options) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08003884 for (const auto& [_, monitors] : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003885 for (const Monitor& monitor : monitors) {
3886 synthesizeCancelationEventsForInputChannelLocked(monitor.inputChannel, options);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003887 }
Michael Wrightfa13dcf2015-06-12 13:25:11 +01003888 }
3889}
3890
Michael Wrightd02c5b62014-02-10 15:10:22 -08003891void InputDispatcher::synthesizeCancelationEventsForInputChannelLocked(
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05003892 const std::shared_ptr<InputChannel>& channel, const CancelationOptions& options) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003893 std::shared_ptr<Connection> connection = getConnectionLocked(channel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003894 if (connection == nullptr) {
3895 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003896 }
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003897
3898 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003899}
3900
3901void InputDispatcher::synthesizeCancelationEventsForConnectionLocked(
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003902 const std::shared_ptr<Connection>& connection, const CancelationOptions& options) {
Linnan Li974dc912023-07-14 14:36:22 +08003903 if ((options.mode == CancelationOptions::Mode::CANCEL_POINTER_EVENTS ||
3904 options.mode == CancelationOptions::Mode::CANCEL_ALL_EVENTS) &&
3905 mDragState && mDragState->dragWindow->getToken() == connection->inputChannel->getToken()) {
3906 LOG(INFO) << __func__
3907 << ": Canceling drag and drop because the pointers for the drag window are being "
3908 "canceled.";
3909 sendDropWindowCommandLocked(nullptr, /*x=*/0, /*y=*/0);
3910 mDragState.reset();
3911 }
3912
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003913 if (connection->status == Connection::Status::BROKEN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003914 return;
3915 }
3916
3917 nsecs_t currentTime = now();
3918
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003919 std::vector<std::unique_ptr<EventEntry>> cancelationEvents =
Siarhei Vishniakou00fca7c2019-10-29 13:05:57 -07003920 connection->inputState.synthesizeCancelationEvents(currentTime, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003921
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003922 if (cancelationEvents.empty()) {
3923 return;
3924 }
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003925 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
3926 ALOGD("channel '%s' ~ Synthesized %zu cancelation events to bring channel back in sync "
Siarhei Vishniakou2e3e4432023-02-09 18:34:11 -08003927 "with reality: %s, mode=%s.",
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003928 connection->getInputChannelName().c_str(), cancelationEvents.size(), options.reason,
Siarhei Vishniakou2e3e4432023-02-09 18:34:11 -08003929 ftl::enum_string(options.mode).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003930 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08003931
Arthur Hungb3307ee2021-10-14 10:57:37 +00003932 std::string reason = std::string("reason=").append(options.reason);
3933 android_log_event_list(LOGTAG_INPUT_CANCEL)
3934 << connection->getInputChannelName().c_str() << reason << LOG_ID_EVENTS;
3935
Svet Ganov5d3bc372020-01-26 23:11:07 -08003936 InputTarget target;
Hu Guoba4ed762023-09-17 20:51:08 +08003937 sp<WindowInfoHandle> windowHandle;
3938 if (options.displayId) {
3939 windowHandle = getWindowHandleLocked(connection->inputChannel->getConnectionToken(),
3940 options.displayId.value());
3941 } else {
3942 windowHandle = getWindowHandleLocked(connection->inputChannel->getConnectionToken());
3943 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08003944 if (windowHandle != nullptr) {
chaviw98318de2021-05-19 16:45:23 -05003945 const WindowInfo* windowInfo = windowHandle->getInfo();
chaviw1ff3d1e2020-07-01 15:53:47 -07003946 target.setDefaultPointerTransform(windowInfo->transform);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003947 target.globalScaleFactor = windowInfo->globalScaleFactor;
3948 }
3949 target.inputChannel = connection->inputChannel;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003950 target.flags = InputTarget::Flags::DISPATCH_AS_IS;
Svet Ganov5d3bc372020-01-26 23:11:07 -08003951
hongzuo liu95785e22022-09-06 02:51:35 +00003952 const bool wasEmpty = connection->outboundQueue.empty();
3953
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003954 for (size_t i = 0; i < cancelationEvents.size(); i++) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003955 std::unique_ptr<EventEntry> cancelationEventEntry = std::move(cancelationEvents[i]);
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003956 switch (cancelationEventEntry->type) {
3957 case EventEntry::Type::KEY: {
3958 logOutboundKeyDetails("cancel - ",
3959 static_cast<const KeyEntry&>(*cancelationEventEntry));
3960 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003961 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003962 case EventEntry::Type::MOTION: {
3963 logOutboundMotionDetails("cancel - ",
3964 static_cast<const MotionEntry&>(*cancelationEventEntry));
3965 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003966 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003967 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003968 case EventEntry::Type::TOUCH_MODE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08003969 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
3970 case EventEntry::Type::DRAG: {
Prabir Pradhan99987712020-11-10 18:43:05 -08003971 LOG_ALWAYS_FATAL("Canceling %s events is not supported",
Dominik Laskowski75788452021-02-09 18:51:25 -08003972 ftl::enum_string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003973 break;
3974 }
3975 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07003976 case EventEntry::Type::DEVICE_RESET:
3977 case EventEntry::Type::SENSOR: {
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003978 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Dominik Laskowski75788452021-02-09 18:51:25 -08003979 ftl::enum_string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003980 break;
3981 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003982 }
3983
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003984 enqueueDispatchEntryLocked(connection, std::move(cancelationEventEntry), target,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003985 InputTarget::Flags::DISPATCH_AS_IS);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003986 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003987
hongzuo liu95785e22022-09-06 02:51:35 +00003988 // If the outbound queue was previously empty, start the dispatch cycle going.
3989 if (wasEmpty && !connection->outboundQueue.empty()) {
3990 startDispatchCycleLocked(currentTime, connection);
3991 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003992}
3993
Svet Ganov5d3bc372020-01-26 23:11:07 -08003994void InputDispatcher::synthesizePointerDownEventsForConnectionLocked(
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003995 const nsecs_t downTime, const std::shared_ptr<Connection>& connection,
Arthur Hungc539dbb2022-12-08 07:45:36 +00003996 ftl::Flags<InputTarget::Flags> targetFlags) {
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003997 if (connection->status == Connection::Status::BROKEN) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003998 return;
3999 }
4000
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004001 std::vector<std::unique_ptr<EventEntry>> downEvents =
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00004002 connection->inputState.synthesizePointerDownEvents(downTime);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004003
4004 if (downEvents.empty()) {
4005 return;
4006 }
4007
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004008 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08004009 ALOGD("channel '%s' ~ Synthesized %zu down events to ensure consistent event stream.",
4010 connection->getInputChannelName().c_str(), downEvents.size());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004011 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08004012
4013 InputTarget target;
chaviw98318de2021-05-19 16:45:23 -05004014 sp<WindowInfoHandle> windowHandle =
Svet Ganov5d3bc372020-01-26 23:11:07 -08004015 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
4016 if (windowHandle != nullptr) {
chaviw98318de2021-05-19 16:45:23 -05004017 const WindowInfo* windowInfo = windowHandle->getInfo();
chaviw1ff3d1e2020-07-01 15:53:47 -07004018 target.setDefaultPointerTransform(windowInfo->transform);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004019 target.globalScaleFactor = windowInfo->globalScaleFactor;
4020 }
4021 target.inputChannel = connection->inputChannel;
Arthur Hungc539dbb2022-12-08 07:45:36 +00004022 target.flags = targetFlags;
Svet Ganov5d3bc372020-01-26 23:11:07 -08004023
hongzuo liu95785e22022-09-06 02:51:35 +00004024 const bool wasEmpty = connection->outboundQueue.empty();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004025 for (std::unique_ptr<EventEntry>& downEventEntry : downEvents) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08004026 switch (downEventEntry->type) {
4027 case EventEntry::Type::MOTION: {
4028 logOutboundMotionDetails("down - ",
4029 static_cast<const MotionEntry&>(*downEventEntry));
4030 break;
4031 }
4032
4033 case EventEntry::Type::KEY:
4034 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07004035 case EventEntry::Type::TOUCH_MODE_CHANGED:
Svet Ganov5d3bc372020-01-26 23:11:07 -08004036 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08004037 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07004038 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08004039 case EventEntry::Type::SENSOR:
4040 case EventEntry::Type::DRAG: {
Svet Ganov5d3bc372020-01-26 23:11:07 -08004041 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Dominik Laskowski75788452021-02-09 18:51:25 -08004042 ftl::enum_string(downEventEntry->type).c_str());
Svet Ganov5d3bc372020-01-26 23:11:07 -08004043 break;
4044 }
4045 }
4046
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004047 enqueueDispatchEntryLocked(connection, std::move(downEventEntry), target,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08004048 InputTarget::Flags::DISPATCH_AS_IS);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004049 }
4050
hongzuo liu95785e22022-09-06 02:51:35 +00004051 // If the outbound queue was previously empty, start the dispatch cycle going.
4052 if (wasEmpty && !connection->outboundQueue.empty()) {
4053 startDispatchCycleLocked(downTime, connection);
4054 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08004055}
4056
Arthur Hungc539dbb2022-12-08 07:45:36 +00004057void InputDispatcher::synthesizeCancelationEventsForWindowLocked(
4058 const sp<WindowInfoHandle>& windowHandle, const CancelationOptions& options) {
4059 if (windowHandle != nullptr) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07004060 std::shared_ptr<Connection> wallpaperConnection =
4061 getConnectionLocked(windowHandle->getToken());
Arthur Hungc539dbb2022-12-08 07:45:36 +00004062 if (wallpaperConnection != nullptr) {
4063 synthesizeCancelationEventsForConnectionLocked(wallpaperConnection, options);
4064 }
4065 }
4066}
4067
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004068std::unique_ptr<MotionEntry> InputDispatcher::splitMotionEvent(
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08004069 const MotionEntry& originalMotionEntry, std::bitset<MAX_POINTER_ID + 1> pointerIds,
4070 nsecs_t splitDownTime) {
4071 ALOG_ASSERT(pointerIds.any());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004072
4073 uint32_t splitPointerIndexMap[MAX_POINTERS];
4074 PointerProperties splitPointerProperties[MAX_POINTERS];
4075 PointerCoords splitPointerCoords[MAX_POINTERS];
4076
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07004077 uint32_t originalPointerCount = originalMotionEntry.pointerCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004078 uint32_t splitPointerCount = 0;
4079
4080 for (uint32_t originalPointerIndex = 0; originalPointerIndex < originalPointerCount;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004081 originalPointerIndex++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004082 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07004083 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08004084 uint32_t pointerId = uint32_t(pointerProperties.id);
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08004085 if (pointerIds.test(pointerId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004086 splitPointerIndexMap[splitPointerCount] = originalPointerIndex;
4087 splitPointerProperties[splitPointerCount].copyFrom(pointerProperties);
4088 splitPointerCoords[splitPointerCount].copyFrom(
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07004089 originalMotionEntry.pointerCoords[originalPointerIndex]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004090 splitPointerCount += 1;
4091 }
4092 }
4093
4094 if (splitPointerCount != pointerIds.count()) {
4095 // This is bad. We are missing some of the pointers that we expected to deliver.
4096 // Most likely this indicates that we received an ACTION_MOVE events that has
4097 // different pointer ids than we expected based on the previous ACTION_DOWN
4098 // or ACTION_POINTER_DOWN events that caused us to decide to split the pointers
4099 // in this way.
4100 ALOGW("Dropping split motion event because the pointer count is %d but "
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08004101 "we expected there to be %zu pointers. This probably means we received "
Siarhei Vishniakou16e4fa02023-02-16 17:48:56 -08004102 "a broken sequence of pointer ids from the input device: %s",
4103 splitPointerCount, pointerIds.count(), originalMotionEntry.getDescription().c_str());
Yi Kong9b14ac62018-07-17 13:48:38 -07004104 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004105 }
4106
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07004107 int32_t action = originalMotionEntry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004108 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004109 if (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN ||
4110 maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004111 int32_t originalPointerIndex = getMotionEventActionPointerIndex(action);
4112 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07004113 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08004114 uint32_t pointerId = uint32_t(pointerProperties.id);
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08004115 if (pointerIds.test(pointerId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004116 if (pointerIds.count() == 1) {
4117 // The first/last pointer went down/up.
4118 action = maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004119 ? AMOTION_EVENT_ACTION_DOWN
arthurhungea3f4fc2020-12-21 23:18:53 +08004120 : (originalMotionEntry.flags & AMOTION_EVENT_FLAG_CANCELED) != 0
4121 ? AMOTION_EVENT_ACTION_CANCEL
4122 : AMOTION_EVENT_ACTION_UP;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004123 } else {
4124 // A secondary pointer went down/up.
4125 uint32_t splitPointerIndex = 0;
4126 while (pointerId != uint32_t(splitPointerProperties[splitPointerIndex].id)) {
4127 splitPointerIndex += 1;
4128 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004129 action = maskedAction |
4130 (splitPointerIndex << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004131 }
4132 } else {
4133 // An unrelated pointer changed.
4134 action = AMOTION_EVENT_ACTION_MOVE;
4135 }
4136 }
4137
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00004138 if (action == AMOTION_EVENT_ACTION_DOWN) {
4139 LOG_ALWAYS_FATAL_IF(splitDownTime != originalMotionEntry.eventTime,
4140 "Split motion event has mismatching downTime and eventTime for "
Siarhei Vishniakou060f82b2023-01-27 06:39:14 -08004141 "ACTION_DOWN, motionEntry=%s, splitDownTime=%" PRId64,
4142 originalMotionEntry.getDescription().c_str(), splitDownTime);
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00004143 }
4144
Garfield Tanff1f1bb2020-01-28 13:24:04 -08004145 int32_t newId = mIdGenerator.nextId();
4146 if (ATRACE_ENABLED()) {
4147 std::string message = StringPrintf("Split MotionEvent(id=0x%" PRIx32
4148 ") to MotionEvent(id=0x%" PRIx32 ").",
4149 originalMotionEntry.id, newId);
4150 ATRACE_NAME(message.c_str());
4151 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004152 std::unique_ptr<MotionEntry> splitMotionEntry =
4153 std::make_unique<MotionEntry>(newId, originalMotionEntry.eventTime,
4154 originalMotionEntry.deviceId, originalMotionEntry.source,
4155 originalMotionEntry.displayId,
4156 originalMotionEntry.policyFlags, action,
4157 originalMotionEntry.actionButton,
4158 originalMotionEntry.flags, originalMotionEntry.metaState,
4159 originalMotionEntry.buttonState,
4160 originalMotionEntry.classification,
4161 originalMotionEntry.edgeFlags,
4162 originalMotionEntry.xPrecision,
4163 originalMotionEntry.yPrecision,
4164 originalMotionEntry.xCursorPosition,
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00004165 originalMotionEntry.yCursorPosition, splitDownTime,
4166 splitPointerCount, splitPointerProperties,
4167 splitPointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004168
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07004169 if (originalMotionEntry.injectionState) {
4170 splitMotionEntry->injectionState = originalMotionEntry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004171 splitMotionEntry->injectionState->refCount += 1;
4172 }
4173
4174 return splitMotionEntry;
4175}
4176
Prabir Pradhan678438e2023-04-13 19:32:51 +00004177void InputDispatcher::notifyConfigurationChanged(const NotifyConfigurationChangedArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004178 if (debugInboundEventDetails()) {
Prabir Pradhan678438e2023-04-13 19:32:51 +00004179 ALOGD("notifyConfigurationChanged - eventTime=%" PRId64, args.eventTime);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004180 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004181
Antonio Kantekf16f2832021-09-28 04:39:20 +00004182 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004183 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004184 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004185
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004186 std::unique_ptr<ConfigurationChangedEntry> newEntry =
Prabir Pradhan678438e2023-04-13 19:32:51 +00004187 std::make_unique<ConfigurationChangedEntry>(args.id, args.eventTime);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004188 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004189 } // release lock
4190
4191 if (needWake) {
4192 mLooper->wake();
4193 }
4194}
4195
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05004196/**
4197 * If one of the meta shortcuts is detected, process them here:
Vaibhav Devmurari34cd5b02023-02-23 14:51:18 +00004198 * Meta + Backspace; Meta + Grave; Meta + Left arrow -> generate BACK
4199 * Most System shortcuts are handled in PhoneWindowManager.java except 'Back' shortcuts. Unlike
4200 * Back, other shortcuts DO NOT need to be sent to applications and are fully handled by the system.
4201 * But for Back key and Back shortcuts, we need to send KEYCODE_BACK to applications which can
4202 * potentially handle the back key presses.
4203 * Note: We don't send any Meta based KeyEvents to applications, so we need to convert to a KeyEvent
4204 * where meta modifier is off before sending. Currently only use case is 'Back'.
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05004205 */
4206void InputDispatcher::accelerateMetaShortcuts(const int32_t deviceId, const int32_t action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004207 int32_t& keyCode, int32_t& metaState) {
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05004208 if (metaState & AMETA_META_ON && action == AKEY_EVENT_ACTION_DOWN) {
4209 int32_t newKeyCode = AKEYCODE_UNKNOWN;
Vaibhav Devmurari34cd5b02023-02-23 14:51:18 +00004210 if (keyCode == AKEYCODE_DEL || keyCode == AKEYCODE_GRAVE || keyCode == AKEYCODE_DPAD_LEFT) {
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05004211 newKeyCode = AKEYCODE_BACK;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05004212 }
4213 if (newKeyCode != AKEYCODE_UNKNOWN) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004214 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05004215 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004216 mReplacedKeys[replacement] = newKeyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05004217 keyCode = newKeyCode;
4218 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
4219 }
4220 } else if (action == AKEY_EVENT_ACTION_UP) {
4221 // In order to maintain a consistent stream of up and down events, check to see if the key
4222 // going up is one we've replaced in a down event and haven't yet replaced in an up event,
4223 // even if the modifier was released between the down and the up events.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004224 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05004225 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004226 auto replacementIt = mReplacedKeys.find(replacement);
4227 if (replacementIt != mReplacedKeys.end()) {
4228 keyCode = replacementIt->second;
4229 mReplacedKeys.erase(replacementIt);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05004230 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
4231 }
4232 }
4233}
4234
Prabir Pradhan678438e2023-04-13 19:32:51 +00004235void InputDispatcher::notifyKey(const NotifyKeyArgs& args) {
Prabir Pradhan96282b02023-02-24 22:36:17 +00004236 ALOGD_IF(debugInboundEventDetails(),
4237 "notifyKey - id=%" PRIx32 ", eventTime=%" PRId64
4238 ", deviceId=%d, source=%s, displayId=%" PRId32
4239 "policyFlags=0x%x, action=%s, flags=0x%x, keyCode=%s, scanCode=0x%x, metaState=0x%x, "
4240 "downTime=%" PRId64,
Prabir Pradhan678438e2023-04-13 19:32:51 +00004241 args.id, args.eventTime, args.deviceId, inputEventSourceToString(args.source).c_str(),
4242 args.displayId, args.policyFlags, KeyEvent::actionToString(args.action), args.flags,
4243 KeyEvent::getLabel(args.keyCode), args.scanCode, args.metaState, args.downTime);
Siarhei Vishniakou6773db62023-04-21 11:30:20 -07004244 Result<void> keyCheck = validateKeyEvent(args.action);
4245 if (!keyCheck.ok()) {
4246 LOG(ERROR) << "invalid key event: " << keyCheck.error();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004247 return;
4248 }
4249
Prabir Pradhan678438e2023-04-13 19:32:51 +00004250 uint32_t policyFlags = args.policyFlags;
4251 int32_t flags = args.flags;
4252 int32_t metaState = args.metaState;
Siarhei Vishniakou622bd322018-10-29 18:02:27 -07004253 // InputDispatcher tracks and generates key repeats on behalf of
4254 // whatever notifies it, so repeatCount should always be set to 0
4255 constexpr int32_t repeatCount = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004256 if ((policyFlags & POLICY_FLAG_VIRTUAL) || (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY)) {
4257 policyFlags |= POLICY_FLAG_VIRTUAL;
4258 flags |= AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
4259 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004260 if (policyFlags & POLICY_FLAG_FUNCTION) {
4261 metaState |= AMETA_FUNCTION_ON;
4262 }
4263
4264 policyFlags |= POLICY_FLAG_TRUSTED;
4265
Prabir Pradhan678438e2023-04-13 19:32:51 +00004266 int32_t keyCode = args.keyCode;
4267 accelerateMetaShortcuts(args.deviceId, args.action, keyCode, metaState);
Michael Wright78f24442014-08-06 15:55:28 -07004268
Michael Wrightd02c5b62014-02-10 15:10:22 -08004269 KeyEvent event;
Prabir Pradhan678438e2023-04-13 19:32:51 +00004270 event.initialize(args.id, args.deviceId, args.source, args.displayId, INVALID_HMAC, args.action,
4271 flags, keyCode, args.scanCode, metaState, repeatCount, args.downTime,
4272 args.eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004273
Michael Wright2b3c3302018-03-02 17:19:13 +00004274 android::base::Timer t;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004275 mPolicy.interceptKeyBeforeQueueing(event, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00004276 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4277 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004278 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00004279 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004280
Antonio Kantekf16f2832021-09-28 04:39:20 +00004281 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004282 { // acquire lock
4283 mLock.lock();
4284
4285 if (shouldSendKeyToInputFilterLocked(args)) {
4286 mLock.unlock();
4287
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004288 policyFlags |= POLICY_FLAG_FILTERED;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004289 if (!mPolicy.filterInputEvent(event, policyFlags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004290 return; // event was consumed by the filter
4291 }
4292
4293 mLock.lock();
4294 }
4295
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004296 std::unique_ptr<KeyEntry> newEntry =
Prabir Pradhan678438e2023-04-13 19:32:51 +00004297 std::make_unique<KeyEntry>(args.id, args.eventTime, args.deviceId, args.source,
4298 args.displayId, policyFlags, args.action, flags, keyCode,
4299 args.scanCode, metaState, repeatCount, args.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004300
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004301 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004302 mLock.unlock();
4303 } // release lock
4304
4305 if (needWake) {
4306 mLooper->wake();
4307 }
4308}
4309
Prabir Pradhan678438e2023-04-13 19:32:51 +00004310bool InputDispatcher::shouldSendKeyToInputFilterLocked(const NotifyKeyArgs& args) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004311 return mInputFilterEnabled;
4312}
4313
Prabir Pradhan678438e2023-04-13 19:32:51 +00004314void InputDispatcher::notifyMotion(const NotifyMotionArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004315 if (debugInboundEventDetails()) {
Prabir Pradhan96282b02023-02-24 22:36:17 +00004316 ALOGD("notifyMotion - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=%s, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004317 "displayId=%" PRId32 ", policyFlags=0x%x, "
Siarhei Vishniakou6ebd0692022-10-20 15:05:45 -07004318 "action=%s, actionButton=0x%x, flags=0x%x, metaState=0x%x, buttonState=0x%x, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004319 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, xCursorPosition=%f, "
4320 "yCursorPosition=%f, downTime=%" PRId64,
Prabir Pradhan678438e2023-04-13 19:32:51 +00004321 args.id, args.eventTime, args.deviceId, inputEventSourceToString(args.source).c_str(),
4322 args.displayId, args.policyFlags, MotionEvent::actionToString(args.action).c_str(),
4323 args.actionButton, args.flags, args.metaState, args.buttonState, args.edgeFlags,
4324 args.xPrecision, args.yPrecision, args.xCursorPosition, args.yCursorPosition,
4325 args.downTime);
4326 for (uint32_t i = 0; i < args.pointerCount; i++) {
Prabir Pradhan96282b02023-02-24 22:36:17 +00004327 ALOGD(" Pointer %d: id=%d, toolType=%s, x=%f, y=%f, pressure=%f, size=%f, "
4328 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, orientation=%f",
Prabir Pradhan678438e2023-04-13 19:32:51 +00004329 i, args.pointerProperties[i].id,
4330 ftl::enum_string(args.pointerProperties[i].toolType).c_str(),
4331 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
4332 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
4333 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
4334 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
4335 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
4336 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
4337 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
4338 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
4339 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004340 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004341 }
Siarhei Vishniakou4ca97272023-03-01 11:31:35 -08004342
Siarhei Vishniakou6773db62023-04-21 11:30:20 -07004343 Result<void> motionCheck = validateMotionEvent(args.action, args.actionButton,
4344 args.pointerCount, args.pointerProperties);
4345 if (!motionCheck.ok()) {
4346 LOG(ERROR) << "Invalid event: " << args.dump() << "; reason: " << motionCheck.error();
Siarhei Vishniakou4ca97272023-03-01 11:31:35 -08004347 return;
4348 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004349
Prabir Pradhan678438e2023-04-13 19:32:51 +00004350 uint32_t policyFlags = args.policyFlags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004351 policyFlags |= POLICY_FLAG_TRUSTED;
Michael Wright2b3c3302018-03-02 17:19:13 +00004352
4353 android::base::Timer t;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004354 mPolicy.interceptMotionBeforeQueueing(args.displayId, args.eventTime, policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00004355 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4356 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004357 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00004358 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004359
Antonio Kantekf16f2832021-09-28 04:39:20 +00004360 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004361 { // acquire lock
4362 mLock.lock();
Siarhei Vishniakou5bf25d92023-02-08 15:43:38 -08004363 if (!(policyFlags & POLICY_FLAG_PASS_TO_USER)) {
4364 // Set the flag anyway if we already have an ongoing gesture. That would allow us to
4365 // complete the processing of the current stroke.
Prabir Pradhan678438e2023-04-13 19:32:51 +00004366 const auto touchStateIt = mTouchStatesByDisplay.find(args.displayId);
Siarhei Vishniakou5bf25d92023-02-08 15:43:38 -08004367 if (touchStateIt != mTouchStatesByDisplay.end()) {
4368 const TouchState& touchState = touchStateIt->second;
Prabir Pradhan678438e2023-04-13 19:32:51 +00004369 if (touchState.deviceId == args.deviceId && touchState.isDown()) {
Siarhei Vishniakou5bf25d92023-02-08 15:43:38 -08004370 policyFlags |= POLICY_FLAG_PASS_TO_USER;
4371 }
4372 }
4373 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004374
4375 if (shouldSendMotionToInputFilterLocked(args)) {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004376 ui::Transform displayTransform;
Prabir Pradhan678438e2023-04-13 19:32:51 +00004377 if (const auto it = mDisplayInfos.find(args.displayId); it != mDisplayInfos.end()) {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004378 displayTransform = it->second.transform;
4379 }
4380
Michael Wrightd02c5b62014-02-10 15:10:22 -08004381 mLock.unlock();
4382
4383 MotionEvent event;
Prabir Pradhan678438e2023-04-13 19:32:51 +00004384 event.initialize(args.id, args.deviceId, args.source, args.displayId, INVALID_HMAC,
4385 args.action, args.actionButton, args.flags, args.edgeFlags,
4386 args.metaState, args.buttonState, args.classification,
4387 displayTransform, args.xPrecision, args.yPrecision,
4388 args.xCursorPosition, args.yCursorPosition, displayTransform,
4389 args.downTime, args.eventTime, args.pointerCount,
4390 args.pointerProperties, args.pointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004391
4392 policyFlags |= POLICY_FLAG_FILTERED;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004393 if (!mPolicy.filterInputEvent(event, policyFlags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004394 return; // event was consumed by the filter
4395 }
4396
4397 mLock.lock();
4398 }
4399
4400 // Just enqueue a new motion event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004401 std::unique_ptr<MotionEntry> newEntry =
Prabir Pradhan678438e2023-04-13 19:32:51 +00004402 std::make_unique<MotionEntry>(args.id, args.eventTime, args.deviceId, args.source,
4403 args.displayId, policyFlags, args.action,
4404 args.actionButton, args.flags, args.metaState,
4405 args.buttonState, args.classification, args.edgeFlags,
4406 args.xPrecision, args.yPrecision,
4407 args.xCursorPosition, args.yCursorPosition,
4408 args.downTime, args.pointerCount,
4409 args.pointerProperties, args.pointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004410
Prabir Pradhan678438e2023-04-13 19:32:51 +00004411 if (args.id != android::os::IInputConstants::INVALID_INPUT_EVENT_ID &&
4412 IdGenerator::getSource(args.id) == IdGenerator::Source::INPUT_READER &&
Siarhei Vishniakou363e7292021-07-09 03:22:42 +00004413 !mInputFilterEnabled) {
Prabir Pradhan678438e2023-04-13 19:32:51 +00004414 const bool isDown = args.action == AMOTION_EVENT_ACTION_DOWN;
4415 mLatencyTracker.trackListener(args.id, isDown, args.eventTime, args.readTime);
Siarhei Vishniakou363e7292021-07-09 03:22:42 +00004416 }
4417
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004418 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004419 mLock.unlock();
4420 } // release lock
4421
4422 if (needWake) {
4423 mLooper->wake();
4424 }
4425}
4426
Prabir Pradhan678438e2023-04-13 19:32:51 +00004427void InputDispatcher::notifySensor(const NotifySensorArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004428 if (debugInboundEventDetails()) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004429 ALOGD("notifySensor - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=0x%x, "
4430 " sensorType=%s",
Prabir Pradhan678438e2023-04-13 19:32:51 +00004431 args.id, args.eventTime, args.deviceId, args.source,
4432 ftl::enum_string(args.sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004433 }
Chris Yef59a2f42020-10-16 12:55:26 -07004434
Antonio Kantekf16f2832021-09-28 04:39:20 +00004435 bool needWake = false;
Chris Yef59a2f42020-10-16 12:55:26 -07004436 { // acquire lock
4437 mLock.lock();
4438
4439 // Just enqueue a new sensor event.
4440 std::unique_ptr<SensorEntry> newEntry =
Prabir Pradhan678438e2023-04-13 19:32:51 +00004441 std::make_unique<SensorEntry>(args.id, args.eventTime, args.deviceId, args.source,
4442 /* policyFlags=*/0, args.hwTimestamp, args.sensorType,
4443 args.accuracy, args.accuracyChanged, args.values);
Chris Yef59a2f42020-10-16 12:55:26 -07004444
4445 needWake = enqueueInboundEventLocked(std::move(newEntry));
4446 mLock.unlock();
4447 } // release lock
4448
4449 if (needWake) {
4450 mLooper->wake();
4451 }
4452}
4453
Prabir Pradhan678438e2023-04-13 19:32:51 +00004454void InputDispatcher::notifyVibratorState(const NotifyVibratorStateArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004455 if (debugInboundEventDetails()) {
Prabir Pradhan678438e2023-04-13 19:32:51 +00004456 ALOGD("notifyVibratorState - eventTime=%" PRId64 ", device=%d, isOn=%d", args.eventTime,
4457 args.deviceId, args.isOn);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004458 }
Prabir Pradhana41d2442023-04-20 21:30:40 +00004459 mPolicy.notifyVibratorState(args.deviceId, args.isOn);
Chris Yefb552902021-02-03 17:18:37 -08004460}
4461
Prabir Pradhan678438e2023-04-13 19:32:51 +00004462bool InputDispatcher::shouldSendMotionToInputFilterLocked(const NotifyMotionArgs& args) {
Jackal Guof9696682018-10-05 12:23:23 +08004463 return mInputFilterEnabled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004464}
4465
Prabir Pradhan678438e2023-04-13 19:32:51 +00004466void InputDispatcher::notifySwitch(const NotifySwitchArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004467 if (debugInboundEventDetails()) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004468 ALOGD("notifySwitch - eventTime=%" PRId64 ", policyFlags=0x%x, switchValues=0x%08x, "
4469 "switchMask=0x%08x",
Prabir Pradhan678438e2023-04-13 19:32:51 +00004470 args.eventTime, args.policyFlags, args.switchValues, args.switchMask);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004471 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004472
Prabir Pradhan678438e2023-04-13 19:32:51 +00004473 uint32_t policyFlags = args.policyFlags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004474 policyFlags |= POLICY_FLAG_TRUSTED;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004475 mPolicy.notifySwitch(args.eventTime, args.switchValues, args.switchMask, policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004476}
4477
Prabir Pradhan678438e2023-04-13 19:32:51 +00004478void InputDispatcher::notifyDeviceReset(const NotifyDeviceResetArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004479 if (debugInboundEventDetails()) {
Prabir Pradhan678438e2023-04-13 19:32:51 +00004480 ALOGD("notifyDeviceReset - eventTime=%" PRId64 ", deviceId=%d", args.eventTime,
4481 args.deviceId);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004482 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004483
Antonio Kantekf16f2832021-09-28 04:39:20 +00004484 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004485 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004486 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004487
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004488 std::unique_ptr<DeviceResetEntry> newEntry =
Prabir Pradhan678438e2023-04-13 19:32:51 +00004489 std::make_unique<DeviceResetEntry>(args.id, args.eventTime, args.deviceId);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004490 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004491 } // release lock
4492
4493 if (needWake) {
4494 mLooper->wake();
4495 }
4496}
4497
Prabir Pradhan678438e2023-04-13 19:32:51 +00004498void InputDispatcher::notifyPointerCaptureChanged(const NotifyPointerCaptureChangedArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004499 if (debugInboundEventDetails()) {
Prabir Pradhan678438e2023-04-13 19:32:51 +00004500 ALOGD("notifyPointerCaptureChanged - eventTime=%" PRId64 ", enabled=%s", args.eventTime,
4501 args.request.enable ? "true" : "false");
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004502 }
Prabir Pradhan7e186182020-11-10 13:56:45 -08004503
Antonio Kantekf16f2832021-09-28 04:39:20 +00004504 bool needWake = false;
Prabir Pradhan99987712020-11-10 18:43:05 -08004505 { // acquire lock
4506 std::scoped_lock _l(mLock);
Prabir Pradhan678438e2023-04-13 19:32:51 +00004507 auto entry =
4508 std::make_unique<PointerCaptureChangedEntry>(args.id, args.eventTime, args.request);
Prabir Pradhan99987712020-11-10 18:43:05 -08004509 needWake = enqueueInboundEventLocked(std::move(entry));
4510 } // release lock
4511
4512 if (needWake) {
4513 mLooper->wake();
4514 }
Prabir Pradhan7e186182020-11-10 13:56:45 -08004515}
4516
Prabir Pradhan5735a322022-04-11 17:23:34 +00004517InputEventInjectionResult InputDispatcher::injectInputEvent(const InputEvent* event,
4518 std::optional<int32_t> targetUid,
4519 InputEventInjectionSync syncMode,
4520 std::chrono::milliseconds timeout,
4521 uint32_t policyFlags) {
Siarhei Vishniakou6773db62023-04-21 11:30:20 -07004522 Result<void> eventValidation = validateInputEvent(*event);
4523 if (!eventValidation.ok()) {
4524 LOG(INFO) << "Injection failed: invalid event: " << eventValidation.error();
4525 return InputEventInjectionResult::FAILED;
4526 }
4527
Prabir Pradhan65613802023-02-22 23:36:58 +00004528 if (debugInboundEventDetails()) {
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004529 LOG(DEBUG) << __func__ << ": targetUid=" << toString(targetUid)
4530 << ", syncMode=" << ftl::enum_string(syncMode) << ", timeout=" << timeout.count()
4531 << "ms, policyFlags=0x" << std::hex << policyFlags << std::dec
4532 << ", event=" << *event;
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004533 }
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07004534 nsecs_t endTime = now() + std::chrono::duration_cast<std::chrono::nanoseconds>(timeout).count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004535
Prabir Pradhan5735a322022-04-11 17:23:34 +00004536 policyFlags |= POLICY_FLAG_INJECTED | POLICY_FLAG_TRUSTED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004537
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004538 // For all injected events, set device id = VIRTUAL_KEYBOARD_ID. The only exception is events
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004539 // that have gone through the InputFilter. If the event passed through the InputFilter, assign
4540 // the provided device id. If the InputFilter is accessibility, and it modifies or synthesizes
4541 // the injected event, it is responsible for setting POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY.
4542 // For those events, we will set FLAG_IS_ACCESSIBILITY_EVENT to allow apps to distinguish them
4543 // from events that originate from actual hardware.
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004544 int32_t resolvedDeviceId = VIRTUAL_KEYBOARD_ID;
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004545 if (policyFlags & POLICY_FLAG_FILTERED) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004546 resolvedDeviceId = event->getDeviceId();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004547 }
4548
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004549 std::queue<std::unique_ptr<EventEntry>> injectedEntries;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004550 switch (event->getType()) {
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004551 case InputEventType::KEY: {
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004552 const KeyEvent& incomingKey = static_cast<const KeyEvent&>(*event);
Siarhei Vishniakou6773db62023-04-21 11:30:20 -07004553 const int32_t action = incomingKey.getAction();
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004554 int32_t flags = incomingKey.getFlags();
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004555 if (policyFlags & POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY) {
4556 flags |= AKEY_EVENT_FLAG_IS_ACCESSIBILITY_EVENT;
4557 }
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004558 int32_t keyCode = incomingKey.getKeyCode();
4559 int32_t metaState = incomingKey.getMetaState();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004560 accelerateMetaShortcuts(resolvedDeviceId, action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004561 /*byref*/ keyCode, /*byref*/ metaState);
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004562 KeyEvent keyEvent;
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004563 keyEvent.initialize(incomingKey.getId(), resolvedDeviceId, incomingKey.getSource(),
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004564 incomingKey.getDisplayId(), INVALID_HMAC, action, flags, keyCode,
4565 incomingKey.getScanCode(), metaState, incomingKey.getRepeatCount(),
4566 incomingKey.getDownTime(), incomingKey.getEventTime());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004567
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004568 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
4569 policyFlags |= POLICY_FLAG_VIRTUAL;
Michael Wright2b3c3302018-03-02 17:19:13 +00004570 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004571
4572 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
4573 android::base::Timer t;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004574 mPolicy.interceptKeyBeforeQueueing(keyEvent, /*byref*/ policyFlags);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004575 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4576 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
4577 std::to_string(t.duration().count()).c_str());
4578 }
4579 }
4580
4581 mLock.lock();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004582 std::unique_ptr<KeyEntry> injectedEntry =
4583 std::make_unique<KeyEntry>(incomingKey.getId(), incomingKey.getEventTime(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004584 resolvedDeviceId, incomingKey.getSource(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004585 incomingKey.getDisplayId(), policyFlags, action,
4586 flags, keyCode, incomingKey.getScanCode(), metaState,
4587 incomingKey.getRepeatCount(),
4588 incomingKey.getDownTime());
4589 injectedEntries.push(std::move(injectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004590 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004591 }
4592
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004593 case InputEventType::MOTION: {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004594 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(*event);
Prabir Pradhanaa561d12021-09-24 06:57:33 -07004595 const bool isPointerEvent =
4596 isFromSource(event->getSource(), AINPUT_SOURCE_CLASS_POINTER);
4597 // If a pointer event has no displayId specified, inject it to the default display.
4598 const uint32_t displayId = isPointerEvent && (event->getDisplayId() == ADISPLAY_ID_NONE)
4599 ? ADISPLAY_ID_DEFAULT
4600 : event->getDisplayId();
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004601 int32_t flags = motionEvent.getFlags();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004602
4603 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004604 nsecs_t eventTime = motionEvent.getEventTime();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004605 android::base::Timer t;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004606 mPolicy.interceptMotionBeforeQueueing(displayId, eventTime, /*byref*/ policyFlags);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004607 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4608 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
4609 std::to_string(t.duration().count()).c_str());
4610 }
4611 }
4612
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004613 if (policyFlags & POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY) {
4614 flags |= AMOTION_EVENT_FLAG_IS_ACCESSIBILITY_EVENT;
4615 }
4616
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004617 mLock.lock();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004618 const nsecs_t* sampleEventTimes = motionEvent.getSampleEventTimes();
4619 const PointerCoords* samplePointerCoords = motionEvent.getSamplePointerCoords();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004620 std::unique_ptr<MotionEntry> injectedEntry =
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004621 std::make_unique<MotionEntry>(motionEvent.getId(), *sampleEventTimes,
4622 resolvedDeviceId, motionEvent.getSource(),
Siarhei Vishniakou6773db62023-04-21 11:30:20 -07004623 displayId, policyFlags, motionEvent.getAction(),
4624 motionEvent.getActionButton(), flags,
4625 motionEvent.getMetaState(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004626 motionEvent.getButtonState(),
4627 motionEvent.getClassification(),
4628 motionEvent.getEdgeFlags(),
4629 motionEvent.getXPrecision(),
4630 motionEvent.getYPrecision(),
4631 motionEvent.getRawXCursorPosition(),
4632 motionEvent.getRawYCursorPosition(),
Siarhei Vishniakou6773db62023-04-21 11:30:20 -07004633 motionEvent.getDownTime(),
4634 motionEvent.getPointerCount(),
4635 motionEvent.getPointerProperties(),
4636 samplePointerCoords);
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004637 transformMotionEntryForInjectionLocked(*injectedEntry, motionEvent.getTransform());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004638 injectedEntries.push(std::move(injectedEntry));
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004639 for (size_t i = motionEvent.getHistorySize(); i > 0; i--) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004640 sampleEventTimes += 1;
Siarhei Vishniakou6773db62023-04-21 11:30:20 -07004641 samplePointerCoords += motionEvent.getPointerCount();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004642 std::unique_ptr<MotionEntry> nextInjectedEntry =
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004643 std::make_unique<MotionEntry>(motionEvent.getId(), *sampleEventTimes,
4644 resolvedDeviceId, motionEvent.getSource(),
Siarhei Vishniakou6773db62023-04-21 11:30:20 -07004645 displayId, policyFlags,
4646 motionEvent.getAction(),
4647 motionEvent.getActionButton(), flags,
4648 motionEvent.getMetaState(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004649 motionEvent.getButtonState(),
4650 motionEvent.getClassification(),
4651 motionEvent.getEdgeFlags(),
4652 motionEvent.getXPrecision(),
4653 motionEvent.getYPrecision(),
4654 motionEvent.getRawXCursorPosition(),
4655 motionEvent.getRawYCursorPosition(),
4656 motionEvent.getDownTime(),
Siarhei Vishniakou6773db62023-04-21 11:30:20 -07004657 motionEvent.getPointerCount(),
4658 motionEvent.getPointerProperties(),
Prabir Pradhan5beda762021-12-10 09:30:08 +00004659 samplePointerCoords);
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004660 transformMotionEntryForInjectionLocked(*nextInjectedEntry,
4661 motionEvent.getTransform());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004662 injectedEntries.push(std::move(nextInjectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004663 }
4664 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004665 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004666
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004667 default:
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004668 LOG(WARNING) << "Cannot inject " << ftl::enum_string(event->getType()) << " events";
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004669 return InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004670 }
4671
Prabir Pradhan5735a322022-04-11 17:23:34 +00004672 InjectionState* injectionState = new InjectionState(targetUid);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004673 if (syncMode == InputEventInjectionSync::NONE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004674 injectionState->injectionIsAsync = true;
4675 }
4676
4677 injectionState->refCount += 1;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004678 injectedEntries.back()->injectionState = injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004679
4680 bool needWake = false;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004681 while (!injectedEntries.empty()) {
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08004682 if (DEBUG_INJECTION) {
4683 LOG(DEBUG) << "Injecting " << injectedEntries.front()->getDescription();
4684 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004685 needWake |= enqueueInboundEventLocked(std::move(injectedEntries.front()));
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004686 injectedEntries.pop();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004687 }
4688
4689 mLock.unlock();
4690
4691 if (needWake) {
4692 mLooper->wake();
4693 }
4694
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004695 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004696 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004697 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004698
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004699 if (syncMode == InputEventInjectionSync::NONE) {
4700 injectionResult = InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004701 } else {
4702 for (;;) {
4703 injectionResult = injectionState->injectionResult;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004704 if (injectionResult != InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004705 break;
4706 }
4707
4708 nsecs_t remainingTimeout = endTime - now();
4709 if (remainingTimeout <= 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004710 if (DEBUG_INJECTION) {
4711 ALOGD("injectInputEvent - Timed out waiting for injection result "
4712 "to become available.");
4713 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004714 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004715 break;
4716 }
4717
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004718 mInjectionResultAvailable.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004719 }
4720
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004721 if (injectionResult == InputEventInjectionResult::SUCCEEDED &&
4722 syncMode == InputEventInjectionSync::WAIT_FOR_FINISHED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004723 while (injectionState->pendingForegroundDispatches != 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004724 if (DEBUG_INJECTION) {
4725 ALOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
4726 injectionState->pendingForegroundDispatches);
4727 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004728 nsecs_t remainingTimeout = endTime - now();
4729 if (remainingTimeout <= 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004730 if (DEBUG_INJECTION) {
4731 ALOGD("injectInputEvent - Timed out waiting for pending foreground "
4732 "dispatches to finish.");
4733 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004734 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004735 break;
4736 }
4737
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004738 mInjectionSyncFinished.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004739 }
4740 }
4741 }
4742
4743 injectionState->release();
4744 } // release lock
4745
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004746 if (DEBUG_INJECTION) {
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08004747 LOG(DEBUG) << "injectInputEvent - Finished with result "
4748 << ftl::enum_string(injectionResult);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004749 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004750
4751 return injectionResult;
4752}
4753
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004754std::unique_ptr<VerifiedInputEvent> InputDispatcher::verifyInputEvent(const InputEvent& event) {
Gang Wange9087892020-01-07 12:17:14 -05004755 std::array<uint8_t, 32> calculatedHmac;
4756 std::unique_ptr<VerifiedInputEvent> result;
4757 switch (event.getType()) {
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004758 case InputEventType::KEY: {
Gang Wange9087892020-01-07 12:17:14 -05004759 const KeyEvent& keyEvent = static_cast<const KeyEvent&>(event);
4760 VerifiedKeyEvent verifiedKeyEvent = verifiedKeyEventFromKeyEvent(keyEvent);
4761 result = std::make_unique<VerifiedKeyEvent>(verifiedKeyEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004762 calculatedHmac = sign(verifiedKeyEvent);
Gang Wange9087892020-01-07 12:17:14 -05004763 break;
4764 }
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004765 case InputEventType::MOTION: {
Gang Wange9087892020-01-07 12:17:14 -05004766 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(event);
4767 VerifiedMotionEvent verifiedMotionEvent =
4768 verifiedMotionEventFromMotionEvent(motionEvent);
4769 result = std::make_unique<VerifiedMotionEvent>(verifiedMotionEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004770 calculatedHmac = sign(verifiedMotionEvent);
Gang Wange9087892020-01-07 12:17:14 -05004771 break;
4772 }
4773 default: {
4774 ALOGE("Cannot verify events of type %" PRId32, event.getType());
4775 return nullptr;
4776 }
4777 }
4778 if (calculatedHmac == INVALID_HMAC) {
4779 return nullptr;
4780 }
tyiu1573a672023-02-21 22:38:32 +00004781 if (0 != CRYPTO_memcmp(calculatedHmac.data(), event.getHmac().data(), calculatedHmac.size())) {
Gang Wange9087892020-01-07 12:17:14 -05004782 return nullptr;
4783 }
4784 return result;
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004785}
4786
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004787void InputDispatcher::setInjectionResult(EventEntry& entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004788 InputEventInjectionResult injectionResult) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004789 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004790 if (injectionState) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004791 if (DEBUG_INJECTION) {
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08004792 LOG(DEBUG) << "Setting input event injection result to "
4793 << ftl::enum_string(injectionResult);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004794 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004795
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004796 if (injectionState->injectionIsAsync && !(entry.policyFlags & POLICY_FLAG_FILTERED)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004797 // Log the outcome since the injector did not wait for the injection result.
4798 switch (injectionResult) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004799 case InputEventInjectionResult::SUCCEEDED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004800 ALOGV("Asynchronous input event injection succeeded.");
4801 break;
Prabir Pradhan5735a322022-04-11 17:23:34 +00004802 case InputEventInjectionResult::TARGET_MISMATCH:
4803 ALOGV("Asynchronous input event injection target mismatch.");
4804 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004805 case InputEventInjectionResult::FAILED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004806 ALOGW("Asynchronous input event injection failed.");
4807 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004808 case InputEventInjectionResult::TIMED_OUT:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004809 ALOGW("Asynchronous input event injection timed out.");
4810 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004811 case InputEventInjectionResult::PENDING:
4812 ALOGE("Setting result to 'PENDING' for asynchronous injection");
4813 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004814 }
4815 }
4816
4817 injectionState->injectionResult = injectionResult;
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004818 mInjectionResultAvailable.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004819 }
4820}
4821
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004822void InputDispatcher::transformMotionEntryForInjectionLocked(
4823 MotionEntry& entry, const ui::Transform& injectedTransform) const {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004824 // Input injection works in the logical display coordinate space, but the input pipeline works
4825 // display space, so we need to transform the injected events accordingly.
4826 const auto it = mDisplayInfos.find(entry.displayId);
4827 if (it == mDisplayInfos.end()) return;
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004828 const auto& transformToDisplay = it->second.transform.inverse() * injectedTransform;
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004829
Prabir Pradhand9a2ebe2022-07-20 19:25:13 +00004830 if (entry.xCursorPosition != AMOTION_EVENT_INVALID_CURSOR_POSITION &&
4831 entry.yCursorPosition != AMOTION_EVENT_INVALID_CURSOR_POSITION) {
4832 const vec2 cursor =
4833 MotionEvent::calculateTransformedXY(entry.source, transformToDisplay,
4834 {entry.xCursorPosition, entry.yCursorPosition});
4835 entry.xCursorPosition = cursor.x;
4836 entry.yCursorPosition = cursor.y;
4837 }
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004838 for (uint32_t i = 0; i < entry.pointerCount; i++) {
Prabir Pradhan8e6ce222022-02-24 09:08:54 -08004839 entry.pointerCoords[i] =
4840 MotionEvent::calculateTransformedCoords(entry.source, transformToDisplay,
4841 entry.pointerCoords[i]);
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004842 }
4843}
4844
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004845void InputDispatcher::incrementPendingForegroundDispatches(EventEntry& entry) {
4846 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004847 if (injectionState) {
4848 injectionState->pendingForegroundDispatches += 1;
4849 }
4850}
4851
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004852void InputDispatcher::decrementPendingForegroundDispatches(EventEntry& entry) {
4853 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004854 if (injectionState) {
4855 injectionState->pendingForegroundDispatches -= 1;
4856
4857 if (injectionState->pendingForegroundDispatches == 0) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004858 mInjectionSyncFinished.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004859 }
4860 }
4861}
4862
chaviw98318de2021-05-19 16:45:23 -05004863const std::vector<sp<WindowInfoHandle>>& InputDispatcher::getWindowHandlesLocked(
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004864 int32_t displayId) const {
chaviw98318de2021-05-19 16:45:23 -05004865 static const std::vector<sp<WindowInfoHandle>> EMPTY_WINDOW_HANDLES;
Vishnu Nairad321cd2020-08-20 16:40:21 -07004866 auto it = mWindowHandlesByDisplay.find(displayId);
4867 return it != mWindowHandlesByDisplay.end() ? it->second : EMPTY_WINDOW_HANDLES;
Arthur Hungb92218b2018-08-14 12:00:21 +08004868}
4869
chaviw98318de2021-05-19 16:45:23 -05004870sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(
chaviwfbe5d9c2018-12-26 12:23:37 -08004871 const sp<IBinder>& windowHandleToken) const {
arthurhungbe737672020-06-24 12:29:21 +08004872 if (windowHandleToken == nullptr) {
4873 return nullptr;
4874 }
4875
Arthur Hungb92218b2018-08-14 12:00:21 +08004876 for (auto& it : mWindowHandlesByDisplay) {
chaviw98318de2021-05-19 16:45:23 -05004877 const std::vector<sp<WindowInfoHandle>>& windowHandles = it.second;
4878 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
chaviwfbe5d9c2018-12-26 12:23:37 -08004879 if (windowHandle->getToken() == windowHandleToken) {
Arthur Hungb92218b2018-08-14 12:00:21 +08004880 return windowHandle;
4881 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004882 }
4883 }
Yi Kong9b14ac62018-07-17 13:48:38 -07004884 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004885}
4886
chaviw98318de2021-05-19 16:45:23 -05004887sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(const sp<IBinder>& windowHandleToken,
4888 int displayId) const {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004889 if (windowHandleToken == nullptr) {
4890 return nullptr;
4891 }
4892
chaviw98318de2021-05-19 16:45:23 -05004893 for (const sp<WindowInfoHandle>& windowHandle : getWindowHandlesLocked(displayId)) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004894 if (windowHandle->getToken() == windowHandleToken) {
4895 return windowHandle;
4896 }
4897 }
4898 return nullptr;
4899}
4900
chaviw98318de2021-05-19 16:45:23 -05004901sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(
4902 const sp<WindowInfoHandle>& windowHandle) const {
Mady Mellor017bcd12020-06-23 19:12:00 +00004903 for (auto& it : mWindowHandlesByDisplay) {
chaviw98318de2021-05-19 16:45:23 -05004904 const std::vector<sp<WindowInfoHandle>>& windowHandles = it.second;
4905 for (const sp<WindowInfoHandle>& handle : windowHandles) {
arthurhungbe737672020-06-24 12:29:21 +08004906 if (handle->getId() == windowHandle->getId() &&
4907 handle->getToken() == windowHandle->getToken()) {
Mady Mellor017bcd12020-06-23 19:12:00 +00004908 if (windowHandle->getInfo()->displayId != it.first) {
4909 ALOGE("Found window %s in display %" PRId32
4910 ", but it should belong to display %" PRId32,
4911 windowHandle->getName().c_str(), it.first,
4912 windowHandle->getInfo()->displayId);
4913 }
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004914 return handle;
Arthur Hungb92218b2018-08-14 12:00:21 +08004915 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004916 }
4917 }
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004918 return nullptr;
4919}
4920
chaviw98318de2021-05-19 16:45:23 -05004921sp<WindowInfoHandle> InputDispatcher::getFocusedWindowHandleLocked(int displayId) const {
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004922 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(displayId);
4923 return getWindowHandleLocked(focusedToken, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004924}
4925
Prabir Pradhan33e3baa2022-12-06 20:30:22 +00004926ui::Transform InputDispatcher::getTransformLocked(int32_t displayId) const {
4927 auto displayInfoIt = mDisplayInfos.find(displayId);
4928 return displayInfoIt != mDisplayInfos.end() ? displayInfoIt->second.transform
4929 : kIdentityTransform;
4930}
4931
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004932bool InputDispatcher::canWindowReceiveMotionLocked(const sp<WindowInfoHandle>& window,
4933 const MotionEntry& motionEntry) const {
4934 const WindowInfo& info = *window->getInfo();
4935
4936 // Skip spy window targets that are not valid for targeted injection.
4937 if (const auto err = verifyTargetedInjection(window, motionEntry); err) {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004938 return false;
4939 }
4940
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004941 if (info.inputConfig.test(WindowInfo::InputConfig::PAUSE_DISPATCHING)) {
4942 ALOGI("Not sending touch event to %s because it is paused", window->getName().c_str());
4943 return false;
4944 }
4945
4946 if (info.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL)) {
4947 ALOGW("Not sending touch gesture to %s because it has config NO_INPUT_CHANNEL",
4948 window->getName().c_str());
4949 return false;
4950 }
4951
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07004952 std::shared_ptr<Connection> connection = getConnectionLocked(window->getToken());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004953 if (connection == nullptr) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004954 ALOGW("Not sending touch to %s because there's no corresponding connection",
4955 window->getName().c_str());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004956 return false;
4957 }
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004958
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004959 if (!connection->responsive) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004960 ALOGW("Not sending touch to %s because it is not responsive", window->getName().c_str());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004961 return false;
4962 }
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004963
4964 // Drop events that can't be trusted due to occlusion
4965 const auto [x, y] = resolveTouchedPosition(motionEntry);
4966 TouchOcclusionInfo occlusionInfo = computeTouchOcclusionInfoLocked(window, x, y);
4967 if (!isTouchTrustedLocked(occlusionInfo)) {
4968 if (DEBUG_TOUCH_OCCLUSION) {
Prabir Pradhan82e081e2022-12-06 09:50:09 +00004969 ALOGD("Stack of obscuring windows during untrusted touch (%.1f, %.1f):", x, y);
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004970 for (const auto& log : occlusionInfo.debugInfo) {
4971 ALOGD("%s", log.c_str());
4972 }
4973 }
4974 ALOGW("Dropping untrusted touch event due to %s/%d", occlusionInfo.obscuringPackage.c_str(),
4975 occlusionInfo.obscuringUid);
4976 return false;
4977 }
4978
4979 // Drop touch events if requested by input feature
4980 if (shouldDropInput(motionEntry, window)) {
4981 return false;
4982 }
4983
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004984 return true;
4985}
4986
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004987std::shared_ptr<InputChannel> InputDispatcher::getInputChannelLocked(
4988 const sp<IBinder>& token) const {
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00004989 auto connectionIt = mConnectionsByToken.find(token);
4990 if (connectionIt == mConnectionsByToken.end()) {
Robert Carr5c8a0262018-10-03 16:30:44 -07004991 return nullptr;
4992 }
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00004993 return connectionIt->second->inputChannel;
Robert Carr5c8a0262018-10-03 16:30:44 -07004994}
4995
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004996void InputDispatcher::updateWindowHandlesForDisplayLocked(
chaviw98318de2021-05-19 16:45:23 -05004997 const std::vector<sp<WindowInfoHandle>>& windowInfoHandles, int32_t displayId) {
4998 if (windowInfoHandles.empty()) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004999 // Remove all handles on a display if there are no windows left.
5000 mWindowHandlesByDisplay.erase(displayId);
5001 return;
5002 }
5003
5004 // Since we compare the pointer of input window handles across window updates, we need
5005 // to make sure the handle object for the same window stays unchanged across updates.
chaviw98318de2021-05-19 16:45:23 -05005006 const std::vector<sp<WindowInfoHandle>>& oldHandles = getWindowHandlesLocked(displayId);
5007 std::unordered_map<int32_t /*id*/, sp<WindowInfoHandle>> oldHandlesById;
5008 for (const sp<WindowInfoHandle>& handle : oldHandles) {
chaviwaf87b3e2019-10-01 16:59:28 -07005009 oldHandlesById[handle->getId()] = handle;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005010 }
5011
chaviw98318de2021-05-19 16:45:23 -05005012 std::vector<sp<WindowInfoHandle>> newHandles;
5013 for (const sp<WindowInfoHandle>& handle : windowInfoHandles) {
chaviw98318de2021-05-19 16:45:23 -05005014 const WindowInfo* info = handle->getInfo();
Siarhei Vishniakou64452932020-11-06 17:51:32 -06005015 if (getInputChannelLocked(handle->getToken()) == nullptr) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005016 const bool noInputChannel =
Prabir Pradhan51e7db02022-02-07 06:02:57 -08005017 info->inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005018 const bool canReceiveInput =
5019 !info->inputConfig.test(WindowInfo::InputConfig::NOT_TOUCHABLE) ||
5020 !info->inputConfig.test(WindowInfo::InputConfig::NOT_FOCUSABLE);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005021 if (canReceiveInput && !noInputChannel) {
John Recke0710582019-09-26 13:46:12 -07005022 ALOGV("Window handle %s has no registered input channel",
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005023 handle->getName().c_str());
Robert Carr2984b7a2020-04-13 17:06:45 -07005024 continue;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005025 }
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005026 }
5027
5028 if (info->displayId != displayId) {
5029 ALOGE("Window %s updated by wrong display %d, should belong to display %d",
5030 handle->getName().c_str(), displayId, info->displayId);
5031 continue;
5032 }
5033
Robert Carredd13602020-04-13 17:24:34 -07005034 if ((oldHandlesById.find(handle->getId()) != oldHandlesById.end()) &&
5035 (oldHandlesById.at(handle->getId())->getToken() == handle->getToken())) {
chaviw98318de2021-05-19 16:45:23 -05005036 const sp<WindowInfoHandle>& oldHandle = oldHandlesById.at(handle->getId());
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005037 oldHandle->updateFrom(handle);
5038 newHandles.push_back(oldHandle);
5039 } else {
5040 newHandles.push_back(handle);
5041 }
5042 }
5043
5044 // Insert or replace
5045 mWindowHandlesByDisplay[displayId] = newHandles;
5046}
5047
Arthur Hung72d8dc32020-03-28 00:48:39 +00005048void InputDispatcher::setInputWindows(
chaviw98318de2021-05-19 16:45:23 -05005049 const std::unordered_map<int32_t, std::vector<sp<WindowInfoHandle>>>& handlesPerDisplay) {
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005050 // TODO(b/198444055): Remove setInputWindows from InputDispatcher.
Arthur Hung72d8dc32020-03-28 00:48:39 +00005051 { // acquire lock
5052 std::scoped_lock _l(mLock);
Siarhei Vishniakou2508b872020-12-03 16:33:53 -10005053 for (const auto& [displayId, handles] : handlesPerDisplay) {
5054 setInputWindowsLocked(handles, displayId);
Arthur Hung72d8dc32020-03-28 00:48:39 +00005055 }
5056 }
5057 // Wake up poll loop since it may need to make new input dispatching choices.
5058 mLooper->wake();
5059}
5060
Arthur Hungb92218b2018-08-14 12:00:21 +08005061/**
5062 * Called from InputManagerService, update window handle list by displayId that can receive input.
5063 * A window handle contains information about InputChannel, Touch Region, Types, Focused,...
5064 * If set an empty list, remove all handles from the specific display.
5065 * For focused handle, check if need to change and send a cancel event to previous one.
5066 * For removed handle, check if need to send a cancel event if already in touch.
5067 */
Arthur Hung72d8dc32020-03-28 00:48:39 +00005068void InputDispatcher::setInputWindowsLocked(
chaviw98318de2021-05-19 16:45:23 -05005069 const std::vector<sp<WindowInfoHandle>>& windowInfoHandles, int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005070 if (DEBUG_FOCUS) {
5071 std::string windowList;
chaviw98318de2021-05-19 16:45:23 -05005072 for (const sp<WindowInfoHandle>& iwh : windowInfoHandles) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005073 windowList += iwh->getName() + " ";
5074 }
5075 ALOGD("setInputWindows displayId=%" PRId32 " %s", displayId, windowList.c_str());
5076 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005077
Prabir Pradhand65552b2021-10-07 11:23:50 -07005078 // Check preconditions for new input windows
chaviw98318de2021-05-19 16:45:23 -05005079 for (const sp<WindowInfoHandle>& window : windowInfoHandles) {
Prabir Pradhand65552b2021-10-07 11:23:50 -07005080 const WindowInfo& info = *window->getInfo();
5081
5082 // Ensure all tokens are null if the window has feature NO_INPUT_CHANNEL
Prabir Pradhan51e7db02022-02-07 06:02:57 -08005083 const bool noInputWindow = info.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005084 if (noInputWindow && window->getToken() != nullptr) {
5085 ALOGE("%s has feature NO_INPUT_WINDOW, but a non-null token. Clearing",
5086 window->getName().c_str());
5087 window->releaseChannel();
5088 }
Prabir Pradhand65552b2021-10-07 11:23:50 -07005089
Prabir Pradhan5c85e052021-12-22 02:27:12 -08005090 // Ensure all spy windows are trusted overlays
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005091 LOG_ALWAYS_FATAL_IF(info.isSpy() &&
5092 !info.inputConfig.test(
5093 WindowInfo::InputConfig::TRUSTED_OVERLAY),
Prabir Pradhan5c85e052021-12-22 02:27:12 -08005094 "%s has feature SPY, but is not a trusted overlay.",
5095 window->getName().c_str());
5096
Prabir Pradhand65552b2021-10-07 11:23:50 -07005097 // Ensure all stylus interceptors are trusted overlays
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005098 LOG_ALWAYS_FATAL_IF(info.interceptsStylus() &&
5099 !info.inputConfig.test(
5100 WindowInfo::InputConfig::TRUSTED_OVERLAY),
Prabir Pradhand65552b2021-10-07 11:23:50 -07005101 "%s has feature INTERCEPTS_STYLUS, but is not a trusted overlay.",
5102 window->getName().c_str());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005103 }
5104
Arthur Hung72d8dc32020-03-28 00:48:39 +00005105 // Copy old handles for release if they are no longer present.
chaviw98318de2021-05-19 16:45:23 -05005106 const std::vector<sp<WindowInfoHandle>> oldWindowHandles = getWindowHandlesLocked(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005107
Prabir Pradhan93a0f912021-04-21 13:47:42 -07005108 // Save the old windows' orientation by ID before it gets updated.
5109 std::unordered_map<int32_t, uint32_t> oldWindowOrientations;
chaviw98318de2021-05-19 16:45:23 -05005110 for (const sp<WindowInfoHandle>& handle : oldWindowHandles) {
Prabir Pradhan93a0f912021-04-21 13:47:42 -07005111 oldWindowOrientations.emplace(handle->getId(),
5112 handle->getInfo()->transform.getOrientation());
5113 }
5114
chaviw98318de2021-05-19 16:45:23 -05005115 updateWindowHandlesForDisplayLocked(windowInfoHandles, displayId);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005116
chaviw98318de2021-05-19 16:45:23 -05005117 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Arthur Hung72d8dc32020-03-28 00:48:39 +00005118
Vishnu Nairc519ff72021-01-21 08:23:08 -08005119 std::optional<FocusResolver::FocusChanges> changes =
5120 mFocusResolver.setInputWindows(displayId, windowHandles);
5121 if (changes) {
5122 onFocusChangedLocked(*changes);
Arthur Hung72d8dc32020-03-28 00:48:39 +00005123 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005124
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005125 std::unordered_map<int32_t, TouchState>::iterator stateIt =
5126 mTouchStatesByDisplay.find(displayId);
5127 if (stateIt != mTouchStatesByDisplay.end()) {
5128 TouchState& state = stateIt->second;
Arthur Hung72d8dc32020-03-28 00:48:39 +00005129 for (size_t i = 0; i < state.windows.size();) {
5130 TouchedWindow& touchedWindow = state.windows[i];
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07005131 if (getWindowHandleLocked(touchedWindow.windowHandle) == nullptr) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005132 if (DEBUG_FOCUS) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00005133 ALOGD("Touched window was removed: %s in display %" PRId32,
5134 touchedWindow.windowHandle->getName().c_str(), displayId);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005135 }
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005136 std::shared_ptr<InputChannel> touchedInputChannel =
Arthur Hung72d8dc32020-03-28 00:48:39 +00005137 getInputChannelLocked(touchedWindow.windowHandle->getToken());
5138 if (touchedInputChannel != nullptr) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00005139 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
Arthur Hung72d8dc32020-03-28 00:48:39 +00005140 "touched window was removed");
5141 synthesizeCancelationEventsForInputChannelLocked(touchedInputChannel, options);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00005142 // Since we are about to drop the touch, cancel the events for the wallpaper as
5143 // well.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005144 if (touchedWindow.targetFlags.test(InputTarget::Flags::FOREGROUND) &&
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005145 touchedWindow.windowHandle->getInfo()->inputConfig.test(
5146 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER)) {
Siarhei Vishniakouca205502021-07-16 21:31:58 +00005147 sp<WindowInfoHandle> wallpaper = state.getWallpaperWindow();
Arthur Hungc539dbb2022-12-08 07:45:36 +00005148 synthesizeCancelationEventsForWindowLocked(wallpaper, options);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00005149 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005150 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00005151 state.windows.erase(state.windows.begin() + i);
5152 } else {
5153 ++i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005154 }
5155 }
arthurhungb89ccb02020-12-30 16:19:01 +08005156
arthurhung6d4bed92021-03-17 11:59:33 +08005157 // If drag window is gone, it would receive a cancel event and broadcast the DRAG_END. We
arthurhungb89ccb02020-12-30 16:19:01 +08005158 // could just clear the state here.
Arthur Hung3915c1f2022-05-31 07:17:17 +00005159 if (mDragState && mDragState->dragWindow->getInfo()->displayId == displayId &&
arthurhung6d4bed92021-03-17 11:59:33 +08005160 std::find(windowHandles.begin(), windowHandles.end(), mDragState->dragWindow) ==
arthurhungb89ccb02020-12-30 16:19:01 +08005161 windowHandles.end()) {
Arthur Hung3915c1f2022-05-31 07:17:17 +00005162 ALOGI("Drag window went away: %s", mDragState->dragWindow->getName().c_str());
5163 sendDropWindowCommandLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08005164 mDragState.reset();
arthurhungb89ccb02020-12-30 16:19:01 +08005165 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00005166 }
Arthur Hung25e2af12020-03-26 12:58:37 +00005167
Prabir Pradhan8b89c2f2021-07-29 16:30:14 +00005168 // Determine if the orientation of any of the input windows have changed, and cancel all
5169 // pointer events if necessary.
5170 for (const sp<WindowInfoHandle>& oldWindowHandle : oldWindowHandles) {
5171 const sp<WindowInfoHandle> newWindowHandle = getWindowHandleLocked(oldWindowHandle);
5172 if (newWindowHandle != nullptr &&
5173 newWindowHandle->getInfo()->transform.getOrientation() !=
5174 oldWindowOrientations[oldWindowHandle->getId()]) {
5175 std::shared_ptr<InputChannel> inputChannel =
5176 getInputChannelLocked(newWindowHandle->getToken());
5177 if (inputChannel != nullptr) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00005178 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
Prabir Pradhan8b89c2f2021-07-29 16:30:14 +00005179 "touched window's orientation changed");
5180 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
Prabir Pradhan93a0f912021-04-21 13:47:42 -07005181 }
5182 }
5183 }
5184
Arthur Hung72d8dc32020-03-28 00:48:39 +00005185 // Release information for windows that are no longer present.
5186 // This ensures that unused input channels are released promptly.
5187 // Otherwise, they might stick around until the window handle is destroyed
5188 // which might not happen until the next GC.
chaviw98318de2021-05-19 16:45:23 -05005189 for (const sp<WindowInfoHandle>& oldWindowHandle : oldWindowHandles) {
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07005190 if (getWindowHandleLocked(oldWindowHandle) == nullptr) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00005191 if (DEBUG_FOCUS) {
5192 ALOGD("Window went away: %s", oldWindowHandle->getName().c_str());
Arthur Hung25e2af12020-03-26 12:58:37 +00005193 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00005194 oldWindowHandle->releaseChannel();
Arthur Hung25e2af12020-03-26 12:58:37 +00005195 }
chaviw291d88a2019-02-14 10:33:58 -08005196 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005197}
5198
5199void InputDispatcher::setFocusedApplication(
Chris Yea209fde2020-07-22 13:54:51 -07005200 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005201 if (DEBUG_FOCUS) {
5202 ALOGD("setFocusedApplication displayId=%" PRId32 " %s", displayId,
5203 inputApplicationHandle ? inputApplicationHandle->getName().c_str() : "<nullptr>");
5204 }
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05005205 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005206 std::scoped_lock _l(mLock);
Vishnu Nair599f1412021-06-21 10:39:58 -07005207 setFocusedApplicationLocked(displayId, inputApplicationHandle);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005208 } // release lock
5209
5210 // Wake up poll loop since it may need to make new input dispatching choices.
5211 mLooper->wake();
5212}
5213
Vishnu Nair599f1412021-06-21 10:39:58 -07005214void InputDispatcher::setFocusedApplicationLocked(
5215 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
5216 std::shared_ptr<InputApplicationHandle> oldFocusedApplicationHandle =
5217 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
5218
5219 if (sharedPointersEqual(oldFocusedApplicationHandle, inputApplicationHandle)) {
5220 return; // This application is already focused. No need to wake up or change anything.
5221 }
5222
5223 // Set the new application handle.
5224 if (inputApplicationHandle != nullptr) {
5225 mFocusedApplicationHandlesByDisplay[displayId] = inputApplicationHandle;
5226 } else {
5227 mFocusedApplicationHandlesByDisplay.erase(displayId);
5228 }
5229
5230 // No matter what the old focused application was, stop waiting on it because it is
5231 // no longer focused.
5232 resetNoFocusedWindowTimeoutLocked();
5233}
5234
Tiger Huang721e26f2018-07-24 22:26:19 +08005235/**
5236 * Sets the focused display, which is responsible for receiving focus-dispatched input events where
5237 * the display not specified.
5238 *
5239 * We track any unreleased events for each window. If a window loses the ability to receive the
5240 * released event, we will send a cancel event to it. So when the focused display is changed, we
5241 * cancel all the unreleased display-unspecified events for the focused window on the old focused
5242 * display. The display-specified events won't be affected.
5243 */
5244void InputDispatcher::setFocusedDisplay(int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005245 if (DEBUG_FOCUS) {
5246 ALOGD("setFocusedDisplay displayId=%" PRId32, displayId);
5247 }
Tiger Huang721e26f2018-07-24 22:26:19 +08005248 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005249 std::scoped_lock _l(mLock);
Tiger Huang721e26f2018-07-24 22:26:19 +08005250
5251 if (mFocusedDisplayId != displayId) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07005252 sp<IBinder> oldFocusedWindowToken =
Vishnu Nairc519ff72021-01-21 08:23:08 -08005253 mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07005254 if (oldFocusedWindowToken != nullptr) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005255 std::shared_ptr<InputChannel> inputChannel =
Vishnu Nairad321cd2020-08-20 16:40:21 -07005256 getInputChannelLocked(oldFocusedWindowToken);
Tiger Huang721e26f2018-07-24 22:26:19 +08005257 if (inputChannel != nullptr) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005258 CancelationOptions
Michael Wrightfb04fd52022-11-24 22:31:11 +00005259 options(CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005260 "The display which contains this window no longer has focus.");
Michael Wright3dd60e22019-03-27 22:06:44 +00005261 options.displayId = ADISPLAY_ID_NONE;
Tiger Huang721e26f2018-07-24 22:26:19 +08005262 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
5263 }
5264 }
5265 mFocusedDisplayId = displayId;
5266
Chris Ye3c2d6f52020-08-09 10:39:48 -07005267 // Find new focused window and validate
Vishnu Nairc519ff72021-01-21 08:23:08 -08005268 sp<IBinder> newFocusedWindowToken = mFocusResolver.getFocusedWindowToken(displayId);
Prabir Pradhancef936d2021-07-21 16:17:52 +00005269 sendFocusChangedCommandLocked(oldFocusedWindowToken, newFocusedWindowToken);
Robert Carrf759f162018-11-13 12:57:11 -08005270
Vishnu Nairad321cd2020-08-20 16:40:21 -07005271 if (newFocusedWindowToken == nullptr) {
Tiger Huang721e26f2018-07-24 22:26:19 +08005272 ALOGW("Focused display #%" PRId32 " does not have a focused window.", displayId);
Vishnu Nairc519ff72021-01-21 08:23:08 -08005273 if (mFocusResolver.hasFocusedWindowTokens()) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07005274 ALOGE("But another display has a focused window\n%s",
Vishnu Nairc519ff72021-01-21 08:23:08 -08005275 mFocusResolver.dumpFocusedWindows().c_str());
Tiger Huang721e26f2018-07-24 22:26:19 +08005276 }
5277 }
5278 }
Tiger Huang721e26f2018-07-24 22:26:19 +08005279 } // release lock
5280
5281 // Wake up poll loop since it may need to make new input dispatching choices.
5282 mLooper->wake();
5283}
5284
Michael Wrightd02c5b62014-02-10 15:10:22 -08005285void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005286 if (DEBUG_FOCUS) {
5287 ALOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
5288 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005289
5290 bool changed;
5291 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005292 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005293
5294 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
5295 if (mDispatchFrozen && !frozen) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005296 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005297 }
5298
5299 if (mDispatchEnabled && !enabled) {
5300 resetAndDropEverythingLocked("dispatcher is being disabled");
5301 }
5302
5303 mDispatchEnabled = enabled;
5304 mDispatchFrozen = frozen;
5305 changed = true;
5306 } else {
5307 changed = false;
5308 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005309 } // release lock
5310
5311 if (changed) {
5312 // Wake up poll loop since it may need to make new input dispatching choices.
5313 mLooper->wake();
5314 }
5315}
5316
5317void InputDispatcher::setInputFilterEnabled(bool enabled) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005318 if (DEBUG_FOCUS) {
5319 ALOGD("setInputFilterEnabled: enabled=%d", enabled);
5320 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005321
5322 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005323 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005324
5325 if (mInputFilterEnabled == enabled) {
5326 return;
5327 }
5328
5329 mInputFilterEnabled = enabled;
5330 resetAndDropEverythingLocked("input filter is being enabled or disabled");
5331 } // release lock
5332
5333 // Wake up poll loop since there might be work to do to drop everything.
5334 mLooper->wake();
5335}
5336
Antonio Kanteka042c022022-07-06 16:51:07 -07005337bool InputDispatcher::setInTouchMode(bool inTouchMode, int32_t pid, int32_t uid, bool hasPermission,
5338 int32_t displayId) {
Antonio Kantekf16f2832021-09-28 04:39:20 +00005339 bool needWake = false;
5340 {
5341 std::scoped_lock lock(mLock);
Antonio Kantek15beb512022-06-13 22:35:41 +00005342 ALOGD_IF(DEBUG_TOUCH_MODE,
5343 "Request to change touch mode to %s (calling pid=%d, uid=%d, "
5344 "hasPermission=%s, target displayId=%d, mTouchModePerDisplay[displayId]=%s)",
5345 toString(inTouchMode), pid, uid, toString(hasPermission), displayId,
5346 mTouchModePerDisplay.count(displayId) == 0
5347 ? "not set"
5348 : std::to_string(mTouchModePerDisplay[displayId]).c_str());
5349
Antonio Kantek15beb512022-06-13 22:35:41 +00005350 auto touchModeIt = mTouchModePerDisplay.find(displayId);
5351 if (touchModeIt != mTouchModePerDisplay.end() && touchModeIt->second == inTouchMode) {
Antonio Kantekea47acb2021-12-23 12:41:25 -08005352 return false;
Antonio Kantekf16f2832021-09-28 04:39:20 +00005353 }
Antonio Kantekea47acb2021-12-23 12:41:25 -08005354 if (!hasPermission) {
Antonio Kantek48710e42022-03-24 14:19:30 -07005355 if (!focusedWindowIsOwnedByLocked(pid, uid) &&
5356 !recentWindowsAreOwnedByLocked(pid, uid)) {
5357 ALOGD("Touch mode switch rejected, caller (pid=%d, uid=%d) doesn't own the focused "
5358 "window nor none of the previously interacted window",
5359 pid, uid);
Antonio Kantekea47acb2021-12-23 12:41:25 -08005360 return false;
5361 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00005362 }
Antonio Kantek15beb512022-06-13 22:35:41 +00005363 mTouchModePerDisplay[displayId] = inTouchMode;
5364 auto entry = std::make_unique<TouchModeEntry>(mIdGenerator.nextId(), now(), inTouchMode,
5365 displayId);
Antonio Kantekf16f2832021-09-28 04:39:20 +00005366 needWake = enqueueInboundEventLocked(std::move(entry));
5367 } // release lock
5368
5369 if (needWake) {
5370 mLooper->wake();
5371 }
Antonio Kantekea47acb2021-12-23 12:41:25 -08005372 return true;
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -08005373}
5374
Antonio Kantek48710e42022-03-24 14:19:30 -07005375bool InputDispatcher::focusedWindowIsOwnedByLocked(int32_t pid, int32_t uid) {
5376 const sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
5377 if (focusedToken == nullptr) {
5378 return false;
5379 }
5380 sp<WindowInfoHandle> windowHandle = getWindowHandleLocked(focusedToken);
5381 return isWindowOwnedBy(windowHandle, pid, uid);
5382}
5383
5384bool InputDispatcher::recentWindowsAreOwnedByLocked(int32_t pid, int32_t uid) {
5385 return std::find_if(mInteractionConnectionTokens.begin(), mInteractionConnectionTokens.end(),
5386 [&](const sp<IBinder>& connectionToken) REQUIRES(mLock) {
5387 const sp<WindowInfoHandle> windowHandle =
5388 getWindowHandleLocked(connectionToken);
5389 return isWindowOwnedBy(windowHandle, pid, uid);
5390 }) != mInteractionConnectionTokens.end();
5391}
5392
Bernardo Rufinoea97d182020-08-19 14:43:14 +01005393void InputDispatcher::setMaximumObscuringOpacityForTouch(float opacity) {
5394 if (opacity < 0 || opacity > 1) {
5395 LOG_ALWAYS_FATAL("Maximum obscuring opacity for touch should be >= 0 and <= 1");
5396 return;
5397 }
5398
5399 std::scoped_lock lock(mLock);
5400 mMaximumObscuringOpacityForTouch = opacity;
5401}
5402
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005403std::tuple<TouchState*, TouchedWindow*, int32_t /*displayId*/>
5404InputDispatcher::findTouchStateWindowAndDisplayLocked(const sp<IBinder>& token) {
Arthur Hungabbb9d82021-09-01 14:52:30 +00005405 for (auto& [displayId, state] : mTouchStatesByDisplay) {
5406 for (TouchedWindow& w : state.windows) {
5407 if (w.windowHandle->getToken() == token) {
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005408 return std::make_tuple(&state, &w, displayId);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005409 }
5410 }
5411 }
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005412 return std::make_tuple(nullptr, nullptr, ADISPLAY_ID_DEFAULT);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005413}
5414
arthurhungb89ccb02020-12-30 16:19:01 +08005415bool InputDispatcher::transferTouchFocus(const sp<IBinder>& fromToken, const sp<IBinder>& toToken,
5416 bool isDragDrop) {
chaviwfbe5d9c2018-12-26 12:23:37 -08005417 if (fromToken == toToken) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005418 if (DEBUG_FOCUS) {
5419 ALOGD("Trivial transfer to same window.");
5420 }
chaviwfbe5d9c2018-12-26 12:23:37 -08005421 return true;
5422 }
5423
Michael Wrightd02c5b62014-02-10 15:10:22 -08005424 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005425 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005426
Arthur Hungabbb9d82021-09-01 14:52:30 +00005427 // Find the target touch state and touched window by fromToken.
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005428 auto [state, touchedWindow, displayId] = findTouchStateWindowAndDisplayLocked(fromToken);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005429 if (state == nullptr || touchedWindow == nullptr) {
5430 ALOGD("Focus transfer failed because from window is not being touched.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005431 return false;
5432 }
Arthur Hungabbb9d82021-09-01 14:52:30 +00005433
Arthur Hungabbb9d82021-09-01 14:52:30 +00005434 sp<WindowInfoHandle> toWindowHandle = getWindowHandleLocked(toToken, displayId);
5435 if (toWindowHandle == nullptr) {
5436 ALOGW("Cannot transfer focus because to window not found.");
5437 return false;
5438 }
5439
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005440 if (DEBUG_FOCUS) {
5441 ALOGD("transferTouchFocus: fromWindowHandle=%s, toWindowHandle=%s",
Arthur Hungabbb9d82021-09-01 14:52:30 +00005442 touchedWindow->windowHandle->getName().c_str(),
5443 toWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005444 }
5445
Arthur Hungabbb9d82021-09-01 14:52:30 +00005446 // Erase old window.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005447 ftl::Flags<InputTarget::Flags> oldTargetFlags = touchedWindow->targetFlags;
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08005448 std::bitset<MAX_POINTER_ID + 1> pointerIds = touchedWindow->pointerIds;
Arthur Hungc539dbb2022-12-08 07:45:36 +00005449 sp<WindowInfoHandle> fromWindowHandle = touchedWindow->windowHandle;
Arthur Hungabbb9d82021-09-01 14:52:30 +00005450 state->removeWindowByToken(fromToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005451
Arthur Hungabbb9d82021-09-01 14:52:30 +00005452 // Add new window.
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00005453 nsecs_t downTimeInTarget = now();
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005454 ftl::Flags<InputTarget::Flags> newTargetFlags =
5455 oldTargetFlags & (InputTarget::Flags::SPLIT | InputTarget::Flags::DISPATCH_AS_IS);
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00005456 if (canReceiveForegroundTouches(*toWindowHandle->getInfo())) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005457 newTargetFlags |= InputTarget::Flags::FOREGROUND;
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00005458 }
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00005459 state->addOrUpdateWindow(toWindowHandle, newTargetFlags, pointerIds, downTimeInTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005460
Arthur Hungabbb9d82021-09-01 14:52:30 +00005461 // Store the dragging window.
5462 if (isDragDrop) {
Arthur Hungb75c2aa2022-07-15 09:35:36 +00005463 if (pointerIds.count() != 1) {
5464 ALOGW("The drag and drop cannot be started when there is no pointer or more than 1"
5465 " pointer on the window.");
Arthur Hung54745652022-04-20 07:17:41 +00005466 return false;
5467 }
Arthur Hungb75c2aa2022-07-15 09:35:36 +00005468 // Track the pointer id for drag window and generate the drag state.
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08005469 const size_t id = firstMarkedBit(pointerIds);
Arthur Hung54745652022-04-20 07:17:41 +00005470 mDragState = std::make_unique<DragState>(toWindowHandle, id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005471 }
5472
Arthur Hungabbb9d82021-09-01 14:52:30 +00005473 // Synthesize cancel for old window and down for new window.
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07005474 std::shared_ptr<Connection> fromConnection = getConnectionLocked(fromToken);
5475 std::shared_ptr<Connection> toConnection = getConnectionLocked(toToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005476 if (fromConnection != nullptr && toConnection != nullptr) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08005477 fromConnection->inputState.mergePointerStateTo(toConnection->inputState);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005478 CancelationOptions
Michael Wrightfb04fd52022-11-24 22:31:11 +00005479 options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005480 "transferring touch focus from this window to another window");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005481 synthesizeCancelationEventsForConnectionLocked(fromConnection, options);
Arthur Hungc539dbb2022-12-08 07:45:36 +00005482 synthesizePointerDownEventsForConnectionLocked(downTimeInTarget, toConnection,
5483 newTargetFlags);
5484
5485 // Check if the wallpaper window should deliver the corresponding event.
5486 transferWallpaperTouch(oldTargetFlags, newTargetFlags, fromWindowHandle, toWindowHandle,
5487 *state, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005488 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005489 } // release lock
5490
5491 // Wake up poll loop since it may need to make new input dispatching choices.
5492 mLooper->wake();
5493 return true;
5494}
5495
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005496/**
5497 * Get the touched foreground window on the given display.
5498 * Return null if there are no windows touched on that display, or if more than one foreground
5499 * window is being touched.
5500 */
5501sp<WindowInfoHandle> InputDispatcher::findTouchedForegroundWindowLocked(int32_t displayId) const {
5502 auto stateIt = mTouchStatesByDisplay.find(displayId);
5503 if (stateIt == mTouchStatesByDisplay.end()) {
5504 ALOGI("No touch state on display %" PRId32, displayId);
5505 return nullptr;
5506 }
5507
5508 const TouchState& state = stateIt->second;
5509 sp<WindowInfoHandle> touchedForegroundWindow;
5510 // If multiple foreground windows are touched, return nullptr
5511 for (const TouchedWindow& window : state.windows) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005512 if (window.targetFlags.test(InputTarget::Flags::FOREGROUND)) {
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005513 if (touchedForegroundWindow != nullptr) {
5514 ALOGI("Two or more foreground windows: %s and %s",
5515 touchedForegroundWindow->getName().c_str(),
5516 window.windowHandle->getName().c_str());
5517 return nullptr;
5518 }
5519 touchedForegroundWindow = window.windowHandle;
5520 }
5521 }
5522 return touchedForegroundWindow;
5523}
5524
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005525// Binder call
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005526bool InputDispatcher::transferTouch(const sp<IBinder>& destChannelToken, int32_t displayId) {
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005527 sp<IBinder> fromToken;
5528 { // acquire lock
5529 std::scoped_lock _l(mLock);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005530 sp<WindowInfoHandle> toWindowHandle = getWindowHandleLocked(destChannelToken, displayId);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005531 if (toWindowHandle == nullptr) {
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005532 ALOGW("Could not find window associated with token=%p on display %" PRId32,
5533 destChannelToken.get(), displayId);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005534 return false;
5535 }
5536
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005537 sp<WindowInfoHandle> from = findTouchedForegroundWindowLocked(displayId);
5538 if (from == nullptr) {
5539 ALOGE("Could not find a source window in %s for %p", __func__, destChannelToken.get());
5540 return false;
5541 }
5542
5543 fromToken = from->getToken();
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005544 } // release lock
5545
5546 return transferTouchFocus(fromToken, destChannelToken);
5547}
5548
Michael Wrightd02c5b62014-02-10 15:10:22 -08005549void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005550 if (DEBUG_FOCUS) {
5551 ALOGD("Resetting and dropping all events (%s).", reason);
5552 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005553
Michael Wrightfb04fd52022-11-24 22:31:11 +00005554 CancelationOptions options(CancelationOptions::Mode::CANCEL_ALL_EVENTS, reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005555 synthesizeCancelationEventsForAllConnectionsLocked(options);
5556
5557 resetKeyRepeatLocked();
5558 releasePendingEventLocked();
5559 drainInboundQueueLocked();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005560 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005561
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005562 mAnrTracker.clear();
Jeff Brownf086ddb2014-02-11 14:28:48 -08005563 mTouchStatesByDisplay.clear();
Michael Wright78f24442014-08-06 15:55:28 -07005564 mReplacedKeys.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005565}
5566
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005567void InputDispatcher::logDispatchStateLocked() const {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005568 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005569 dumpDispatchStateLocked(dump);
5570
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005571 std::istringstream stream(dump);
5572 std::string line;
5573
5574 while (std::getline(stream, line, '\n')) {
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07005575 ALOGI("%s", line.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005576 }
5577}
5578
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005579std::string InputDispatcher::dumpPointerCaptureStateLocked() const {
Prabir Pradhan99987712020-11-10 18:43:05 -08005580 std::string dump;
5581
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005582 dump += StringPrintf(INDENT "Pointer Capture Requested: %s\n",
5583 toString(mCurrentPointerCaptureRequest.enable));
Prabir Pradhan99987712020-11-10 18:43:05 -08005584
5585 std::string windowName = "None";
5586 if (mWindowTokenWithPointerCapture) {
chaviw98318de2021-05-19 16:45:23 -05005587 const sp<WindowInfoHandle> captureWindowHandle =
Prabir Pradhan99987712020-11-10 18:43:05 -08005588 getWindowHandleLocked(mWindowTokenWithPointerCapture);
5589 windowName = captureWindowHandle ? captureWindowHandle->getName().c_str()
5590 : "token has capture without window";
5591 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005592 dump += StringPrintf(INDENT "Current Window with Pointer Capture: %s\n", windowName.c_str());
Prabir Pradhan99987712020-11-10 18:43:05 -08005593
5594 return dump;
5595}
5596
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005597void InputDispatcher::dumpDispatchStateLocked(std::string& dump) const {
Siarhei Vishniakou043a3ec2019-05-01 11:30:46 -07005598 dump += StringPrintf(INDENT "DispatchEnabled: %s\n", toString(mDispatchEnabled));
5599 dump += StringPrintf(INDENT "DispatchFrozen: %s\n", toString(mDispatchFrozen));
5600 dump += StringPrintf(INDENT "InputFilterEnabled: %s\n", toString(mInputFilterEnabled));
Tiger Huang721e26f2018-07-24 22:26:19 +08005601 dump += StringPrintf(INDENT "FocusedDisplayId: %" PRId32 "\n", mFocusedDisplayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005602
Tiger Huang721e26f2018-07-24 22:26:19 +08005603 if (!mFocusedApplicationHandlesByDisplay.empty()) {
5604 dump += StringPrintf(INDENT "FocusedApplications:\n");
5605 for (auto& it : mFocusedApplicationHandlesByDisplay) {
5606 const int32_t displayId = it.first;
Chris Yea209fde2020-07-22 13:54:51 -07005607 const std::shared_ptr<InputApplicationHandle>& applicationHandle = it.second;
Siarhei Vishniakou70622952020-07-30 11:17:23 -05005608 const std::chrono::duration timeout =
5609 applicationHandle->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005610 dump += StringPrintf(INDENT2 "displayId=%" PRId32
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005611 ", name='%s', dispatchingTimeout=%" PRId64 "ms\n",
Siarhei Vishniakou70622952020-07-30 11:17:23 -05005612 displayId, applicationHandle->getName().c_str(), millis(timeout));
Tiger Huang721e26f2018-07-24 22:26:19 +08005613 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005614 } else {
Tiger Huang721e26f2018-07-24 22:26:19 +08005615 dump += StringPrintf(INDENT "FocusedApplications: <none>\n");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005616 }
Tiger Huang721e26f2018-07-24 22:26:19 +08005617
Vishnu Nairc519ff72021-01-21 08:23:08 -08005618 dump += mFocusResolver.dump();
Prabir Pradhan99987712020-11-10 18:43:05 -08005619 dump += dumpPointerCaptureStateLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005620
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005621 if (!mTouchStatesByDisplay.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005622 dump += StringPrintf(INDENT "TouchStatesByDisplay:\n");
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005623 for (const auto& [displayId, state] : mTouchStatesByDisplay) {
Siarhei Vishniakou6e1e9872022-11-08 17:51:35 -08005624 std::string touchStateDump = addLinePrefix(state.dump(), INDENT2);
5625 dump += INDENT2 + std::to_string(displayId) + " : " + touchStateDump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005626 }
5627 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005628 dump += INDENT "TouchStates: <no displays touched>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005629 }
5630
arthurhung6d4bed92021-03-17 11:59:33 +08005631 if (mDragState) {
5632 dump += StringPrintf(INDENT "DragState:\n");
5633 mDragState->dump(dump, INDENT2);
5634 }
5635
Arthur Hungb92218b2018-08-14 12:00:21 +08005636 if (!mWindowHandlesByDisplay.empty()) {
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005637 for (const auto& [displayId, windowHandles] : mWindowHandlesByDisplay) {
5638 dump += StringPrintf(INDENT "Display: %" PRId32 "\n", displayId);
5639 if (const auto& it = mDisplayInfos.find(displayId); it != mDisplayInfos.end()) {
5640 const auto& displayInfo = it->second;
5641 dump += StringPrintf(INDENT2 "logicalSize=%dx%d\n", displayInfo.logicalWidth,
5642 displayInfo.logicalHeight);
5643 displayInfo.transform.dump(dump, "transform", INDENT4);
5644 } else {
5645 dump += INDENT2 "No DisplayInfo found!\n";
5646 }
5647
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08005648 if (!windowHandles.empty()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08005649 dump += INDENT2 "Windows:\n";
5650 for (size_t i = 0; i < windowHandles.size(); i++) {
chaviw98318de2021-05-19 16:45:23 -05005651 const sp<WindowInfoHandle>& windowHandle = windowHandles[i];
5652 const WindowInfo* windowInfo = windowHandle->getInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005653
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00005654 dump += StringPrintf(INDENT3 "%zu: name='%s', id=%" PRId32 ", displayId=%d, "
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005655 "inputConfig=%s, alpha=%.2f, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005656 "frame=[%d,%d][%d,%d], globalScale=%f, "
Bernardo Rufino49d99e42021-01-18 15:16:59 +00005657 "applicationInfo.name=%s, "
5658 "applicationInfo.token=%s, "
chaviw1ff3d1e2020-07-01 15:53:47 -07005659 "touchableRegion=",
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00005660 i, windowInfo->name.c_str(), windowInfo->id,
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005661 windowInfo->displayId,
5662 windowInfo->inputConfig.string().c_str(),
5663 windowInfo->alpha, windowInfo->frameLeft,
5664 windowInfo->frameTop, windowInfo->frameRight,
5665 windowInfo->frameBottom, windowInfo->globalScaleFactor,
Bernardo Rufino49d99e42021-01-18 15:16:59 +00005666 windowInfo->applicationInfo.name.c_str(),
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07005667 binderToString(windowInfo->applicationInfo.token).c_str());
Bernardo Rufino53fc31e2020-11-03 11:01:07 +00005668 dump += dumpRegion(windowInfo->touchableRegion);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005669 dump += StringPrintf(", ownerPid=%d, ownerUid=%d, dispatchingTimeout=%" PRId64
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005670 "ms, hasToken=%s, "
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005671 "touchOcclusionMode=%s\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005672 windowInfo->ownerPid, windowInfo->ownerUid,
Bernardo Rufinoc2f1fad2020-11-04 17:30:57 +00005673 millis(windowInfo->dispatchingTimeout),
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07005674 binderToString(windowInfo->token).c_str(),
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005675 toString(windowInfo->touchOcclusionMode).c_str());
chaviw85b44202020-07-24 11:46:21 -07005676 windowInfo->transform.dump(dump, "transform", INDENT4);
Arthur Hungb92218b2018-08-14 12:00:21 +08005677 }
5678 } else {
5679 dump += INDENT2 "Windows: <none>\n";
5680 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005681 }
5682 } else {
Arthur Hungb92218b2018-08-14 12:00:21 +08005683 dump += INDENT "Displays: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005684 }
5685
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005686 if (!mGlobalMonitorsByDisplay.empty()) {
5687 for (const auto& [displayId, monitors] : mGlobalMonitorsByDisplay) {
5688 dump += StringPrintf(INDENT "Global monitors on display %d:\n", displayId);
Michael Wright3dd60e22019-03-27 22:06:44 +00005689 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005690 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005691 } else {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005692 dump += INDENT "Global Monitors: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005693 }
5694
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005695 const nsecs_t currentTime = now();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005696
5697 // Dump recently dispatched or dropped events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005698 if (!mRecentQueue.empty()) {
5699 dump += StringPrintf(INDENT "RecentQueue: length=%zu\n", mRecentQueue.size());
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005700 for (const std::shared_ptr<EventEntry>& entry : mRecentQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005701 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005702 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005703 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005704 }
5705 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005706 dump += INDENT "RecentQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005707 }
5708
5709 // Dump event currently being dispatched.
5710 if (mPendingEvent) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005711 dump += INDENT "PendingEvent:\n";
5712 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005713 dump += mPendingEvent->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005714 dump += StringPrintf(", age=%" PRId64 "ms\n",
5715 ns2ms(currentTime - mPendingEvent->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005716 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005717 dump += INDENT "PendingEvent: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005718 }
5719
5720 // Dump inbound events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005721 if (!mInboundQueue.empty()) {
5722 dump += StringPrintf(INDENT "InboundQueue: length=%zu\n", mInboundQueue.size());
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005723 for (const std::shared_ptr<EventEntry>& entry : mInboundQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005724 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005725 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005726 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005727 }
5728 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005729 dump += INDENT "InboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005730 }
5731
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005732 if (!mReplacedKeys.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005733 dump += INDENT "ReplacedKeys:\n";
Michael Wright3cec4462022-11-24 22:05:46 +00005734 for (const auto& [replacement, newKeyCode] : mReplacedKeys) {
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005735 dump += StringPrintf(INDENT2 "originalKeyCode=%d, deviceId=%d -> newKeyCode=%d\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005736 replacement.keyCode, replacement.deviceId, newKeyCode);
Michael Wright78f24442014-08-06 15:55:28 -07005737 }
5738 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005739 dump += INDENT "ReplacedKeys: <empty>\n";
Michael Wright78f24442014-08-06 15:55:28 -07005740 }
5741
Prabir Pradhancef936d2021-07-21 16:17:52 +00005742 if (!mCommandQueue.empty()) {
5743 dump += StringPrintf(INDENT "CommandQueue: size=%zu\n", mCommandQueue.size());
5744 } else {
5745 dump += INDENT "CommandQueue: <empty>\n";
5746 }
5747
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005748 if (!mConnectionsByToken.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005749 dump += INDENT "Connections:\n";
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005750 for (const auto& [token, connection] : mConnectionsByToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005751 dump += StringPrintf(INDENT2 "%i: channelName='%s', windowName='%s', "
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005752 "status=%s, monitor=%s, responsive=%s\n",
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005753 connection->inputChannel->getFd().get(),
5754 connection->getInputChannelName().c_str(),
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08005755 connection->getWindowName().c_str(),
5756 ftl::enum_string(connection->status).c_str(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005757 toString(connection->monitor), toString(connection->responsive));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005758
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005759 if (!connection->outboundQueue.empty()) {
5760 dump += StringPrintf(INDENT3 "OutboundQueue: length=%zu\n",
5761 connection->outboundQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005762 dump += dumpQueue(connection->outboundQueue, currentTime);
5763
Michael Wrightd02c5b62014-02-10 15:10:22 -08005764 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005765 dump += INDENT3 "OutboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005766 }
5767
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005768 if (!connection->waitQueue.empty()) {
5769 dump += StringPrintf(INDENT3 "WaitQueue: length=%zu\n",
5770 connection->waitQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005771 dump += dumpQueue(connection->waitQueue, currentTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005772 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005773 dump += INDENT3 "WaitQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005774 }
5775 }
5776 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005777 dump += INDENT "Connections: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005778 }
5779
5780 if (isAppSwitchPendingLocked()) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005781 dump += StringPrintf(INDENT "AppSwitch: pending, due in %" PRId64 "ms\n",
5782 ns2ms(mAppSwitchDueTime - now()));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005783 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005784 dump += INDENT "AppSwitch: not pending\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005785 }
5786
Antonio Kantek15beb512022-06-13 22:35:41 +00005787 if (!mTouchModePerDisplay.empty()) {
5788 dump += INDENT "TouchModePerDisplay:\n";
5789 for (const auto& [displayId, touchMode] : mTouchModePerDisplay) {
5790 dump += StringPrintf(INDENT2 "Display: %" PRId32 " TouchMode: %s\n", displayId,
5791 std::to_string(touchMode).c_str());
5792 }
5793 } else {
5794 dump += INDENT "TouchModePerDisplay: <none>\n";
5795 }
5796
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005797 dump += INDENT "Configuration:\n";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005798 dump += StringPrintf(INDENT2 "KeyRepeatDelay: %" PRId64 "ms\n", ns2ms(mConfig.keyRepeatDelay));
5799 dump += StringPrintf(INDENT2 "KeyRepeatTimeout: %" PRId64 "ms\n",
5800 ns2ms(mConfig.keyRepeatTimeout));
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00005801 dump += mLatencyTracker.dump(INDENT2);
Siarhei Vishniakoua04181f2021-03-26 05:56:49 +00005802 dump += mLatencyAggregator.dump(INDENT2);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005803}
5804
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005805void InputDispatcher::dumpMonitors(std::string& dump, const std::vector<Monitor>& monitors) const {
Michael Wright3dd60e22019-03-27 22:06:44 +00005806 const size_t numMonitors = monitors.size();
5807 for (size_t i = 0; i < numMonitors; i++) {
5808 const Monitor& monitor = monitors[i];
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005809 const std::shared_ptr<InputChannel>& channel = monitor.inputChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005810 dump += StringPrintf(INDENT2 "%zu: '%s', ", i, channel->getName().c_str());
5811 dump += "\n";
5812 }
5813}
5814
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005815class LooperEventCallback : public LooperCallback {
5816public:
5817 LooperEventCallback(std::function<int(int events)> callback) : mCallback(callback) {}
5818 int handleEvent(int /*fd*/, int events, void* /*data*/) override { return mCallback(events); }
5819
5820private:
5821 std::function<int(int events)> mCallback;
5822};
5823
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005824Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputChannel(const std::string& name) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00005825 if (DEBUG_CHANNEL_CREATION) {
5826 ALOGD("channel '%s' ~ createInputChannel", name.c_str());
5827 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005828
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005829 std::unique_ptr<InputChannel> serverChannel;
Garfield Tan15601662020-09-22 15:32:38 -07005830 std::unique_ptr<InputChannel> clientChannel;
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005831 status_t result = InputChannel::openInputChannelPair(name, serverChannel, clientChannel);
Garfield Tan15601662020-09-22 15:32:38 -07005832
5833 if (result) {
5834 return base::Error(result) << "Failed to open input channel pair with name " << name;
5835 }
5836
Michael Wrightd02c5b62014-02-10 15:10:22 -08005837 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005838 std::scoped_lock _l(mLock);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005839 const sp<IBinder>& token = serverChannel->getConnectionToken();
Tomasz Wasilczyk32024602023-11-16 10:17:54 -08005840 auto&& fd = serverChannel->getFd();
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07005841 std::shared_ptr<Connection> connection =
5842 std::make_shared<Connection>(std::move(serverChannel), /*monitor=*/false,
5843 mIdGenerator);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005844
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005845 if (mConnectionsByToken.find(token) != mConnectionsByToken.end()) {
5846 ALOGE("Created a new connection, but the token %p is already known", token.get());
5847 }
5848 mConnectionsByToken.emplace(token, connection);
5849
5850 std::function<int(int events)> callback = std::bind(&InputDispatcher::handleReceiveCallback,
5851 this, std::placeholders::_1, token);
5852
Tomasz Wasilczyk32024602023-11-16 10:17:54 -08005853 mLooper->addFd(fd.get(), 0, ALOOPER_EVENT_INPUT, sp<LooperEventCallback>::make(callback),
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005854 nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005855 } // release lock
5856
5857 // Wake the looper because some connections have changed.
5858 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07005859 return clientChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005860}
5861
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005862Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputMonitor(int32_t displayId,
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005863 const std::string& name,
5864 int32_t pid) {
Garfield Tan15601662020-09-22 15:32:38 -07005865 std::shared_ptr<InputChannel> serverChannel;
5866 std::unique_ptr<InputChannel> clientChannel;
5867 status_t result = openInputChannelPair(name, serverChannel, clientChannel);
5868 if (result) {
5869 return base::Error(result) << "Failed to open input channel pair with name " << name;
5870 }
5871
Michael Wright3dd60e22019-03-27 22:06:44 +00005872 { // acquire lock
5873 std::scoped_lock _l(mLock);
5874
5875 if (displayId < 0) {
Garfield Tan15601662020-09-22 15:32:38 -07005876 return base::Error(BAD_VALUE) << "Attempted to create input monitor with name " << name
5877 << " without a specified display.";
Michael Wright3dd60e22019-03-27 22:06:44 +00005878 }
5879
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07005880 std::shared_ptr<Connection> connection =
5881 std::make_shared<Connection>(serverChannel, /*monitor=*/true, mIdGenerator);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005882 const sp<IBinder>& token = serverChannel->getConnectionToken();
Tomasz Wasilczyk32024602023-11-16 10:17:54 -08005883 auto&& fd = serverChannel->getFd();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005884
5885 if (mConnectionsByToken.find(token) != mConnectionsByToken.end()) {
5886 ALOGE("Created a new connection, but the token %p is already known", token.get());
5887 }
5888 mConnectionsByToken.emplace(token, connection);
5889 std::function<int(int events)> callback = std::bind(&InputDispatcher::handleReceiveCallback,
5890 this, std::placeholders::_1, token);
Michael Wright3dd60e22019-03-27 22:06:44 +00005891
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005892 mGlobalMonitorsByDisplay[displayId].emplace_back(serverChannel, pid);
Michael Wright3dd60e22019-03-27 22:06:44 +00005893
Tomasz Wasilczyk32024602023-11-16 10:17:54 -08005894 mLooper->addFd(fd.get(), 0, ALOOPER_EVENT_INPUT, sp<LooperEventCallback>::make(callback),
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005895 nullptr);
Michael Wright3dd60e22019-03-27 22:06:44 +00005896 }
Garfield Tan15601662020-09-22 15:32:38 -07005897
Michael Wright3dd60e22019-03-27 22:06:44 +00005898 // Wake the looper because some connections have changed.
5899 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07005900 return clientChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005901}
5902
Garfield Tan15601662020-09-22 15:32:38 -07005903status_t InputDispatcher::removeInputChannel(const sp<IBinder>& connectionToken) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005904 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005905 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005906
Harry Cutts33476232023-01-30 19:57:29 +00005907 status_t status = removeInputChannelLocked(connectionToken, /*notify=*/false);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005908 if (status) {
5909 return status;
5910 }
5911 } // release lock
5912
5913 // Wake the poll loop because removing the connection may have changed the current
5914 // synchronization state.
5915 mLooper->wake();
5916 return OK;
5917}
5918
Garfield Tan15601662020-09-22 15:32:38 -07005919status_t InputDispatcher::removeInputChannelLocked(const sp<IBinder>& connectionToken,
5920 bool notify) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07005921 std::shared_ptr<Connection> connection = getConnectionLocked(connectionToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005922 if (connection == nullptr) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005923 // Connection can be removed via socket hang up or an explicit call to 'removeInputChannel'
Michael Wrightd02c5b62014-02-10 15:10:22 -08005924 return BAD_VALUE;
5925 }
5926
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005927 removeConnectionLocked(connection);
Robert Carr5c8a0262018-10-03 16:30:44 -07005928
Michael Wrightd02c5b62014-02-10 15:10:22 -08005929 if (connection->monitor) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005930 removeMonitorChannelLocked(connectionToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005931 }
5932
Tomasz Wasilczyk32024602023-11-16 10:17:54 -08005933 mLooper->removeFd(connection->inputChannel->getFd().get());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005934
5935 nsecs_t currentTime = now();
5936 abortBrokenDispatchCycleLocked(currentTime, connection, notify);
5937
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08005938 connection->status = Connection::Status::ZOMBIE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005939 return OK;
5940}
5941
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005942void InputDispatcher::removeMonitorChannelLocked(const sp<IBinder>& connectionToken) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005943 for (auto it = mGlobalMonitorsByDisplay.begin(); it != mGlobalMonitorsByDisplay.end();) {
5944 auto& [displayId, monitors] = *it;
5945 std::erase_if(monitors, [connectionToken](const Monitor& monitor) {
5946 return monitor.inputChannel->getConnectionToken() == connectionToken;
5947 });
Michael Wright3dd60e22019-03-27 22:06:44 +00005948
Michael Wright3dd60e22019-03-27 22:06:44 +00005949 if (monitors.empty()) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005950 it = mGlobalMonitorsByDisplay.erase(it);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005951 } else {
5952 ++it;
5953 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005954 }
5955}
5956
Michael Wright3dd60e22019-03-27 22:06:44 +00005957status_t InputDispatcher::pilferPointers(const sp<IBinder>& token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005958 std::scoped_lock _l(mLock);
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00005959 return pilferPointersLocked(token);
5960}
Michael Wright3dd60e22019-03-27 22:06:44 +00005961
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00005962status_t InputDispatcher::pilferPointersLocked(const sp<IBinder>& token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005963 const std::shared_ptr<InputChannel> requestingChannel = getInputChannelLocked(token);
5964 if (!requestingChannel) {
5965 ALOGW("Attempted to pilfer pointers from an un-registered channel or invalid token");
5966 return BAD_VALUE;
Michael Wright3dd60e22019-03-27 22:06:44 +00005967 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005968
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005969 auto [statePtr, windowPtr, displayId] = findTouchStateWindowAndDisplayLocked(token);
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08005970 if (statePtr == nullptr || windowPtr == nullptr || windowPtr->pointerIds.none()) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005971 ALOGW("Attempted to pilfer points from a channel without any on-going pointer streams."
5972 " Ignoring.");
5973 return BAD_VALUE;
5974 }
5975
5976 TouchState& state = *statePtr;
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00005977 TouchedWindow& window = *windowPtr;
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005978 // Send cancel events to all the input channels we're stealing from.
Michael Wrightfb04fd52022-11-24 22:31:11 +00005979 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005980 "input channel stole pointer stream");
5981 options.deviceId = state.deviceId;
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005982 options.displayId = displayId;
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07005983 options.pointerIds = window.pointerIds;
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005984 std::string canceledWindows;
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00005985 for (const TouchedWindow& w : state.windows) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005986 const std::shared_ptr<InputChannel> channel =
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00005987 getInputChannelLocked(w.windowHandle->getToken());
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005988 if (channel != nullptr && channel->getConnectionToken() != token) {
5989 synthesizeCancelationEventsForInputChannelLocked(channel, options);
5990 canceledWindows += canceledWindows.empty() ? "[" : ", ";
5991 canceledWindows += channel->getName();
5992 }
5993 }
5994 canceledWindows += canceledWindows.empty() ? "[]" : "]";
5995 ALOGI("Channel %s is stealing touch from %s", requestingChannel->getName().c_str(),
5996 canceledWindows.c_str());
5997
Prabir Pradhane680f9b2022-02-04 04:24:00 -08005998 // Prevent the gesture from being sent to any other windows.
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00005999 // This only blocks relevant pointers to be sent to other windows
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08006000 window.pilferedPointerIds |= window.pointerIds;
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00006001
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07006002 state.cancelPointersForWindowsExcept(window.pointerIds, token);
Michael Wright3dd60e22019-03-27 22:06:44 +00006003 return OK;
6004}
6005
Prabir Pradhan99987712020-11-10 18:43:05 -08006006void InputDispatcher::requestPointerCapture(const sp<IBinder>& windowToken, bool enabled) {
6007 { // acquire lock
6008 std::scoped_lock _l(mLock);
6009 if (DEBUG_FOCUS) {
chaviw98318de2021-05-19 16:45:23 -05006010 const sp<WindowInfoHandle> windowHandle = getWindowHandleLocked(windowToken);
Prabir Pradhan99987712020-11-10 18:43:05 -08006011 ALOGI("Request to %s Pointer Capture from: %s.", enabled ? "enable" : "disable",
6012 windowHandle != nullptr ? windowHandle->getName().c_str()
6013 : "token without window");
6014 }
6015
Vishnu Nairc519ff72021-01-21 08:23:08 -08006016 const sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Prabir Pradhan99987712020-11-10 18:43:05 -08006017 if (focusedToken != windowToken) {
6018 ALOGW("Ignoring request to %s Pointer Capture: window does not have focus.",
6019 enabled ? "enable" : "disable");
6020 return;
6021 }
6022
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006023 if (enabled == mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006024 ALOGW("Ignoring request to %s Pointer Capture: "
6025 "window has %s requested pointer capture.",
6026 enabled ? "enable" : "disable", enabled ? "already" : "not");
6027 return;
6028 }
6029
Christine Franksb768bb42021-11-29 12:11:31 -08006030 if (enabled) {
6031 if (std::find(mIneligibleDisplaysForPointerCapture.begin(),
6032 mIneligibleDisplaysForPointerCapture.end(),
6033 mFocusedDisplayId) != mIneligibleDisplaysForPointerCapture.end()) {
6034 ALOGW("Ignoring request to enable Pointer Capture: display is not eligible");
6035 return;
6036 }
6037 }
6038
Prabir Pradhan99987712020-11-10 18:43:05 -08006039 setPointerCaptureLocked(enabled);
6040 } // release lock
6041
6042 // Wake the thread to process command entries.
6043 mLooper->wake();
6044}
6045
Christine Franksb768bb42021-11-29 12:11:31 -08006046void InputDispatcher::setDisplayEligibilityForPointerCapture(int32_t displayId, bool isEligible) {
6047 { // acquire lock
6048 std::scoped_lock _l(mLock);
6049 std::erase(mIneligibleDisplaysForPointerCapture, displayId);
6050 if (!isEligible) {
6051 mIneligibleDisplaysForPointerCapture.push_back(displayId);
6052 }
6053 } // release lock
6054}
6055
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006056std::optional<int32_t> InputDispatcher::findMonitorPidByTokenLocked(const sp<IBinder>& token) {
6057 for (const auto& [_, monitors] : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00006058 for (const Monitor& monitor : monitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07006059 if (monitor.inputChannel->getConnectionToken() == token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006060 return monitor.pid;
Michael Wright3dd60e22019-03-27 22:06:44 +00006061 }
6062 }
6063 }
6064 return std::nullopt;
6065}
6066
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006067std::shared_ptr<Connection> InputDispatcher::getConnectionLocked(
6068 const sp<IBinder>& inputConnectionToken) const {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07006069 if (inputConnectionToken == nullptr) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07006070 return nullptr;
Arthur Hung3b413f22018-10-26 18:05:34 +08006071 }
6072
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00006073 for (const auto& [token, connection] : mConnectionsByToken) {
6074 if (token == inputConnectionToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07006075 return connection;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006076 }
6077 }
Robert Carr4e670e52018-08-15 13:26:12 -07006078
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07006079 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006080}
6081
Siarhei Vishniakouad991402020-10-28 11:40:09 -05006082std::string InputDispatcher::getConnectionNameLocked(const sp<IBinder>& connectionToken) const {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006083 std::shared_ptr<Connection> connection = getConnectionLocked(connectionToken);
Siarhei Vishniakouad991402020-10-28 11:40:09 -05006084 if (connection == nullptr) {
6085 return "<nullptr>";
6086 }
6087 return connection->getInputChannelName();
6088}
6089
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006090void InputDispatcher::removeConnectionLocked(const std::shared_ptr<Connection>& connection) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006091 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00006092 mConnectionsByToken.erase(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07006093}
6094
Prabir Pradhancef936d2021-07-21 16:17:52 +00006095void InputDispatcher::doDispatchCycleFinishedCommand(nsecs_t finishTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006096 const std::shared_ptr<Connection>& connection,
6097 uint32_t seq, bool handled,
6098 nsecs_t consumeTime) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006099 // Handle post-event policy actions.
6100 std::deque<DispatchEntry*>::iterator dispatchEntryIt = connection->findWaitQueueEntry(seq);
6101 if (dispatchEntryIt == connection->waitQueue.end()) {
6102 return;
6103 }
6104 DispatchEntry* dispatchEntry = *dispatchEntryIt;
6105 const nsecs_t eventDuration = finishTime - dispatchEntry->deliveryTime;
6106 if (eventDuration > SLOW_EVENT_PROCESSING_WARNING_TIMEOUT) {
6107 ALOGI("%s spent %" PRId64 "ms processing %s", connection->getWindowName().c_str(),
6108 ns2ms(eventDuration), dispatchEntry->eventEntry->getDescription().c_str());
6109 }
6110 if (shouldReportFinishedEvent(*dispatchEntry, *connection)) {
6111 mLatencyTracker.trackFinishedEvent(dispatchEntry->eventEntry->id,
6112 connection->inputChannel->getConnectionToken(),
6113 dispatchEntry->deliveryTime, consumeTime, finishTime);
6114 }
6115
6116 bool restartEvent;
6117 if (dispatchEntry->eventEntry->type == EventEntry::Type::KEY) {
6118 KeyEntry& keyEntry = static_cast<KeyEntry&>(*(dispatchEntry->eventEntry));
6119 restartEvent =
6120 afterKeyEventLockedInterruptable(connection, dispatchEntry, keyEntry, handled);
6121 } else if (dispatchEntry->eventEntry->type == EventEntry::Type::MOTION) {
6122 MotionEntry& motionEntry = static_cast<MotionEntry&>(*(dispatchEntry->eventEntry));
6123 restartEvent = afterMotionEventLockedInterruptable(connection, dispatchEntry, motionEntry,
6124 handled);
6125 } else {
6126 restartEvent = false;
6127 }
6128
6129 // Dequeue the event and start the next cycle.
6130 // Because the lock might have been released, it is possible that the
6131 // contents of the wait queue to have been drained, so we need to double-check
6132 // a few things.
6133 dispatchEntryIt = connection->findWaitQueueEntry(seq);
6134 if (dispatchEntryIt != connection->waitQueue.end()) {
6135 dispatchEntry = *dispatchEntryIt;
6136 connection->waitQueue.erase(dispatchEntryIt);
6137 const sp<IBinder>& connectionToken = connection->inputChannel->getConnectionToken();
6138 mAnrTracker.erase(dispatchEntry->timeoutTime, connectionToken);
6139 if (!connection->responsive) {
6140 connection->responsive = isConnectionResponsive(*connection);
6141 if (connection->responsive) {
6142 // The connection was unresponsive, and now it's responsive.
6143 processConnectionResponsiveLocked(*connection);
6144 }
6145 }
6146 traceWaitQueueLength(*connection);
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08006147 if (restartEvent && connection->status == Connection::Status::NORMAL) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006148 connection->outboundQueue.push_front(dispatchEntry);
6149 traceOutboundQueueLength(*connection);
6150 } else {
6151 releaseDispatchEntry(dispatchEntry);
6152 }
6153 }
6154
6155 // Start the next dispatch cycle for this connection.
6156 startDispatchCycleLocked(now(), connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006157}
6158
Prabir Pradhancef936d2021-07-21 16:17:52 +00006159void InputDispatcher::sendFocusChangedCommandLocked(const sp<IBinder>& oldToken,
6160 const sp<IBinder>& newToken) {
6161 auto command = [this, oldToken, newToken]() REQUIRES(mLock) {
6162 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00006163 mPolicy.notifyFocusChanged(oldToken, newToken);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006164 };
6165 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08006166}
6167
Prabir Pradhancef936d2021-07-21 16:17:52 +00006168void InputDispatcher::sendDropWindowCommandLocked(const sp<IBinder>& token, float x, float y) {
6169 auto command = [this, token, x, y]() REQUIRES(mLock) {
6170 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00006171 mPolicy.notifyDropWindow(token, x, y);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006172 };
6173 postCommandLocked(std::move(command));
Robert Carrf759f162018-11-13 12:57:11 -08006174}
6175
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006176void InputDispatcher::onAnrLocked(const std::shared_ptr<Connection>& connection) {
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006177 if (connection == nullptr) {
6178 LOG_ALWAYS_FATAL("Caller must check for nullness");
6179 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006180 // Since we are allowing the policy to extend the timeout, maybe the waitQueue
6181 // is already healthy again. Don't raise ANR in this situation
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006182 if (connection->waitQueue.empty()) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006183 ALOGI("Not raising ANR because the connection %s has recovered",
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006184 connection->inputChannel->getName().c_str());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006185 return;
6186 }
6187 /**
6188 * The "oldestEntry" is the entry that was first sent to the application. That entry, however,
6189 * may not be the one that caused the timeout to occur. One possibility is that window timeout
6190 * has changed. This could cause newer entries to time out before the already dispatched
6191 * entries. In that situation, the newest entries caused ANR. But in all likelihood, the app
6192 * processes the events linearly. So providing information about the oldest entry seems to be
6193 * most useful.
6194 */
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006195 DispatchEntry* oldestEntry = *connection->waitQueue.begin();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006196 const nsecs_t currentWait = now() - oldestEntry->deliveryTime;
6197 std::string reason =
6198 android::base::StringPrintf("%s is not responding. Waited %" PRId64 "ms for %s",
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006199 connection->inputChannel->getName().c_str(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006200 ns2ms(currentWait),
6201 oldestEntry->eventEntry->getDescription().c_str());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006202 sp<IBinder> connectionToken = connection->inputChannel->getConnectionToken();
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -06006203 updateLastAnrStateLocked(getWindowHandleLocked(connectionToken), reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006204
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006205 processConnectionUnresponsiveLocked(*connection, std::move(reason));
6206
6207 // Stop waking up for events on this connection, it is already unresponsive
6208 cancelEventsForAnrLocked(connection);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006209}
6210
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05006211void InputDispatcher::onAnrLocked(std::shared_ptr<InputApplicationHandle> application) {
6212 std::string reason =
6213 StringPrintf("%s does not have a focused window", application->getName().c_str());
6214 updateLastAnrStateLocked(*application, reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006215
Yabin Cui8eb9c552023-06-08 18:05:07 +00006216 auto command = [this, app = std::move(application)]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006217 scoped_unlock unlock(mLock);
Yabin Cuiced952f2023-06-09 21:12:51 +00006218 mPolicy.notifyNoFocusedWindowAnr(app);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006219 };
6220 postCommandLocked(std::move(command));
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00006221}
6222
chaviw98318de2021-05-19 16:45:23 -05006223void InputDispatcher::updateLastAnrStateLocked(const sp<WindowInfoHandle>& window,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006224 const std::string& reason) {
6225 const std::string windowLabel = getApplicationWindowLabel(nullptr, window);
6226 updateLastAnrStateLocked(windowLabel, reason);
6227}
6228
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05006229void InputDispatcher::updateLastAnrStateLocked(const InputApplicationHandle& application,
6230 const std::string& reason) {
6231 const std::string windowLabel = getApplicationWindowLabel(&application, nullptr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006232 updateLastAnrStateLocked(windowLabel, reason);
6233}
6234
6235void InputDispatcher::updateLastAnrStateLocked(const std::string& windowLabel,
6236 const std::string& reason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006237 // Capture a record of the InputDispatcher state at the time of the ANR.
Yi Kong9b14ac62018-07-17 13:48:38 -07006238 time_t t = time(nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006239 struct tm tm;
6240 localtime_r(&t, &tm);
6241 char timestr[64];
6242 strftime(timestr, sizeof(timestr), "%F %T", &tm);
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006243 mLastAnrState.clear();
6244 mLastAnrState += INDENT "ANR:\n";
6245 mLastAnrState += StringPrintf(INDENT2 "Time: %s\n", timestr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006246 mLastAnrState += StringPrintf(INDENT2 "Reason: %s\n", reason.c_str());
6247 mLastAnrState += StringPrintf(INDENT2 "Window: %s\n", windowLabel.c_str());
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006248 dumpDispatchStateLocked(mLastAnrState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006249}
6250
Prabir Pradhancef936d2021-07-21 16:17:52 +00006251void InputDispatcher::doInterceptKeyBeforeDispatchingCommand(const sp<IBinder>& focusedWindowToken,
6252 KeyEntry& entry) {
6253 const KeyEvent event = createKeyEvent(entry);
6254 nsecs_t delay = 0;
6255 { // release lock
6256 scoped_unlock unlock(mLock);
6257 android::base::Timer t;
Prabir Pradhana41d2442023-04-20 21:30:40 +00006258 delay = mPolicy.interceptKeyBeforeDispatching(focusedWindowToken, event, entry.policyFlags);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006259 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
6260 ALOGW("Excessive delay in interceptKeyBeforeDispatching; took %s ms",
6261 std::to_string(t.duration().count()).c_str());
6262 }
6263 } // acquire lock
Michael Wrightd02c5b62014-02-10 15:10:22 -08006264
6265 if (delay < 0) {
Michael Wright5caf55a2022-11-24 22:31:42 +00006266 entry.interceptKeyResult = KeyEntry::InterceptKeyResult::SKIP;
Prabir Pradhancef936d2021-07-21 16:17:52 +00006267 } else if (delay == 0) {
Michael Wright5caf55a2022-11-24 22:31:42 +00006268 entry.interceptKeyResult = KeyEntry::InterceptKeyResult::CONTINUE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006269 } else {
Michael Wright5caf55a2022-11-24 22:31:42 +00006270 entry.interceptKeyResult = KeyEntry::InterceptKeyResult::TRY_AGAIN_LATER;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006271 entry.interceptKeyWakeupTime = now() + delay;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006272 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006273}
6274
Prabir Pradhancef936d2021-07-21 16:17:52 +00006275void InputDispatcher::sendWindowUnresponsiveCommandLocked(const sp<IBinder>& token,
Prabir Pradhanedd96402022-02-15 01:46:16 -08006276 std::optional<int32_t> pid,
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006277 std::string reason) {
Yabin Cui8eb9c552023-06-08 18:05:07 +00006278 auto command = [this, token, pid, r = std::move(reason)]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006279 scoped_unlock unlock(mLock);
Yabin Cuiced952f2023-06-09 21:12:51 +00006280 mPolicy.notifyWindowUnresponsive(token, pid, r);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006281 };
6282 postCommandLocked(std::move(command));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006283}
6284
Prabir Pradhanedd96402022-02-15 01:46:16 -08006285void InputDispatcher::sendWindowResponsiveCommandLocked(const sp<IBinder>& token,
6286 std::optional<int32_t> pid) {
6287 auto command = [this, token, pid]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006288 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00006289 mPolicy.notifyWindowResponsive(token, pid);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006290 };
6291 postCommandLocked(std::move(command));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006292}
6293
6294/**
6295 * Tell the policy that a connection has become unresponsive so that it can start ANR.
6296 * Check whether the connection of interest is a monitor or a window, and add the corresponding
6297 * command entry to the command queue.
6298 */
6299void InputDispatcher::processConnectionUnresponsiveLocked(const Connection& connection,
6300 std::string reason) {
6301 const sp<IBinder>& connectionToken = connection.inputChannel->getConnectionToken();
Prabir Pradhanedd96402022-02-15 01:46:16 -08006302 std::optional<int32_t> pid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006303 if (connection.monitor) {
6304 ALOGW("Monitor %s is unresponsive: %s", connection.inputChannel->getName().c_str(),
6305 reason.c_str());
Prabir Pradhanedd96402022-02-15 01:46:16 -08006306 pid = findMonitorPidByTokenLocked(connectionToken);
6307 } else {
6308 // The connection is a window
6309 ALOGW("Window %s is unresponsive: %s", connection.inputChannel->getName().c_str(),
6310 reason.c_str());
6311 const sp<WindowInfoHandle> handle = getWindowHandleLocked(connectionToken);
6312 if (handle != nullptr) {
6313 pid = handle->getInfo()->ownerPid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006314 }
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006315 }
Prabir Pradhanedd96402022-02-15 01:46:16 -08006316 sendWindowUnresponsiveCommandLocked(connectionToken, pid, std::move(reason));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006317}
6318
6319/**
6320 * Tell the policy that a connection has become responsive so that it can stop ANR.
6321 */
6322void InputDispatcher::processConnectionResponsiveLocked(const Connection& connection) {
6323 const sp<IBinder>& connectionToken = connection.inputChannel->getConnectionToken();
Prabir Pradhanedd96402022-02-15 01:46:16 -08006324 std::optional<int32_t> pid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006325 if (connection.monitor) {
Prabir Pradhanedd96402022-02-15 01:46:16 -08006326 pid = findMonitorPidByTokenLocked(connectionToken);
6327 } else {
6328 // The connection is a window
6329 const sp<WindowInfoHandle> handle = getWindowHandleLocked(connectionToken);
6330 if (handle != nullptr) {
6331 pid = handle->getInfo()->ownerPid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006332 }
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006333 }
Prabir Pradhanedd96402022-02-15 01:46:16 -08006334 sendWindowResponsiveCommandLocked(connectionToken, pid);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006335}
6336
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006337bool InputDispatcher::afterKeyEventLockedInterruptable(
6338 const std::shared_ptr<Connection>& connection, DispatchEntry* dispatchEntry,
6339 KeyEntry& keyEntry, bool handled) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006340 if (keyEntry.flags & AKEY_EVENT_FLAG_FALLBACK) {
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006341 if (!handled) {
6342 // Report the key as unhandled, since the fallback was not handled.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006343 mReporter->reportUnhandledKey(keyEntry.id);
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006344 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006345 return false;
6346 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006347
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006348 // Get the fallback key state.
6349 // Clear it out after dispatching the UP.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006350 int32_t originalKeyCode = keyEntry.keyCode;
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006351 std::optional<int32_t> fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006352 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006353 connection->inputState.removeFallbackKey(originalKeyCode);
6354 }
6355
6356 if (handled || !dispatchEntry->hasForegroundTarget()) {
6357 // If the application handles the original key for which we previously
6358 // generated a fallback or if the window is not a foreground window,
6359 // then cancel the associated fallback key, if any.
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006360 if (fallbackKeyCode) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006361 // Dispatch the unhandled key to the policy with the cancel flag.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006362 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6363 ALOGD("Unhandled key event: Asking policy to cancel fallback action. "
6364 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6365 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount,
6366 keyEntry.policyFlags);
6367 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006368 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006369 event.setFlags(event.getFlags() | AKEY_EVENT_FLAG_CANCELED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006370
6371 mLock.unlock();
6372
Prabir Pradhana41d2442023-04-20 21:30:40 +00006373 if (const auto unhandledKeyFallback =
6374 mPolicy.dispatchUnhandledKey(connection->inputChannel->getConnectionToken(),
6375 event, keyEntry.policyFlags);
6376 unhandledKeyFallback) {
6377 event = *unhandledKeyFallback;
6378 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006379
6380 mLock.lock();
6381
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006382 // Cancel the fallback key.
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006383 if (*fallbackKeyCode != AKEYCODE_UNKNOWN) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00006384 CancelationOptions options(CancelationOptions::Mode::CANCEL_FALLBACK_EVENTS,
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006385 "application handled the original non-fallback key "
6386 "or is no longer a foreground target, "
6387 "canceling previously dispatched fallback key");
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006388 options.keyCode = *fallbackKeyCode;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006389 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006390 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006391 connection->inputState.removeFallbackKey(originalKeyCode);
6392 }
6393 } else {
6394 // If the application did not handle a non-fallback key, first check
6395 // that we are in a good state to perform unhandled key event processing
6396 // Then ask the policy what to do with it.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006397 bool initialDown = keyEntry.action == AKEY_EVENT_ACTION_DOWN && keyEntry.repeatCount == 0;
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006398 if (!fallbackKeyCode && !initialDown) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006399 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6400 ALOGD("Unhandled key event: Skipping unhandled key event processing "
6401 "since this is not an initial down. "
6402 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6403 originalKeyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
6404 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006405 return false;
6406 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006407
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006408 // Dispatch the unhandled key to the policy.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006409 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6410 ALOGD("Unhandled key event: Asking policy to perform fallback action. "
6411 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6412 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
6413 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006414 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006415
6416 mLock.unlock();
6417
Prabir Pradhana41d2442023-04-20 21:30:40 +00006418 bool fallback = false;
6419 if (auto fb = mPolicy.dispatchUnhandledKey(connection->inputChannel->getConnectionToken(),
6420 event, keyEntry.policyFlags);
6421 fb) {
6422 fallback = true;
6423 event = *fb;
6424 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006425
6426 mLock.lock();
6427
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08006428 if (connection->status != Connection::Status::NORMAL) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006429 connection->inputState.removeFallbackKey(originalKeyCode);
6430 return false;
6431 }
6432
6433 // Latch the fallback keycode for this key on an initial down.
6434 // The fallback keycode cannot change at any other point in the lifecycle.
6435 if (initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006436 if (fallback) {
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006437 *fallbackKeyCode = event.getKeyCode();
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006438 } else {
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006439 *fallbackKeyCode = AKEYCODE_UNKNOWN;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006440 }
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006441 connection->inputState.setFallbackKey(originalKeyCode, *fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006442 }
6443
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006444 ALOG_ASSERT(fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006445
6446 // Cancel the fallback key if the policy decides not to send it anymore.
6447 // We will continue to dispatch the key to the policy but we will no
6448 // longer dispatch a fallback key to the application.
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006449 if (*fallbackKeyCode != AKEYCODE_UNKNOWN &&
6450 (!fallback || *fallbackKeyCode != event.getKeyCode())) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006451 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6452 if (fallback) {
6453 ALOGD("Unhandled key event: Policy requested to send key %d"
6454 "as a fallback for %d, but on the DOWN it had requested "
6455 "to send %d instead. Fallback canceled.",
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006456 event.getKeyCode(), originalKeyCode, *fallbackKeyCode);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006457 } else {
6458 ALOGD("Unhandled key event: Policy did not request fallback for %d, "
6459 "but on the DOWN it had requested to send %d. "
6460 "Fallback canceled.",
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006461 originalKeyCode, *fallbackKeyCode);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006462 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006463 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006464
Michael Wrightfb04fd52022-11-24 22:31:11 +00006465 CancelationOptions options(CancelationOptions::Mode::CANCEL_FALLBACK_EVENTS,
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006466 "canceling fallback, policy no longer desires it");
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006467 options.keyCode = *fallbackKeyCode;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006468 synthesizeCancelationEventsForConnectionLocked(connection, options);
6469
6470 fallback = false;
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006471 *fallbackKeyCode = AKEYCODE_UNKNOWN;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006472 if (keyEntry.action != AKEY_EVENT_ACTION_UP) {
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006473 connection->inputState.setFallbackKey(originalKeyCode, *fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006474 }
6475 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006476
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006477 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6478 {
6479 std::string msg;
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006480 const std::map<int32_t, int32_t>& fallbackKeys =
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006481 connection->inputState.getFallbackKeys();
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006482 for (const auto& [key, value] : fallbackKeys) {
6483 msg += StringPrintf(", %d->%d", key, value);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006484 }
6485 ALOGD("Unhandled key event: %zu currently tracked fallback keys%s.",
6486 fallbackKeys.size(), msg.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006487 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006488 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006489
6490 if (fallback) {
6491 // Restart the dispatch cycle using the fallback key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006492 keyEntry.eventTime = event.getEventTime();
6493 keyEntry.deviceId = event.getDeviceId();
6494 keyEntry.source = event.getSource();
6495 keyEntry.displayId = event.getDisplayId();
6496 keyEntry.flags = event.getFlags() | AKEY_EVENT_FLAG_FALLBACK;
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006497 keyEntry.keyCode = *fallbackKeyCode;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006498 keyEntry.scanCode = event.getScanCode();
6499 keyEntry.metaState = event.getMetaState();
6500 keyEntry.repeatCount = event.getRepeatCount();
6501 keyEntry.downTime = event.getDownTime();
6502 keyEntry.syntheticRepeat = false;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006503
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006504 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6505 ALOGD("Unhandled key event: Dispatching fallback key. "
6506 "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006507 originalKeyCode, *fallbackKeyCode, keyEntry.metaState);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006508 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006509 return true; // restart the event
6510 } else {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006511 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6512 ALOGD("Unhandled key event: No fallback key.");
6513 }
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006514
6515 // Report the key as unhandled, since there is no fallback key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006516 mReporter->reportUnhandledKey(keyEntry.id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006517 }
6518 }
6519 return false;
6520}
6521
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006522bool InputDispatcher::afterMotionEventLockedInterruptable(
6523 const std::shared_ptr<Connection>& connection, DispatchEntry* dispatchEntry,
6524 MotionEntry& motionEntry, bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006525 return false;
6526}
6527
Michael Wrightd02c5b62014-02-10 15:10:22 -08006528void InputDispatcher::traceInboundQueueLengthLocked() {
6529 if (ATRACE_ENABLED()) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07006530 ATRACE_INT("iq", mInboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006531 }
6532}
6533
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006534void InputDispatcher::traceOutboundQueueLength(const Connection& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006535 if (ATRACE_ENABLED()) {
6536 char counterName[40];
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006537 snprintf(counterName, sizeof(counterName), "oq:%s", connection.getWindowName().c_str());
6538 ATRACE_INT(counterName, connection.outboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006539 }
6540}
6541
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006542void InputDispatcher::traceWaitQueueLength(const Connection& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006543 if (ATRACE_ENABLED()) {
6544 char counterName[40];
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006545 snprintf(counterName, sizeof(counterName), "wq:%s", connection.getWindowName().c_str());
6546 ATRACE_INT(counterName, connection.waitQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006547 }
6548}
6549
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006550void InputDispatcher::dump(std::string& dump) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006551 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006552
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006553 dump += "Input Dispatcher State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08006554 dumpDispatchStateLocked(dump);
6555
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006556 if (!mLastAnrState.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006557 dump += "\nInput Dispatcher State at time of last ANR:\n";
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006558 dump += mLastAnrState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006559 }
6560}
6561
6562void InputDispatcher::monitor() {
6563 // Acquire and release the lock to ensure that the dispatcher has not deadlocked.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006564 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006565 mLooper->wake();
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006566 mDispatcherIsAlive.wait(_l);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006567}
6568
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08006569/**
6570 * Wake up the dispatcher and wait until it processes all events and commands.
6571 * The notification of mDispatcherEnteredIdle is guaranteed to happen after wake(), so
6572 * this method can be safely called from any thread, as long as you've ensured that
6573 * the work you are interested in completing has already been queued.
6574 */
6575bool InputDispatcher::waitForIdle() {
6576 /**
6577 * Timeout should represent the longest possible time that a device might spend processing
6578 * events and commands.
6579 */
6580 constexpr std::chrono::duration TIMEOUT = 100ms;
6581 std::unique_lock lock(mLock);
6582 mLooper->wake();
6583 std::cv_status result = mDispatcherEnteredIdle.wait_for(lock, TIMEOUT);
6584 return result == std::cv_status::no_timeout;
6585}
6586
Vishnu Naire798b472020-07-23 13:52:21 -07006587/**
6588 * Sets focus to the window identified by the token. This must be called
6589 * after updating any input window handles.
6590 *
6591 * Params:
6592 * request.token - input channel token used to identify the window that should gain focus.
6593 * request.focusedToken - the token that the caller expects currently to be focused. If the
6594 * specified token does not match the currently focused window, this request will be dropped.
6595 * If the specified focused token matches the currently focused window, the call will succeed.
6596 * Set this to "null" if this call should succeed no matter what the currently focused token is.
6597 * request.timestamp - SYSTEM_TIME_MONOTONIC timestamp in nanos set by the client (wm)
6598 * when requesting the focus change. This determines which request gets
6599 * precedence if there is a focus change request from another source such as pointer down.
6600 */
Vishnu Nair958da932020-08-21 17:12:37 -07006601void InputDispatcher::setFocusedWindow(const FocusRequest& request) {
6602 { // acquire lock
6603 std::scoped_lock _l(mLock);
Vishnu Nairc519ff72021-01-21 08:23:08 -08006604 std::optional<FocusResolver::FocusChanges> changes =
6605 mFocusResolver.setFocusedWindow(request, getWindowHandlesLocked(request.displayId));
6606 if (changes) {
6607 onFocusChangedLocked(*changes);
Vishnu Nair958da932020-08-21 17:12:37 -07006608 }
6609 } // release lock
6610 // Wake up poll loop since it may need to make new input dispatching choices.
6611 mLooper->wake();
6612}
6613
Vishnu Nairc519ff72021-01-21 08:23:08 -08006614void InputDispatcher::onFocusChangedLocked(const FocusResolver::FocusChanges& changes) {
6615 if (changes.oldFocus) {
6616 std::shared_ptr<InputChannel> focusedInputChannel = getInputChannelLocked(changes.oldFocus);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006617 if (focusedInputChannel) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00006618 CancelationOptions options(CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS,
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006619 "focus left window");
6620 synthesizeCancelationEventsForInputChannelLocked(focusedInputChannel, options);
Harry Cutts33476232023-01-30 19:57:29 +00006621 enqueueFocusEventLocked(changes.oldFocus, /*hasFocus=*/false, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006622 }
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006623 }
Vishnu Nairc519ff72021-01-21 08:23:08 -08006624 if (changes.newFocus) {
Harry Cutts33476232023-01-30 19:57:29 +00006625 enqueueFocusEventLocked(changes.newFocus, /*hasFocus=*/true, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006626 }
6627
Prabir Pradhan99987712020-11-10 18:43:05 -08006628 // If a window has pointer capture, then it must have focus. We need to ensure that this
6629 // contract is upheld when pointer capture is being disabled due to a loss of window focus.
6630 // If the window loses focus before it loses pointer capture, then the window can be in a state
6631 // where it has pointer capture but not focus, violating the contract. Therefore we must
6632 // dispatch the pointer capture event before the focus event. Since focus events are added to
6633 // the front of the queue (above), we add the pointer capture event to the front of the queue
6634 // after the focus events are added. This ensures the pointer capture event ends up at the
6635 // front.
6636 disablePointerCaptureForcedLocked();
6637
Vishnu Nairc519ff72021-01-21 08:23:08 -08006638 if (mFocusedDisplayId == changes.displayId) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006639 sendFocusChangedCommandLocked(changes.oldFocus, changes.newFocus);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006640 }
6641}
Vishnu Nair958da932020-08-21 17:12:37 -07006642
Prabir Pradhan99987712020-11-10 18:43:05 -08006643void InputDispatcher::disablePointerCaptureForcedLocked() {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006644 if (!mCurrentPointerCaptureRequest.enable && !mWindowTokenWithPointerCapture) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006645 return;
6646 }
6647
6648 ALOGD_IF(DEBUG_FOCUS, "Disabling Pointer Capture because the window lost focus.");
6649
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006650 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006651 setPointerCaptureLocked(false);
6652 }
6653
6654 if (!mWindowTokenWithPointerCapture) {
6655 // No need to send capture changes because no window has capture.
6656 return;
6657 }
6658
6659 if (mPendingEvent != nullptr) {
6660 // Move the pending event to the front of the queue. This will give the chance
6661 // for the pending event to be dropped if it is a captured event.
6662 mInboundQueue.push_front(mPendingEvent);
6663 mPendingEvent = nullptr;
6664 }
6665
6666 auto entry = std::make_unique<PointerCaptureChangedEntry>(mIdGenerator.nextId(), now(),
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006667 mCurrentPointerCaptureRequest);
Prabir Pradhan99987712020-11-10 18:43:05 -08006668 mInboundQueue.push_front(std::move(entry));
6669}
6670
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006671void InputDispatcher::setPointerCaptureLocked(bool enable) {
6672 mCurrentPointerCaptureRequest.enable = enable;
6673 mCurrentPointerCaptureRequest.seq++;
6674 auto command = [this, request = mCurrentPointerCaptureRequest]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006675 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00006676 mPolicy.setPointerCapture(request);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006677 };
6678 postCommandLocked(std::move(command));
Prabir Pradhan99987712020-11-10 18:43:05 -08006679}
6680
Vishnu Nair599f1412021-06-21 10:39:58 -07006681void InputDispatcher::displayRemoved(int32_t displayId) {
6682 { // acquire lock
6683 std::scoped_lock _l(mLock);
6684 // Set an empty list to remove all handles from the specific display.
6685 setInputWindowsLocked(/* window handles */ {}, displayId);
6686 setFocusedApplicationLocked(displayId, nullptr);
6687 // Call focus resolver to clean up stale requests. This must be called after input windows
6688 // have been removed for the removed display.
6689 mFocusResolver.displayRemoved(displayId);
Christine Franksb768bb42021-11-29 12:11:31 -08006690 // Reset pointer capture eligibility, regardless of previous state.
6691 std::erase(mIneligibleDisplaysForPointerCapture, displayId);
Antonio Kantek15beb512022-06-13 22:35:41 +00006692 // Remove the associated touch mode state.
6693 mTouchModePerDisplay.erase(displayId);
Vishnu Nair599f1412021-06-21 10:39:58 -07006694 } // release lock
6695
6696 // Wake up poll loop since it may need to make new input dispatching choices.
6697 mLooper->wake();
6698}
6699
Patrick Williamsd828f302023-04-28 17:52:08 -05006700void InputDispatcher::onWindowInfosChanged(const gui::WindowInfosUpdate& update) {
chaviw15fab6f2021-06-07 14:15:52 -05006701 // The listener sends the windows as a flattened array. Separate the windows by display for
6702 // more convenient parsing.
6703 std::unordered_map<int32_t, std::vector<sp<WindowInfoHandle>>> handlesPerDisplay;
Patrick Williamsd828f302023-04-28 17:52:08 -05006704 for (const auto& info : update.windowInfos) {
chaviw15fab6f2021-06-07 14:15:52 -05006705 handlesPerDisplay.emplace(info.displayId, std::vector<sp<WindowInfoHandle>>());
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07006706 handlesPerDisplay[info.displayId].push_back(sp<WindowInfoHandle>::make(info));
chaviw15fab6f2021-06-07 14:15:52 -05006707 }
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006708
6709 { // acquire lock
6710 std::scoped_lock _l(mLock);
Prabir Pradhan814fe082022-07-22 20:22:18 +00006711
6712 // Ensure that we have an entry created for all existing displays so that if a displayId has
6713 // no windows, we can tell that the windows were removed from the display.
6714 for (const auto& [displayId, _] : mWindowHandlesByDisplay) {
6715 handlesPerDisplay[displayId];
6716 }
6717
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006718 mDisplayInfos.clear();
Patrick Williamsd828f302023-04-28 17:52:08 -05006719 for (const auto& displayInfo : update.displayInfos) {
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006720 mDisplayInfos.emplace(displayInfo.displayId, displayInfo);
6721 }
6722
6723 for (const auto& [displayId, handles] : handlesPerDisplay) {
6724 setInputWindowsLocked(handles, displayId);
6725 }
Patrick Williams9464b2c2023-05-23 11:22:04 -05006726
6727 if (update.vsyncId < mWindowInfosVsyncId) {
6728 ALOGE("Received out of order window infos update. Last update vsync id: %" PRId64
6729 ", current update vsync id: %" PRId64,
6730 mWindowInfosVsyncId, update.vsyncId);
6731 }
6732 mWindowInfosVsyncId = update.vsyncId;
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006733 }
6734 // Wake up poll loop since it may need to make new input dispatching choices.
6735 mLooper->wake();
chaviw15fab6f2021-06-07 14:15:52 -05006736}
6737
Vishnu Nair062a8672021-09-03 16:07:44 -07006738bool InputDispatcher::shouldDropInput(
6739 const EventEntry& entry, const sp<android::gui::WindowInfoHandle>& windowHandle) const {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006740 if (windowHandle->getInfo()->inputConfig.test(WindowInfo::InputConfig::DROP_INPUT) ||
6741 (windowHandle->getInfo()->inputConfig.test(
6742 WindowInfo::InputConfig::DROP_INPUT_IF_OBSCURED) &&
Vishnu Nair062a8672021-09-03 16:07:44 -07006743 isWindowObscuredLocked(windowHandle))) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006744 ALOGW("Dropping %s event targeting %s as requested by the input configuration {%s} on "
6745 "display %" PRId32 ".",
Vishnu Nair062a8672021-09-03 16:07:44 -07006746 ftl::enum_string(entry.type).c_str(), windowHandle->getName().c_str(),
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006747 windowHandle->getInfo()->inputConfig.string().c_str(),
Vishnu Nair062a8672021-09-03 16:07:44 -07006748 windowHandle->getInfo()->displayId);
6749 return true;
6750 }
6751 return false;
6752}
6753
Siarhei Vishniakou18050092021-09-01 13:32:49 -07006754void InputDispatcher::DispatcherWindowListener::onWindowInfosChanged(
Patrick Williamsd828f302023-04-28 17:52:08 -05006755 const gui::WindowInfosUpdate& update) {
6756 mDispatcher.onWindowInfosChanged(update);
Siarhei Vishniakou18050092021-09-01 13:32:49 -07006757}
6758
Arthur Hungdfd528e2021-12-08 13:23:04 +00006759void InputDispatcher::cancelCurrentTouch() {
6760 {
6761 std::scoped_lock _l(mLock);
6762 ALOGD("Canceling all ongoing pointer gestures on all displays.");
Michael Wrightfb04fd52022-11-24 22:31:11 +00006763 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
Arthur Hungdfd528e2021-12-08 13:23:04 +00006764 "cancel current touch");
6765 synthesizeCancelationEventsForAllConnectionsLocked(options);
6766
6767 mTouchStatesByDisplay.clear();
Arthur Hungdfd528e2021-12-08 13:23:04 +00006768 }
6769 // Wake up poll loop since there might be work to do.
6770 mLooper->wake();
6771}
6772
Prabir Pradhan87112a72023-04-20 19:13:39 +00006773void InputDispatcher::requestRefreshConfiguration() {
Prabir Pradhana41d2442023-04-20 21:30:40 +00006774 InputDispatcherConfiguration config = mPolicy.getDispatcherConfiguration();
Prabir Pradhan87112a72023-04-20 19:13:39 +00006775
6776 std::scoped_lock _l(mLock);
6777 mConfig = config;
6778}
6779
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006780void InputDispatcher::setMonitorDispatchingTimeoutForTest(std::chrono::nanoseconds timeout) {
6781 std::scoped_lock _l(mLock);
6782 mMonitorDispatchingTimeout = timeout;
6783}
6784
Arthur Hungc539dbb2022-12-08 07:45:36 +00006785void InputDispatcher::slipWallpaperTouch(ftl::Flags<InputTarget::Flags> targetFlags,
6786 const sp<WindowInfoHandle>& oldWindowHandle,
6787 const sp<WindowInfoHandle>& newWindowHandle,
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08006788 TouchState& state, int32_t pointerId,
Siarhei Vishniakoubf880522023-05-01 11:03:22 -07006789 std::vector<InputTarget>& targets) const {
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08006790 std::bitset<MAX_POINTER_ID + 1> pointerIds;
6791 pointerIds.set(pointerId);
Arthur Hungc539dbb2022-12-08 07:45:36 +00006792 const bool oldHasWallpaper = oldWindowHandle->getInfo()->inputConfig.test(
6793 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
6794 const bool newHasWallpaper = targetFlags.test(InputTarget::Flags::FOREGROUND) &&
6795 newWindowHandle->getInfo()->inputConfig.test(
6796 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
6797 const sp<WindowInfoHandle> oldWallpaper =
6798 oldHasWallpaper ? state.getWallpaperWindow() : nullptr;
6799 const sp<WindowInfoHandle> newWallpaper =
6800 newHasWallpaper ? findWallpaperWindowBelow(newWindowHandle) : nullptr;
6801 if (oldWallpaper == newWallpaper) {
6802 return;
6803 }
6804
6805 if (oldWallpaper != nullptr) {
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08006806 const TouchedWindow& oldTouchedWindow = state.getTouchedWindow(oldWallpaper);
6807 addWindowTargetLocked(oldWallpaper,
6808 oldTouchedWindow.targetFlags |
6809 InputTarget::Flags::DISPATCH_AS_SLIPPERY_EXIT,
6810 pointerIds, oldTouchedWindow.firstDownTimeInTarget, targets);
6811 state.removeTouchedPointerFromWindow(pointerId, oldWallpaper);
Arthur Hungc539dbb2022-12-08 07:45:36 +00006812 }
6813
6814 if (newWallpaper != nullptr) {
6815 state.addOrUpdateWindow(newWallpaper,
6816 InputTarget::Flags::DISPATCH_AS_SLIPPERY_ENTER |
6817 InputTarget::Flags::WINDOW_IS_OBSCURED |
6818 InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED,
6819 pointerIds);
6820 }
6821}
6822
6823void InputDispatcher::transferWallpaperTouch(ftl::Flags<InputTarget::Flags> oldTargetFlags,
6824 ftl::Flags<InputTarget::Flags> newTargetFlags,
6825 const sp<WindowInfoHandle> fromWindowHandle,
6826 const sp<WindowInfoHandle> toWindowHandle,
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08006827 TouchState& state,
6828 std::bitset<MAX_POINTER_ID + 1> pointerIds) {
Arthur Hungc539dbb2022-12-08 07:45:36 +00006829 const bool oldHasWallpaper = oldTargetFlags.test(InputTarget::Flags::FOREGROUND) &&
6830 fromWindowHandle->getInfo()->inputConfig.test(
6831 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
6832 const bool newHasWallpaper = newTargetFlags.test(InputTarget::Flags::FOREGROUND) &&
6833 toWindowHandle->getInfo()->inputConfig.test(
6834 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
6835
6836 const sp<WindowInfoHandle> oldWallpaper =
6837 oldHasWallpaper ? state.getWallpaperWindow() : nullptr;
6838 const sp<WindowInfoHandle> newWallpaper =
6839 newHasWallpaper ? findWallpaperWindowBelow(toWindowHandle) : nullptr;
6840 if (oldWallpaper == newWallpaper) {
6841 return;
6842 }
6843
6844 if (oldWallpaper != nullptr) {
6845 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
6846 "transferring touch focus to another window");
6847 state.removeWindowByToken(oldWallpaper->getToken());
6848 synthesizeCancelationEventsForWindowLocked(oldWallpaper, options);
6849 }
6850
6851 if (newWallpaper != nullptr) {
6852 nsecs_t downTimeInTarget = now();
6853 ftl::Flags<InputTarget::Flags> wallpaperFlags =
6854 oldTargetFlags & (InputTarget::Flags::SPLIT | InputTarget::Flags::DISPATCH_AS_IS);
6855 wallpaperFlags |= InputTarget::Flags::WINDOW_IS_OBSCURED |
6856 InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED;
6857 state.addOrUpdateWindow(newWallpaper, wallpaperFlags, pointerIds, downTimeInTarget);
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006858 std::shared_ptr<Connection> wallpaperConnection =
6859 getConnectionLocked(newWallpaper->getToken());
Arthur Hungc539dbb2022-12-08 07:45:36 +00006860 if (wallpaperConnection != nullptr) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006861 std::shared_ptr<Connection> toConnection =
6862 getConnectionLocked(toWindowHandle->getToken());
Arthur Hungc539dbb2022-12-08 07:45:36 +00006863 toConnection->inputState.mergePointerStateTo(wallpaperConnection->inputState);
6864 synthesizePointerDownEventsForConnectionLocked(downTimeInTarget, wallpaperConnection,
6865 wallpaperFlags);
6866 }
6867 }
6868}
6869
6870sp<WindowInfoHandle> InputDispatcher::findWallpaperWindowBelow(
6871 const sp<WindowInfoHandle>& windowHandle) const {
6872 const std::vector<sp<WindowInfoHandle>>& windowHandles =
6873 getWindowHandlesLocked(windowHandle->getInfo()->displayId);
6874 bool foundWindow = false;
6875 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
6876 if (!foundWindow && otherHandle != windowHandle) {
6877 continue;
6878 }
6879 if (windowHandle == otherHandle) {
6880 foundWindow = true;
6881 continue;
6882 }
6883
6884 if (otherHandle->getInfo()->inputConfig.test(WindowInfo::InputConfig::IS_WALLPAPER)) {
6885 return otherHandle;
6886 }
6887 }
6888 return nullptr;
6889}
6890
Garfield Tane84e6f92019-08-29 17:28:41 -07006891} // namespace android::inputdispatcher