blob: a10c957d150f5ae4c1398c34209d52a297cd42a1 [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)) {
665 LOG(FATAL) << "Expected ACTION_HOVER_MOVE instead of " << entry.getDescription();
666 }
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000667 touchedWindow.targetFlags = InputTarget::Flags::DISPATCH_AS_IS;
668 }
Siarhei Vishniakou8a878352023-01-30 14:05:01 -0800669 touchedWindow.pointerIds.set(pointerId);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000670 if (canReceiveForegroundTouches(*newWindow->getInfo())) {
671 touchedWindow.targetFlags |= InputTarget::Flags::FOREGROUND;
672 }
673 out.push_back(touchedWindow);
674 }
675 return out;
676}
677
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -0800678template <typename T>
679std::vector<T>& operator+=(std::vector<T>& left, const std::vector<T>& right) {
680 left.insert(left.end(), right.begin(), right.end());
681 return left;
682}
683
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000684} // namespace
685
Michael Wrightd02c5b62014-02-10 15:10:22 -0800686// --- InputDispatcher ---
687
Prabir Pradhana41d2442023-04-20 21:30:40 +0000688InputDispatcher::InputDispatcher(InputDispatcherPolicyInterface& policy)
Siarhei Vishniakou289e9242022-02-15 14:50:16 -0800689 : InputDispatcher(policy, STALE_EVENT_TIMEOUT) {}
690
Prabir Pradhana41d2442023-04-20 21:30:40 +0000691InputDispatcher::InputDispatcher(InputDispatcherPolicyInterface& policy,
Siarhei Vishniakou289e9242022-02-15 14:50:16 -0800692 std::chrono::nanoseconds staleEventTimeout)
Garfield Tan00f511d2019-06-12 16:55:40 -0700693 : mPolicy(policy),
694 mPendingEvent(nullptr),
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700695 mLastDropReason(DropReason::NOT_DROPPED),
Garfield Tanff1f1bb2020-01-28 13:24:04 -0800696 mIdGenerator(IdGenerator::Source::INPUT_DISPATCHER),
Garfield Tan00f511d2019-06-12 16:55:40 -0700697 mAppSwitchSawKeyDown(false),
Colin Cross5b799302022-10-18 21:52:41 -0700698 mAppSwitchDueTime(LLONG_MAX),
Garfield Tan00f511d2019-06-12 16:55:40 -0700699 mNextUnblockedEvent(nullptr),
Prabir Pradhan1376fcd2022-01-21 09:56:35 -0800700 mMonitorDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT),
Garfield Tan00f511d2019-06-12 16:55:40 -0700701 mDispatchEnabled(false),
702 mDispatchFrozen(false),
703 mInputFilterEnabled(false),
Bernardo Rufinoea97d182020-08-19 14:43:14 +0100704 mMaximumObscuringOpacityForTouch(1.0f),
Siarhei Vishniakou2508b872020-12-03 16:33:53 -1000705 mFocusedDisplayId(ADISPLAY_ID_DEFAULT),
Prabir Pradhan99987712020-11-10 18:43:05 -0800706 mWindowTokenWithPointerCapture(nullptr),
Siarhei Vishniakou289e9242022-02-15 14:50:16 -0800707 mStaleEventTimeout(staleEventTimeout),
Siarhei Vishniakoua04181f2021-03-26 05:56:49 +0000708 mLatencyAggregator(),
Antonio Kantek15beb512022-06-13 22:35:41 +0000709 mLatencyTracker(&mLatencyAggregator) {
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -0700710 mLooper = sp<Looper>::make(false);
Prabir Pradhanf93562f2018-11-29 12:13:37 -0800711 mReporter = createInputReporter();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800712
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -0700713 mWindowInfoListener = sp<DispatcherWindowListener>::make(*this);
Siarhei Vishniakou31977182022-09-30 08:51:23 -0700714#if defined(__ANDROID__)
Siarhei Vishniakou18050092021-09-01 13:32:49 -0700715 SurfaceComposerClient::getDefault()->addWindowInfosListener(mWindowInfoListener);
Siarhei Vishniakou31977182022-09-30 08:51:23 -0700716#endif
Yi Kong9b14ac62018-07-17 13:48:38 -0700717 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800718}
719
720InputDispatcher::~InputDispatcher() {
Prabir Pradhancef936d2021-07-21 16:17:52 +0000721 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800722
Prabir Pradhancef936d2021-07-21 16:17:52 +0000723 resetKeyRepeatLocked();
724 releasePendingEventLocked();
725 drainInboundQueueLocked();
726 mCommandQueue.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800727
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +0000728 while (!mConnectionsByToken.empty()) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -0700729 std::shared_ptr<Connection> connection = mConnectionsByToken.begin()->second;
Harry Cutts33476232023-01-30 19:57:29 +0000730 removeInputChannelLocked(connection->inputChannel->getConnectionToken(), /*notify=*/false);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800731 }
732}
733
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700734status_t InputDispatcher::start() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700735 if (mThread) {
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700736 return ALREADY_EXISTS;
737 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700738 mThread = std::make_unique<InputThread>(
739 "InputDispatcher", [this]() { dispatchOnce(); }, [this]() { mLooper->wake(); });
740 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700741}
742
743status_t InputDispatcher::stop() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700744 if (mThread && mThread->isCallingThread()) {
745 ALOGE("InputDispatcher cannot be stopped from its own thread!");
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700746 return INVALID_OPERATION;
747 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700748 mThread.reset();
749 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700750}
751
Michael Wrightd02c5b62014-02-10 15:10:22 -0800752void InputDispatcher::dispatchOnce() {
Colin Cross5b799302022-10-18 21:52:41 -0700753 nsecs_t nextWakeupTime = LLONG_MAX;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800754 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -0800755 std::scoped_lock _l(mLock);
756 mDispatcherIsAlive.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800757
758 // Run a dispatch loop if there are no pending commands.
759 // The dispatch loop might enqueue commands to run afterwards.
760 if (!haveCommandsLocked()) {
761 dispatchOnceInnerLocked(&nextWakeupTime);
762 }
763
764 // Run all pending commands if there are any.
765 // If any commands were run then force the next poll to wake up immediately.
Prabir Pradhancef936d2021-07-21 16:17:52 +0000766 if (runCommandsLockedInterruptable()) {
Colin Cross5b799302022-10-18 21:52:41 -0700767 nextWakeupTime = LLONG_MIN;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800768 }
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800769
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700770 // If we are still waiting for ack on some events,
771 // we might have to wake up earlier to check if an app is anr'ing.
772 const nsecs_t nextAnrCheck = processAnrsLocked();
773 nextWakeupTime = std::min(nextWakeupTime, nextAnrCheck);
774
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800775 // We are about to enter an infinitely long sleep, because we have no commands or
776 // pending or queued events
Colin Cross5b799302022-10-18 21:52:41 -0700777 if (nextWakeupTime == LLONG_MAX) {
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800778 mDispatcherEnteredIdle.notify_all();
779 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800780 } // release lock
781
782 // Wait for callback or timeout or wake. (make sure we round up, not down)
783 nsecs_t currentTime = now();
784 int timeoutMillis = toMillisecondTimeoutDelay(currentTime, nextWakeupTime);
785 mLooper->pollOnce(timeoutMillis);
786}
787
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700788/**
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500789 * Raise ANR if there is no focused window.
790 * Before the ANR is raised, do a final state check:
791 * 1. The currently focused application must be the same one we are waiting for.
792 * 2. Ensure we still don't have a focused window.
793 */
794void InputDispatcher::processNoFocusedWindowAnrLocked() {
795 // Check if the application that we are waiting for is still focused.
796 std::shared_ptr<InputApplicationHandle> focusedApplication =
797 getValueByKey(mFocusedApplicationHandlesByDisplay, mAwaitedApplicationDisplayId);
798 if (focusedApplication == nullptr ||
799 focusedApplication->getApplicationToken() !=
800 mAwaitedFocusedApplication->getApplicationToken()) {
801 // Unexpected because we should have reset the ANR timer when focused application changed
802 ALOGE("Waited for a focused window, but focused application has already changed to %s",
803 focusedApplication->getName().c_str());
804 return; // The focused application has changed.
805 }
806
chaviw98318de2021-05-19 16:45:23 -0500807 const sp<WindowInfoHandle>& focusedWindowHandle =
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500808 getFocusedWindowHandleLocked(mAwaitedApplicationDisplayId);
809 if (focusedWindowHandle != nullptr) {
810 return; // We now have a focused window. No need for ANR.
811 }
812 onAnrLocked(mAwaitedFocusedApplication);
813}
814
815/**
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700816 * Check if any of the connections' wait queues have events that are too old.
817 * If we waited for events to be ack'ed for more than the window timeout, raise an ANR.
818 * Return the time at which we should wake up next.
819 */
820nsecs_t InputDispatcher::processAnrsLocked() {
821 const nsecs_t currentTime = now();
Colin Cross5b799302022-10-18 21:52:41 -0700822 nsecs_t nextAnrCheck = LLONG_MAX;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700823 // Check if we are waiting for a focused window to appear. Raise ANR if waited too long
824 if (mNoFocusedWindowTimeoutTime.has_value() && mAwaitedFocusedApplication != nullptr) {
825 if (currentTime >= *mNoFocusedWindowTimeoutTime) {
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500826 processNoFocusedWindowAnrLocked();
Chris Yea209fde2020-07-22 13:54:51 -0700827 mAwaitedFocusedApplication.reset();
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500828 mNoFocusedWindowTimeoutTime = std::nullopt;
Colin Cross5b799302022-10-18 21:52:41 -0700829 return LLONG_MIN;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700830 } else {
Siarhei Vishniakou38a6d272020-10-20 20:29:33 -0500831 // Keep waiting. We will drop the event when mNoFocusedWindowTimeoutTime comes.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700832 nextAnrCheck = *mNoFocusedWindowTimeoutTime;
833 }
834 }
835
836 // Check if any connection ANRs are due
837 nextAnrCheck = std::min(nextAnrCheck, mAnrTracker.firstTimeout());
838 if (currentTime < nextAnrCheck) { // most likely scenario
839 return nextAnrCheck; // everything is normal. Let's check again at nextAnrCheck
840 }
841
842 // If we reached here, we have an unresponsive connection.
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -0700843 std::shared_ptr<Connection> connection = getConnectionLocked(mAnrTracker.firstToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700844 if (connection == nullptr) {
845 ALOGE("Could not find connection for entry %" PRId64, mAnrTracker.firstTimeout());
846 return nextAnrCheck;
847 }
848 connection->responsive = false;
849 // Stop waking up for this unresponsive connection
850 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000851 onAnrLocked(connection);
Colin Cross5b799302022-10-18 21:52:41 -0700852 return LLONG_MIN;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700853}
854
Prabir Pradhan1376fcd2022-01-21 09:56:35 -0800855std::chrono::nanoseconds InputDispatcher::getDispatchingTimeoutLocked(
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -0700856 const std::shared_ptr<Connection>& connection) {
Prabir Pradhan1376fcd2022-01-21 09:56:35 -0800857 if (connection->monitor) {
858 return mMonitorDispatchingTimeout;
859 }
860 const sp<WindowInfoHandle> window =
861 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700862 if (window != nullptr) {
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500863 return window->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700864 }
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500865 return DEFAULT_INPUT_DISPATCHING_TIMEOUT;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700866}
867
Michael Wrightd02c5b62014-02-10 15:10:22 -0800868void InputDispatcher::dispatchOnceInnerLocked(nsecs_t* nextWakeupTime) {
869 nsecs_t currentTime = now();
870
Jeff Browndc5992e2014-04-11 01:27:26 -0700871 // Reset the key repeat timer whenever normal dispatch is suspended while the
872 // device is in a non-interactive state. This is to ensure that we abort a key
873 // repeat if the device is just coming out of sleep.
874 if (!mDispatchEnabled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800875 resetKeyRepeatLocked();
876 }
877
878 // If dispatching is frozen, do not process timeouts or try to deliver any new events.
879 if (mDispatchFrozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +0100880 if (DEBUG_FOCUS) {
881 ALOGD("Dispatch frozen. Waiting some more.");
882 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800883 return;
884 }
885
886 // Optimize latency of app switches.
887 // Essentially we start a short timeout when an app switch key (HOME / ENDCALL) has
888 // been pressed. When it expires, we preempt dispatch and drop all other pending events.
889 bool isAppSwitchDue = mAppSwitchDueTime <= currentTime;
890 if (mAppSwitchDueTime < *nextWakeupTime) {
891 *nextWakeupTime = mAppSwitchDueTime;
892 }
893
894 // Ready to start a new event.
895 // If we don't already have a pending event, go grab one.
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700896 if (!mPendingEvent) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700897 if (mInboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800898 if (isAppSwitchDue) {
899 // The inbound queue is empty so the app switch key we were waiting
900 // for will never arrive. Stop waiting for it.
901 resetPendingAppSwitchLocked(false);
902 isAppSwitchDue = false;
903 }
904
905 // Synthesize a key repeat if appropriate.
906 if (mKeyRepeatState.lastKeyEntry) {
907 if (currentTime >= mKeyRepeatState.nextRepeatTime) {
908 mPendingEvent = synthesizeKeyRepeatLocked(currentTime);
909 } else {
910 if (mKeyRepeatState.nextRepeatTime < *nextWakeupTime) {
911 *nextWakeupTime = mKeyRepeatState.nextRepeatTime;
912 }
913 }
914 }
915
916 // Nothing to do if there is no pending event.
917 if (!mPendingEvent) {
918 return;
919 }
920 } else {
921 // Inbound queue has at least one entry.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700922 mPendingEvent = mInboundQueue.front();
923 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800924 traceInboundQueueLengthLocked();
925 }
926
927 // Poke user activity for this event.
928 if (mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700929 pokeUserActivityLocked(*mPendingEvent);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800930 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800931 }
932
933 // Now we have an event to dispatch.
934 // All events are eventually dequeued and processed this way, even if we intend to drop them.
Yi Kong9b14ac62018-07-17 13:48:38 -0700935 ALOG_ASSERT(mPendingEvent != nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800936 bool done = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700937 DropReason dropReason = DropReason::NOT_DROPPED;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800938 if (!(mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700939 dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800940 } else if (!mDispatchEnabled) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700941 dropReason = DropReason::DISABLED;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800942 }
943
944 if (mNextUnblockedEvent == mPendingEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -0700945 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800946 }
947
948 switch (mPendingEvent->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700949 case EventEntry::Type::CONFIGURATION_CHANGED: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700950 const ConfigurationChangedEntry& typedEntry =
951 static_cast<const ConfigurationChangedEntry&>(*mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700952 done = dispatchConfigurationChangedLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700953 dropReason = DropReason::NOT_DROPPED; // configuration changes are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700954 break;
955 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800956
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700957 case EventEntry::Type::DEVICE_RESET: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700958 const DeviceResetEntry& typedEntry =
959 static_cast<const DeviceResetEntry&>(*mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700960 done = dispatchDeviceResetLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700961 dropReason = DropReason::NOT_DROPPED; // device resets are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700962 break;
963 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800964
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100965 case EventEntry::Type::FOCUS: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700966 std::shared_ptr<FocusEntry> typedEntry =
967 std::static_pointer_cast<FocusEntry>(mPendingEvent);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100968 dispatchFocusLocked(currentTime, typedEntry);
969 done = true;
970 dropReason = DropReason::NOT_DROPPED; // focus events are never dropped
971 break;
972 }
973
Antonio Kantek7242d8b2021-08-05 16:07:20 -0700974 case EventEntry::Type::TOUCH_MODE_CHANGED: {
975 const auto typedEntry = std::static_pointer_cast<TouchModeEntry>(mPendingEvent);
976 dispatchTouchModeChangeLocked(currentTime, typedEntry);
977 done = true;
978 dropReason = DropReason::NOT_DROPPED; // touch mode events are never dropped
979 break;
980 }
981
Prabir Pradhan99987712020-11-10 18:43:05 -0800982 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
983 const auto typedEntry =
984 std::static_pointer_cast<PointerCaptureChangedEntry>(mPendingEvent);
985 dispatchPointerCaptureChangedLocked(currentTime, typedEntry, dropReason);
986 done = true;
987 break;
988 }
989
arthurhungb89ccb02020-12-30 16:19:01 +0800990 case EventEntry::Type::DRAG: {
991 std::shared_ptr<DragEntry> typedEntry =
992 std::static_pointer_cast<DragEntry>(mPendingEvent);
993 dispatchDragLocked(currentTime, typedEntry);
994 done = true;
995 break;
996 }
997
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700998 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700999 std::shared_ptr<KeyEntry> keyEntry = std::static_pointer_cast<KeyEntry>(mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001000 if (isAppSwitchDue) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001001 if (isAppSwitchKeyEvent(*keyEntry)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001002 resetPendingAppSwitchLocked(true);
1003 isAppSwitchDue = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001004 } else if (dropReason == DropReason::NOT_DROPPED) {
1005 dropReason = DropReason::APP_SWITCH;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001006 }
1007 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001008 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *keyEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001009 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001010 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001011 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
1012 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001013 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001014 done = dispatchKeyLocked(currentTime, keyEntry, &dropReason, nextWakeupTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001015 break;
1016 }
1017
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001018 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001019 std::shared_ptr<MotionEntry> motionEntry =
1020 std::static_pointer_cast<MotionEntry>(mPendingEvent);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001021 if (dropReason == DropReason::NOT_DROPPED && isAppSwitchDue) {
1022 dropReason = DropReason::APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001023 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001024 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *motionEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001025 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001026 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001027 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
1028 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001029 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001030 done = dispatchMotionLocked(currentTime, motionEntry, &dropReason, nextWakeupTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001031 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001032 }
Chris Yef59a2f42020-10-16 12:55:26 -07001033
1034 case EventEntry::Type::SENSOR: {
1035 std::shared_ptr<SensorEntry> sensorEntry =
1036 std::static_pointer_cast<SensorEntry>(mPendingEvent);
1037 if (dropReason == DropReason::NOT_DROPPED && isAppSwitchDue) {
1038 dropReason = DropReason::APP_SWITCH;
1039 }
1040 // Sensor timestamps use SYSTEM_TIME_BOOTTIME time base, so we can't use
1041 // 'currentTime' here, get SYSTEM_TIME_BOOTTIME instead.
1042 nsecs_t bootTime = systemTime(SYSTEM_TIME_BOOTTIME);
1043 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(bootTime, *sensorEntry)) {
1044 dropReason = DropReason::STALE;
1045 }
1046 dispatchSensorLocked(currentTime, sensorEntry, &dropReason, nextWakeupTime);
1047 done = true;
1048 break;
1049 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001050 }
1051
1052 if (done) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001053 if (dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001054 dropInboundEventLocked(*mPendingEvent, dropReason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001055 }
Michael Wright3a981722015-06-10 15:26:13 +01001056 mLastDropReason = dropReason;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001057
1058 releasePendingEventLocked();
Colin Cross5b799302022-10-18 21:52:41 -07001059 *nextWakeupTime = LLONG_MIN; // force next poll to wake up immediately
Michael Wrightd02c5b62014-02-10 15:10:22 -08001060 }
1061}
1062
Siarhei Vishniakou289e9242022-02-15 14:50:16 -08001063bool InputDispatcher::isStaleEvent(nsecs_t currentTime, const EventEntry& entry) {
1064 return std::chrono::nanoseconds(currentTime - entry.eventTime) >= mStaleEventTimeout;
1065}
1066
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001067/**
1068 * Return true if the events preceding this incoming motion event should be dropped
1069 * Return false otherwise (the default behaviour)
1070 */
1071bool InputDispatcher::shouldPruneInboundQueueLocked(const MotionEntry& motionEntry) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001072 const bool isPointerDownEvent = motionEntry.action == AMOTION_EVENT_ACTION_DOWN &&
Prabir Pradhanaa561d12021-09-24 06:57:33 -07001073 isFromSource(motionEntry.source, AINPUT_SOURCE_CLASS_POINTER);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001074
1075 // Optimize case where the current application is unresponsive and the user
1076 // decides to touch a window in a different application.
1077 // If the application takes too long to catch up then we drop all events preceding
1078 // the touch into the other window.
1079 if (isPointerDownEvent && mAwaitedFocusedApplication != nullptr) {
Siarhei Vishniakou9306c382022-09-30 15:30:31 -07001080 const int32_t displayId = motionEntry.displayId;
1081 const auto [x, y] = resolveTouchedPosition(motionEntry);
Harry Cutts33476232023-01-30 19:57:29 +00001082 const bool isStylus = isPointerFromStylus(motionEntry, /*pointerIndex=*/0);
Siarhei Vishniakou9306c382022-09-30 15:30:31 -07001083
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08001084 auto [touchedWindowHandle, _] = findTouchedWindowAtLocked(displayId, x, y, isStylus);
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001085 if (touchedWindowHandle != nullptr &&
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001086 touchedWindowHandle->getApplicationToken() !=
1087 mAwaitedFocusedApplication->getApplicationToken()) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001088 // User touched a different application than the one we are waiting on.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001089 ALOGI("Pruning input queue because user touched a different application while waiting "
1090 "for %s",
1091 mAwaitedFocusedApplication->getName().c_str());
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001092 return true;
1093 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001094
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08001095 // Alternatively, maybe there's a spy window that could handle this event.
1096 const std::vector<sp<WindowInfoHandle>> touchedSpies =
1097 findTouchedSpyWindowsAtLocked(displayId, x, y, isStylus);
1098 for (const auto& windowHandle : touchedSpies) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07001099 const std::shared_ptr<Connection> connection =
1100 getConnectionLocked(windowHandle->getToken());
Siarhei Vishniakou34ed4d42020-06-18 00:43:02 +00001101 if (connection != nullptr && connection->responsive) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08001102 // This spy window could take more input. Drop all events preceding this
1103 // event, so that the spy window can get a chance to receive the stream.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001104 ALOGW("Pruning the input queue because %s is unresponsive, but we have a "
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08001105 "responsive spy window that may handle the event.",
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001106 mAwaitedFocusedApplication->getName().c_str());
1107 return true;
1108 }
1109 }
1110 }
1111
1112 // Prevent getting stuck: if we have a pending key event, and some motion events that have not
1113 // yet been processed by some connections, the dispatcher will wait for these motion
1114 // events to be processed before dispatching the key event. This is because these motion events
1115 // may cause a new window to be launched, which the user might expect to receive focus.
1116 // To prevent waiting forever for such events, just send the key to the currently focused window
1117 if (isPointerDownEvent && mKeyIsWaitingForEventsTimeout) {
1118 ALOGD("Received a new pointer down event, stop waiting for events to process and "
1119 "just send the pending key event to the focused window.");
1120 mKeyIsWaitingForEventsTimeout = now();
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001121 }
1122 return false;
1123}
1124
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001125bool InputDispatcher::enqueueInboundEventLocked(std::unique_ptr<EventEntry> newEntry) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001126 bool needWake = mInboundQueue.empty();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001127 mInboundQueue.push_back(std::move(newEntry));
1128 EventEntry& entry = *(mInboundQueue.back());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001129 traceInboundQueueLengthLocked();
1130
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001131 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001132 case EventEntry::Type::KEY: {
Prabir Pradhan5735a322022-04-11 17:23:34 +00001133 LOG_ALWAYS_FATAL_IF((entry.policyFlags & POLICY_FLAG_TRUSTED) == 0,
1134 "Unexpected untrusted event.");
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001135 // Optimize app switch latency.
1136 // If the application takes too long to catch up then we drop all events preceding
1137 // the app switch key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001138 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001139 if (isAppSwitchKeyEvent(keyEntry)) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001140 if (keyEntry.action == AKEY_EVENT_ACTION_DOWN) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001141 mAppSwitchSawKeyDown = true;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001142 } else if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001143 if (mAppSwitchSawKeyDown) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001144 if (DEBUG_APP_SWITCH) {
1145 ALOGD("App switch is pending!");
1146 }
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001147 mAppSwitchDueTime = keyEntry.eventTime + APP_SWITCH_TIMEOUT;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001148 mAppSwitchSawKeyDown = false;
1149 needWake = true;
1150 }
1151 }
1152 }
Arthur Hung2ee6d0b2022-03-03 20:19:38 +08001153
1154 // If a new up event comes in, and the pending event with same key code has been asked
1155 // to try again later because of the policy. We have to reset the intercept key wake up
1156 // time for it may have been handled in the policy and could be dropped.
1157 if (keyEntry.action == AKEY_EVENT_ACTION_UP && mPendingEvent &&
1158 mPendingEvent->type == EventEntry::Type::KEY) {
1159 KeyEntry& pendingKey = static_cast<KeyEntry&>(*mPendingEvent);
1160 if (pendingKey.keyCode == keyEntry.keyCode &&
1161 pendingKey.interceptKeyResult ==
Michael Wright5caf55a2022-11-24 22:31:42 +00001162 KeyEntry::InterceptKeyResult::TRY_AGAIN_LATER) {
1163 pendingKey.interceptKeyResult = KeyEntry::InterceptKeyResult::UNKNOWN;
Arthur Hung2ee6d0b2022-03-03 20:19:38 +08001164 pendingKey.interceptKeyWakeupTime = 0;
1165 needWake = true;
1166 }
1167 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001168 break;
1169 }
1170
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001171 case EventEntry::Type::MOTION: {
Prabir Pradhan5735a322022-04-11 17:23:34 +00001172 LOG_ALWAYS_FATAL_IF((entry.policyFlags & POLICY_FLAG_TRUSTED) == 0,
1173 "Unexpected untrusted event.");
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001174 if (shouldPruneInboundQueueLocked(static_cast<MotionEntry&>(entry))) {
1175 mNextUnblockedEvent = mInboundQueue.back();
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001176 needWake = true;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001177 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001178 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001179 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001180 case EventEntry::Type::FOCUS: {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001181 LOG_ALWAYS_FATAL("Focus events should be inserted using enqueueFocusEventLocked");
1182 break;
1183 }
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001184 case EventEntry::Type::TOUCH_MODE_CHANGED:
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001185 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08001186 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07001187 case EventEntry::Type::SENSOR:
arthurhungb89ccb02020-12-30 16:19:01 +08001188 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
1189 case EventEntry::Type::DRAG: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001190 // nothing to do
1191 break;
1192 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001193 }
1194
1195 return needWake;
1196}
1197
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001198void InputDispatcher::addRecentEventLocked(std::shared_ptr<EventEntry> entry) {
Chris Yef59a2f42020-10-16 12:55:26 -07001199 // Do not store sensor event in recent queue to avoid flooding the queue.
1200 if (entry->type != EventEntry::Type::SENSOR) {
1201 mRecentQueue.push_back(entry);
1202 }
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001203 if (mRecentQueue.size() > RECENT_QUEUE_MAX_SIZE) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001204 mRecentQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001205 }
1206}
1207
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08001208std::pair<sp<WindowInfoHandle>, std::vector<InputTarget>>
Prabir Pradhan82e081e2022-12-06 09:50:09 +00001209InputDispatcher::findTouchedWindowAtLocked(int32_t displayId, float x, float y, bool isStylus,
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08001210 bool ignoreDragWindow) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001211 // Traverse windows from front to back to find touched window.
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08001212 std::vector<InputTarget> outsideTargets;
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001213 const auto& windowHandles = getWindowHandlesLocked(displayId);
chaviw98318de2021-05-19 16:45:23 -05001214 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
arthurhung6d4bed92021-03-17 11:59:33 +08001215 if (ignoreDragWindow && haveSameToken(windowHandle, mDragState->dragWindow)) {
arthurhungb89ccb02020-12-30 16:19:01 +08001216 continue;
1217 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001218
Prabir Pradhan3f90d312021-11-19 03:57:24 -08001219 const WindowInfo& info = *windowHandle->getInfo();
Prabir Pradhan33e3baa2022-12-06 20:30:22 +00001220 if (!info.isSpy() &&
1221 windowAcceptsTouchAt(info, displayId, x, y, isStylus, getTransformLocked(displayId))) {
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08001222 return {windowHandle, outsideTargets};
Prabir Pradhan3f90d312021-11-19 03:57:24 -08001223 }
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001224
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08001225 if (info.inputConfig.test(WindowInfo::InputConfig::WATCH_OUTSIDE_TOUCH)) {
1226 addWindowTargetLocked(windowHandle, InputTarget::Flags::DISPATCH_AS_OUTSIDE,
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08001227 /*pointerIds=*/{}, /*firstDownTimeInTarget=*/std::nullopt,
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08001228 outsideTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001229 }
1230 }
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08001231 return {nullptr, {}};
Michael Wrightd02c5b62014-02-10 15:10:22 -08001232}
1233
Prabir Pradhand65552b2021-10-07 11:23:50 -07001234std::vector<sp<WindowInfoHandle>> InputDispatcher::findTouchedSpyWindowsAtLocked(
Prabir Pradhan82e081e2022-12-06 09:50:09 +00001235 int32_t displayId, float x, float y, bool isStylus) const {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001236 // Traverse windows from front to back and gather the touched spy windows.
1237 std::vector<sp<WindowInfoHandle>> spyWindows;
1238 const auto& windowHandles = getWindowHandlesLocked(displayId);
1239 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
1240 const WindowInfo& info = *windowHandle->getInfo();
1241
Prabir Pradhan33e3baa2022-12-06 20:30:22 +00001242 if (!windowAcceptsTouchAt(info, displayId, x, y, isStylus, getTransformLocked(displayId))) {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001243 continue;
1244 }
1245 if (!info.isSpy()) {
1246 // The first touched non-spy window was found, so return the spy windows touched so far.
1247 return spyWindows;
1248 }
1249 spyWindows.push_back(windowHandle);
1250 }
1251 return spyWindows;
1252}
1253
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001254void InputDispatcher::dropInboundEventLocked(const EventEntry& entry, DropReason dropReason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001255 const char* reason;
1256 switch (dropReason) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001257 case DropReason::POLICY:
Prabir Pradhan65613802023-02-22 23:36:58 +00001258 if (debugInboundEventDetails()) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001259 ALOGD("Dropped event because policy consumed it.");
1260 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001261 reason = "inbound event was dropped because the policy consumed it";
1262 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001263 case DropReason::DISABLED:
1264 if (mLastDropReason != DropReason::DISABLED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001265 ALOGI("Dropped event because input dispatch is disabled.");
1266 }
1267 reason = "inbound event was dropped because input dispatch is disabled";
1268 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001269 case DropReason::APP_SWITCH:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001270 ALOGI("Dropped event because of pending overdue app switch.");
1271 reason = "inbound event was dropped because of pending overdue app switch";
1272 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001273 case DropReason::BLOCKED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001274 ALOGI("Dropped event because the current application is not responding and the user "
1275 "has started interacting with a different application.");
1276 reason = "inbound event was dropped because the current application is not responding "
1277 "and the user has started interacting with a different application";
1278 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001279 case DropReason::STALE:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001280 ALOGI("Dropped event because it is stale.");
1281 reason = "inbound event was dropped because it is stale";
1282 break;
Prabir Pradhan99987712020-11-10 18:43:05 -08001283 case DropReason::NO_POINTER_CAPTURE:
1284 ALOGI("Dropped event because there is no window with Pointer Capture.");
1285 reason = "inbound event was dropped because there is no window with Pointer Capture";
1286 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001287 case DropReason::NOT_DROPPED: {
1288 LOG_ALWAYS_FATAL("Should not be dropping a NOT_DROPPED event");
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001289 return;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001290 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001291 }
1292
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001293 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001294 case EventEntry::Type::KEY: {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001295 CancelationOptions options(CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS, reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001296 synthesizeCancelationEventsForAllConnectionsLocked(options);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001297 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001298 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001299 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001300 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
1301 if (motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001302 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS, reason);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001303 synthesizeCancelationEventsForAllConnectionsLocked(options);
1304 } else {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001305 CancelationOptions options(CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS,
1306 reason);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001307 synthesizeCancelationEventsForAllConnectionsLocked(options);
1308 }
1309 break;
1310 }
Chris Yef59a2f42020-10-16 12:55:26 -07001311 case EventEntry::Type::SENSOR: {
1312 break;
1313 }
arthurhungb89ccb02020-12-30 16:19:01 +08001314 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
1315 case EventEntry::Type::DRAG: {
Prabir Pradhan99987712020-11-10 18:43:05 -08001316 break;
1317 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001318 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001319 case EventEntry::Type::TOUCH_MODE_CHANGED:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001320 case EventEntry::Type::CONFIGURATION_CHANGED:
1321 case EventEntry::Type::DEVICE_RESET: {
Dominik Laskowski75788452021-02-09 18:51:25 -08001322 LOG_ALWAYS_FATAL("Should not drop %s events", ftl::enum_string(entry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001323 break;
1324 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001325 }
1326}
1327
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08001328static bool isAppSwitchKeyCode(int32_t keyCode) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001329 return keyCode == AKEYCODE_HOME || keyCode == AKEYCODE_ENDCALL ||
1330 keyCode == AKEYCODE_APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001331}
1332
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001333bool InputDispatcher::isAppSwitchKeyEvent(const KeyEntry& keyEntry) {
1334 return !(keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) && isAppSwitchKeyCode(keyEntry.keyCode) &&
1335 (keyEntry.policyFlags & POLICY_FLAG_TRUSTED) &&
1336 (keyEntry.policyFlags & POLICY_FLAG_PASS_TO_USER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001337}
1338
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07001339bool InputDispatcher::isAppSwitchPendingLocked() const {
Colin Cross5b799302022-10-18 21:52:41 -07001340 return mAppSwitchDueTime != LLONG_MAX;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001341}
1342
1343void InputDispatcher::resetPendingAppSwitchLocked(bool handled) {
Colin Cross5b799302022-10-18 21:52:41 -07001344 mAppSwitchDueTime = LLONG_MAX;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001345
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001346 if (DEBUG_APP_SWITCH) {
1347 if (handled) {
1348 ALOGD("App switch has arrived.");
1349 } else {
1350 ALOGD("App switch was abandoned.");
1351 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001352 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001353}
1354
Michael Wrightd02c5b62014-02-10 15:10:22 -08001355bool InputDispatcher::haveCommandsLocked() const {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001356 return !mCommandQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001357}
1358
Prabir Pradhancef936d2021-07-21 16:17:52 +00001359bool InputDispatcher::runCommandsLockedInterruptable() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001360 if (mCommandQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001361 return false;
1362 }
1363
1364 do {
Prabir Pradhancef936d2021-07-21 16:17:52 +00001365 auto command = std::move(mCommandQueue.front());
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001366 mCommandQueue.pop_front();
Prabir Pradhancef936d2021-07-21 16:17:52 +00001367 // Commands are run with the lock held, but may release and re-acquire the lock from within.
1368 command();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001369 } while (!mCommandQueue.empty());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001370 return true;
1371}
1372
Prabir Pradhancef936d2021-07-21 16:17:52 +00001373void InputDispatcher::postCommandLocked(Command&& command) {
1374 mCommandQueue.push_back(command);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001375}
1376
1377void InputDispatcher::drainInboundQueueLocked() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001378 while (!mInboundQueue.empty()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001379 std::shared_ptr<EventEntry> entry = mInboundQueue.front();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001380 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001381 releaseInboundEventLocked(entry);
1382 }
1383 traceInboundQueueLengthLocked();
1384}
1385
1386void InputDispatcher::releasePendingEventLocked() {
1387 if (mPendingEvent) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001388 releaseInboundEventLocked(mPendingEvent);
Yi Kong9b14ac62018-07-17 13:48:38 -07001389 mPendingEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001390 }
1391}
1392
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001393void InputDispatcher::releaseInboundEventLocked(std::shared_ptr<EventEntry> entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001394 InjectionState* injectionState = entry->injectionState;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001395 if (injectionState && injectionState->injectionResult == InputEventInjectionResult::PENDING) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001396 if (DEBUG_DISPATCH_CYCLE) {
1397 ALOGD("Injected inbound event was dropped.");
1398 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001399 setInjectionResult(*entry, InputEventInjectionResult::FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001400 }
1401 if (entry == mNextUnblockedEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001402 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001403 }
1404 addRecentEventLocked(entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001405}
1406
1407void InputDispatcher::resetKeyRepeatLocked() {
1408 if (mKeyRepeatState.lastKeyEntry) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001409 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001410 }
1411}
1412
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001413std::shared_ptr<KeyEntry> InputDispatcher::synthesizeKeyRepeatLocked(nsecs_t currentTime) {
1414 std::shared_ptr<KeyEntry> entry = mKeyRepeatState.lastKeyEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001415
Michael Wright2e732952014-09-24 13:26:59 -07001416 uint32_t policyFlags = entry->policyFlags &
1417 (POLICY_FLAG_RAW_MASK | POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_TRUSTED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001418
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001419 std::shared_ptr<KeyEntry> newEntry =
1420 std::make_unique<KeyEntry>(mIdGenerator.nextId(), currentTime, entry->deviceId,
1421 entry->source, entry->displayId, policyFlags, entry->action,
1422 entry->flags, entry->keyCode, entry->scanCode,
1423 entry->metaState, entry->repeatCount + 1, entry->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001424
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001425 newEntry->syntheticRepeat = true;
1426 mKeyRepeatState.lastKeyEntry = newEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001427 mKeyRepeatState.nextRepeatTime = currentTime + mConfig.keyRepeatDelay;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001428 return newEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001429}
1430
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001431bool InputDispatcher::dispatchConfigurationChangedLocked(nsecs_t currentTime,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001432 const ConfigurationChangedEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001433 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1434 ALOGD("dispatchConfigurationChanged - eventTime=%" PRId64, entry.eventTime);
1435 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001436
1437 // Reset key repeating in case a keyboard device was added or removed or something.
1438 resetKeyRepeatLocked();
1439
1440 // Enqueue a command to run outside the lock to tell the policy that the configuration changed.
Prabir Pradhancef936d2021-07-21 16:17:52 +00001441 auto command = [this, eventTime = entry.eventTime]() REQUIRES(mLock) {
1442 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00001443 mPolicy.notifyConfigurationChanged(eventTime);
Prabir Pradhancef936d2021-07-21 16:17:52 +00001444 };
1445 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001446 return true;
1447}
1448
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001449bool InputDispatcher::dispatchDeviceResetLocked(nsecs_t currentTime,
1450 const DeviceResetEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001451 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1452 ALOGD("dispatchDeviceReset - eventTime=%" PRId64 ", deviceId=%d", entry.eventTime,
1453 entry.deviceId);
1454 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001455
liushenxiang42232912021-05-21 20:24:09 +08001456 // Reset key repeating in case a keyboard device was disabled or enabled.
1457 if (mKeyRepeatState.lastKeyEntry && mKeyRepeatState.lastKeyEntry->deviceId == entry.deviceId) {
1458 resetKeyRepeatLocked();
1459 }
1460
Michael Wrightfb04fd52022-11-24 22:31:11 +00001461 CancelationOptions options(CancelationOptions::Mode::CANCEL_ALL_EVENTS, "device was reset");
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001462 options.deviceId = entry.deviceId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001463 synthesizeCancelationEventsForAllConnectionsLocked(options);
Siarhei Vishniakou0686f0c2023-05-02 11:56:15 -07001464
1465 // Remove all active pointers from this device
1466 for (auto& [_, touchState] : mTouchStatesByDisplay) {
1467 touchState.removeAllPointersForDevice(entry.deviceId);
1468 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001469 return true;
1470}
1471
Vishnu Nairad321cd2020-08-20 16:40:21 -07001472void InputDispatcher::enqueueFocusEventLocked(const sp<IBinder>& windowToken, bool hasFocus,
Vishnu Nairc519ff72021-01-21 08:23:08 -08001473 const std::string& reason) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001474 if (mPendingEvent != nullptr) {
1475 // Move the pending event to the front of the queue. This will give the chance
1476 // for the pending event to get dispatched to the newly focused window
1477 mInboundQueue.push_front(mPendingEvent);
1478 mPendingEvent = nullptr;
1479 }
1480
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001481 std::unique_ptr<FocusEntry> focusEntry =
1482 std::make_unique<FocusEntry>(mIdGenerator.nextId(), now(), windowToken, hasFocus,
1483 reason);
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001484
1485 // This event should go to the front of the queue, but behind all other focus events
1486 // Find the last focus event, and insert right after it
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001487 std::deque<std::shared_ptr<EventEntry>>::reverse_iterator it =
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001488 std::find_if(mInboundQueue.rbegin(), mInboundQueue.rend(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001489 [](const std::shared_ptr<EventEntry>& event) {
1490 return event->type == EventEntry::Type::FOCUS;
1491 });
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001492
1493 // Maintain the order of focus events. Insert the entry after all other focus events.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001494 mInboundQueue.insert(it.base(), std::move(focusEntry));
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001495}
1496
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001497void InputDispatcher::dispatchFocusLocked(nsecs_t currentTime, std::shared_ptr<FocusEntry> entry) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05001498 std::shared_ptr<InputChannel> channel = getInputChannelLocked(entry->connectionToken);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001499 if (channel == nullptr) {
1500 return; // Window has gone away
1501 }
1502 InputTarget target;
1503 target.inputChannel = channel;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08001504 target.flags = InputTarget::Flags::DISPATCH_AS_IS;
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001505 entry->dispatchInProgress = true;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00001506 std::string message = std::string("Focus ") + (entry->hasFocus ? "entering " : "leaving ") +
1507 channel->getName();
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07001508 std::string reason = std::string("reason=").append(entry->reason);
1509 android_log_event_list(LOGTAG_INPUT_FOCUS) << message << reason << LOG_ID_EVENTS;
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001510 dispatchEventLocked(currentTime, entry, {target});
1511}
1512
Prabir Pradhan99987712020-11-10 18:43:05 -08001513void InputDispatcher::dispatchPointerCaptureChangedLocked(
1514 nsecs_t currentTime, const std::shared_ptr<PointerCaptureChangedEntry>& entry,
1515 DropReason& dropReason) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001516 dropReason = DropReason::NOT_DROPPED;
1517
Prabir Pradhan99987712020-11-10 18:43:05 -08001518 const bool haveWindowWithPointerCapture = mWindowTokenWithPointerCapture != nullptr;
Prabir Pradhan99987712020-11-10 18:43:05 -08001519 sp<IBinder> token;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001520
1521 if (entry->pointerCaptureRequest.enable) {
1522 // Enable Pointer Capture.
1523 if (haveWindowWithPointerCapture &&
1524 (entry->pointerCaptureRequest == mCurrentPointerCaptureRequest)) {
Prabir Pradhan7092e262022-05-03 16:51:09 +00001525 // This can happen if pointer capture is disabled and re-enabled before we notify the
1526 // app of the state change, so there is no need to notify the app.
1527 ALOGI("Skipping dispatch of Pointer Capture being enabled: no state change.");
1528 return;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001529 }
1530 if (!mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08001531 // This can happen if a window requests capture and immediately releases capture.
1532 ALOGW("No window requested Pointer Capture.");
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001533 dropReason = DropReason::NO_POINTER_CAPTURE;
Prabir Pradhan99987712020-11-10 18:43:05 -08001534 return;
1535 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001536 if (entry->pointerCaptureRequest.seq != mCurrentPointerCaptureRequest.seq) {
1537 ALOGI("Skipping dispatch of Pointer Capture being enabled: sequence number mismatch.");
1538 return;
1539 }
1540
Vishnu Nairc519ff72021-01-21 08:23:08 -08001541 token = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Prabir Pradhan99987712020-11-10 18:43:05 -08001542 LOG_ALWAYS_FATAL_IF(!token, "Cannot find focused window for Pointer Capture.");
1543 mWindowTokenWithPointerCapture = token;
1544 } else {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001545 // Disable Pointer Capture.
1546 // We do not check if the sequence number matches for requests to disable Pointer Capture
1547 // for two reasons:
1548 // 1. Pointer Capture can be disabled by a focus change, which means we can get two entries
1549 // to disable capture with the same sequence number: one generated by
1550 // disablePointerCaptureForcedLocked() and another as an acknowledgement of Pointer
1551 // Capture being disabled in InputReader.
1552 // 2. We respect any request to disable Pointer Capture generated by InputReader, since the
1553 // actual Pointer Capture state that affects events being generated by input devices is
1554 // in InputReader.
1555 if (!haveWindowWithPointerCapture) {
1556 // Pointer capture was already forcefully disabled because of focus change.
1557 dropReason = DropReason::NOT_DROPPED;
1558 return;
1559 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001560 token = mWindowTokenWithPointerCapture;
1561 mWindowTokenWithPointerCapture = nullptr;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001562 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan7d030382020-12-21 07:58:35 -08001563 setPointerCaptureLocked(false);
1564 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001565 }
1566
1567 auto channel = getInputChannelLocked(token);
1568 if (channel == nullptr) {
1569 // Window has gone away, clean up Pointer Capture state.
1570 mWindowTokenWithPointerCapture = nullptr;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001571 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan7d030382020-12-21 07:58:35 -08001572 setPointerCaptureLocked(false);
1573 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001574 return;
1575 }
1576 InputTarget target;
1577 target.inputChannel = channel;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08001578 target.flags = InputTarget::Flags::DISPATCH_AS_IS;
Prabir Pradhan99987712020-11-10 18:43:05 -08001579 entry->dispatchInProgress = true;
1580 dispatchEventLocked(currentTime, entry, {target});
1581
1582 dropReason = DropReason::NOT_DROPPED;
1583}
1584
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001585void InputDispatcher::dispatchTouchModeChangeLocked(nsecs_t currentTime,
1586 const std::shared_ptr<TouchModeEntry>& entry) {
1587 const std::vector<sp<WindowInfoHandle>>& windowHandles =
Antonio Kantek15beb512022-06-13 22:35:41 +00001588 getWindowHandlesLocked(entry->displayId);
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001589 if (windowHandles.empty()) {
1590 return;
1591 }
1592 const std::vector<InputTarget> inputTargets =
1593 getInputTargetsFromWindowHandlesLocked(windowHandles);
1594 if (inputTargets.empty()) {
1595 return;
1596 }
1597 entry->dispatchInProgress = true;
1598 dispatchEventLocked(currentTime, entry, inputTargets);
1599}
1600
1601std::vector<InputTarget> InputDispatcher::getInputTargetsFromWindowHandlesLocked(
1602 const std::vector<sp<WindowInfoHandle>>& windowHandles) const {
1603 std::vector<InputTarget> inputTargets;
1604 for (const sp<WindowInfoHandle>& handle : windowHandles) {
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001605 const sp<IBinder>& token = handle->getToken();
1606 if (token == nullptr) {
1607 continue;
1608 }
1609 std::shared_ptr<InputChannel> channel = getInputChannelLocked(token);
1610 if (channel == nullptr) {
1611 continue; // Window has gone away
1612 }
1613 InputTarget target;
1614 target.inputChannel = channel;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08001615 target.flags = InputTarget::Flags::DISPATCH_AS_IS;
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001616 inputTargets.push_back(target);
1617 }
1618 return inputTargets;
1619}
1620
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001621bool InputDispatcher::dispatchKeyLocked(nsecs_t currentTime, std::shared_ptr<KeyEntry> entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001622 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001623 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001624 if (!entry->dispatchInProgress) {
1625 if (entry->repeatCount == 0 && entry->action == AKEY_EVENT_ACTION_DOWN &&
1626 (entry->policyFlags & POLICY_FLAG_TRUSTED) &&
1627 (!(entry->policyFlags & POLICY_FLAG_DISABLE_KEY_REPEAT))) {
1628 if (mKeyRepeatState.lastKeyEntry &&
Chris Ye2ad95392020-09-01 13:44:44 -07001629 mKeyRepeatState.lastKeyEntry->keyCode == entry->keyCode &&
Michael Wrightd02c5b62014-02-10 15:10:22 -08001630 // We have seen two identical key downs in a row which indicates that the device
1631 // driver is automatically generating key repeats itself. We take note of the
1632 // repeat here, but we disable our own next key repeat timer since it is clear that
1633 // we will not need to synthesize key repeats ourselves.
Chris Ye2ad95392020-09-01 13:44:44 -07001634 mKeyRepeatState.lastKeyEntry->deviceId == entry->deviceId) {
1635 // Make sure we don't get key down from a different device. If a different
1636 // device Id has same key pressed down, the new device Id will replace the
1637 // current one to hold the key repeat with repeat count reset.
1638 // In the future when got a KEY_UP on the device id, drop it and do not
1639 // stop the key repeat on current device.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001640 entry->repeatCount = mKeyRepeatState.lastKeyEntry->repeatCount + 1;
1641 resetKeyRepeatLocked();
Colin Cross5b799302022-10-18 21:52:41 -07001642 mKeyRepeatState.nextRepeatTime = LLONG_MAX; // don't generate repeats ourselves
Michael Wrightd02c5b62014-02-10 15:10:22 -08001643 } else {
1644 // Not a repeat. Save key down state in case we do see a repeat later.
1645 resetKeyRepeatLocked();
1646 mKeyRepeatState.nextRepeatTime = entry->eventTime + mConfig.keyRepeatTimeout;
1647 }
1648 mKeyRepeatState.lastKeyEntry = entry;
Chris Ye2ad95392020-09-01 13:44:44 -07001649 } else if (entry->action == AKEY_EVENT_ACTION_UP && mKeyRepeatState.lastKeyEntry &&
1650 mKeyRepeatState.lastKeyEntry->deviceId != entry->deviceId) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001651 // The key on device 'deviceId' is still down, do not stop key repeat
Prabir Pradhan65613802023-02-22 23:36:58 +00001652 if (debugInboundEventDetails()) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001653 ALOGD("deviceId=%d got KEY_UP as stale", entry->deviceId);
1654 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001655 } else if (!entry->syntheticRepeat) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001656 resetKeyRepeatLocked();
1657 }
1658
1659 if (entry->repeatCount == 1) {
1660 entry->flags |= AKEY_EVENT_FLAG_LONG_PRESS;
1661 } else {
1662 entry->flags &= ~AKEY_EVENT_FLAG_LONG_PRESS;
1663 }
1664
1665 entry->dispatchInProgress = true;
1666
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001667 logOutboundKeyDetails("dispatchKey - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001668 }
1669
1670 // Handle case where the policy asked us to try again later last time.
Michael Wright5caf55a2022-11-24 22:31:42 +00001671 if (entry->interceptKeyResult == KeyEntry::InterceptKeyResult::TRY_AGAIN_LATER) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001672 if (currentTime < entry->interceptKeyWakeupTime) {
1673 if (entry->interceptKeyWakeupTime < *nextWakeupTime) {
1674 *nextWakeupTime = entry->interceptKeyWakeupTime;
1675 }
1676 return false; // wait until next wakeup
1677 }
Michael Wright5caf55a2022-11-24 22:31:42 +00001678 entry->interceptKeyResult = KeyEntry::InterceptKeyResult::UNKNOWN;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001679 entry->interceptKeyWakeupTime = 0;
1680 }
1681
1682 // Give the policy a chance to intercept the key.
Michael Wright5caf55a2022-11-24 22:31:42 +00001683 if (entry->interceptKeyResult == KeyEntry::InterceptKeyResult::UNKNOWN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001684 if (entry->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07001685 sp<IBinder> focusedWindowToken =
Vishnu Nairc519ff72021-01-21 08:23:08 -08001686 mFocusResolver.getFocusedWindowToken(getTargetDisplayId(*entry));
Prabir Pradhancef936d2021-07-21 16:17:52 +00001687
1688 auto command = [this, focusedWindowToken, entry]() REQUIRES(mLock) {
1689 doInterceptKeyBeforeDispatchingCommand(focusedWindowToken, *entry);
1690 };
1691 postCommandLocked(std::move(command));
Josep del Riob3981622023-04-18 15:49:45 +00001692 // Poke user activity for keys not passed to user
1693 pokeUserActivityLocked(*entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001694 return false; // wait for the command to run
1695 } else {
Michael Wright5caf55a2022-11-24 22:31:42 +00001696 entry->interceptKeyResult = KeyEntry::InterceptKeyResult::CONTINUE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001697 }
Michael Wright5caf55a2022-11-24 22:31:42 +00001698 } else if (entry->interceptKeyResult == KeyEntry::InterceptKeyResult::SKIP) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001699 if (*dropReason == DropReason::NOT_DROPPED) {
1700 *dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001701 }
1702 }
1703
1704 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001705 if (*dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001706 setInjectionResult(*entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001707 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
1708 : InputEventInjectionResult::FAILED);
Garfield Tan6a5a14e2020-01-28 13:24:04 -08001709 mReporter->reportDroppedKey(entry->id);
Josep del Riob3981622023-04-18 15:49:45 +00001710 // Poke user activity for undispatched keys
1711 pokeUserActivityLocked(*entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001712 return true;
1713 }
1714
1715 // Identify targets.
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001716 InputEventInjectionResult injectionResult;
1717 sp<WindowInfoHandle> focusedWindow =
1718 findFocusedWindowTargetLocked(currentTime, *entry, nextWakeupTime,
1719 /*byref*/ injectionResult);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001720 if (injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001721 return false;
1722 }
1723
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001724 setInjectionResult(*entry, injectionResult);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001725 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001726 return true;
1727 }
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001728 LOG_ALWAYS_FATAL_IF(focusedWindow == nullptr);
1729
1730 std::vector<InputTarget> inputTargets;
1731 addWindowTargetLocked(focusedWindow,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08001732 InputTarget::Flags::FOREGROUND | InputTarget::Flags::DISPATCH_AS_IS,
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08001733 /*pointerIds=*/{}, getDownTime(*entry), inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001734
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001735 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001736 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001737
1738 // Dispatch the key.
1739 dispatchEventLocked(currentTime, entry, inputTargets);
1740 return true;
1741}
1742
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001743void InputDispatcher::logOutboundKeyDetails(const char* prefix, const KeyEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001744 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1745 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32 ", "
1746 "policyFlags=0x%x, action=0x%x, flags=0x%x, keyCode=0x%x, scanCode=0x%x, "
1747 "metaState=0x%x, repeatCount=%d, downTime=%" PRId64,
1748 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId,
1749 entry.policyFlags, entry.action, entry.flags, entry.keyCode, entry.scanCode,
1750 entry.metaState, entry.repeatCount, entry.downTime);
1751 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001752}
1753
Prabir Pradhancef936d2021-07-21 16:17:52 +00001754void InputDispatcher::dispatchSensorLocked(nsecs_t currentTime,
1755 const std::shared_ptr<SensorEntry>& entry,
Chris Yef59a2f42020-10-16 12:55:26 -07001756 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001757 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1758 ALOGD("notifySensorEvent eventTime=%" PRId64 ", hwTimestamp=%" PRId64 ", deviceId=%d, "
1759 "source=0x%x, sensorType=%s",
1760 entry->eventTime, entry->hwTimestamp, entry->deviceId, entry->source,
Dominik Laskowski75788452021-02-09 18:51:25 -08001761 ftl::enum_string(entry->sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001762 }
Prabir Pradhancef936d2021-07-21 16:17:52 +00001763 auto command = [this, entry]() REQUIRES(mLock) {
1764 scoped_unlock unlock(mLock);
1765
1766 if (entry->accuracyChanged) {
Prabir Pradhana41d2442023-04-20 21:30:40 +00001767 mPolicy.notifySensorAccuracy(entry->deviceId, entry->sensorType, entry->accuracy);
Prabir Pradhancef936d2021-07-21 16:17:52 +00001768 }
Prabir Pradhana41d2442023-04-20 21:30:40 +00001769 mPolicy.notifySensorEvent(entry->deviceId, entry->sensorType, entry->accuracy,
1770 entry->hwTimestamp, entry->values);
Prabir Pradhancef936d2021-07-21 16:17:52 +00001771 };
1772 postCommandLocked(std::move(command));
Chris Yef59a2f42020-10-16 12:55:26 -07001773}
1774
1775bool InputDispatcher::flushSensor(int deviceId, InputDeviceSensorType sensorType) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001776 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1777 ALOGD("flushSensor deviceId=%d, sensorType=%s", deviceId,
Dominik Laskowski75788452021-02-09 18:51:25 -08001778 ftl::enum_string(sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001779 }
Chris Yef59a2f42020-10-16 12:55:26 -07001780 { // acquire lock
1781 std::scoped_lock _l(mLock);
1782
1783 for (auto it = mInboundQueue.begin(); it != mInboundQueue.end(); it++) {
1784 std::shared_ptr<EventEntry> entry = *it;
1785 if (entry->type == EventEntry::Type::SENSOR) {
1786 it = mInboundQueue.erase(it);
1787 releaseInboundEventLocked(entry);
1788 }
1789 }
1790 }
1791 return true;
1792}
1793
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001794bool InputDispatcher::dispatchMotionLocked(nsecs_t currentTime, std::shared_ptr<MotionEntry> entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001795 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001796 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001797 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001798 if (!entry->dispatchInProgress) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001799 entry->dispatchInProgress = true;
1800
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001801 logOutboundMotionDetails("dispatchMotion - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001802 }
1803
1804 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001805 if (*dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001806 setInjectionResult(*entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001807 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
1808 : InputEventInjectionResult::FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001809 return true;
1810 }
1811
Prabir Pradhanaa561d12021-09-24 06:57:33 -07001812 const bool isPointerEvent = isFromSource(entry->source, AINPUT_SOURCE_CLASS_POINTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001813
1814 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001815 std::vector<InputTarget> inputTargets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001816
1817 bool conflictingPointerActions = false;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001818 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001819 if (isPointerEvent) {
1820 // Pointer event. (eg. touchscreen)
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00001821
1822 if (mDragState &&
1823 (entry->action & AMOTION_EVENT_ACTION_MASK) == AMOTION_EVENT_ACTION_POINTER_DOWN) {
1824 // If drag and drop ongoing and pointer down occur: pilfer drag window pointers
1825 pilferPointersLocked(mDragState->dragWindow->getToken());
1826 }
1827
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08001828 inputTargets =
Siarhei Vishniakou4fe57392022-10-25 13:44:30 -07001829 findTouchedWindowTargetsLocked(currentTime, *entry, &conflictingPointerActions,
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001830 /*byref*/ injectionResult);
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08001831 LOG_ALWAYS_FATAL_IF(injectionResult != InputEventInjectionResult::SUCCEEDED &&
1832 !inputTargets.empty());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001833 } else {
1834 // Non touch event. (eg. trackball)
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001835 sp<WindowInfoHandle> focusedWindow =
1836 findFocusedWindowTargetLocked(currentTime, *entry, nextWakeupTime, injectionResult);
1837 if (injectionResult == InputEventInjectionResult::SUCCEEDED) {
1838 LOG_ALWAYS_FATAL_IF(focusedWindow == nullptr);
1839 addWindowTargetLocked(focusedWindow,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08001840 InputTarget::Flags::FOREGROUND |
1841 InputTarget::Flags::DISPATCH_AS_IS,
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08001842 /*pointerIds=*/{}, getDownTime(*entry), inputTargets);
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001843 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001844 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001845 if (injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001846 return false;
1847 }
1848
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001849 setInjectionResult(*entry, injectionResult);
Prabir Pradhan5735a322022-04-11 17:23:34 +00001850 if (injectionResult == InputEventInjectionResult::TARGET_MISMATCH) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001851 return true;
1852 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001853 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001854 CancelationOptions::Mode mode(
1855 isPointerEvent ? CancelationOptions::Mode::CANCEL_POINTER_EVENTS
1856 : CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS);
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001857 CancelationOptions options(mode, "input event injection failed");
1858 synthesizeCancelationEventsForMonitorsLocked(options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001859 return true;
1860 }
1861
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001862 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001863 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001864
1865 // Dispatch the motion.
1866 if (conflictingPointerActions) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001867 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001868 "conflicting pointer actions");
Michael Wrightd02c5b62014-02-10 15:10:22 -08001869 synthesizeCancelationEventsForAllConnectionsLocked(options);
1870 }
1871 dispatchEventLocked(currentTime, entry, inputTargets);
1872 return true;
1873}
1874
chaviw98318de2021-05-19 16:45:23 -05001875void InputDispatcher::enqueueDragEventLocked(const sp<WindowInfoHandle>& windowHandle,
Arthur Hung54745652022-04-20 07:17:41 +00001876 bool isExiting, const int32_t rawX,
1877 const int32_t rawY) {
1878 const vec2 xy = windowHandle->getInfo()->transform.transform(vec2(rawX, rawY));
arthurhungb89ccb02020-12-30 16:19:01 +08001879 std::unique_ptr<DragEntry> dragEntry =
Arthur Hung54745652022-04-20 07:17:41 +00001880 std::make_unique<DragEntry>(mIdGenerator.nextId(), now(), windowHandle->getToken(),
1881 isExiting, xy.x, xy.y);
arthurhungb89ccb02020-12-30 16:19:01 +08001882
1883 enqueueInboundEventLocked(std::move(dragEntry));
1884}
1885
1886void InputDispatcher::dispatchDragLocked(nsecs_t currentTime, std::shared_ptr<DragEntry> entry) {
1887 std::shared_ptr<InputChannel> channel = getInputChannelLocked(entry->connectionToken);
1888 if (channel == nullptr) {
1889 return; // Window has gone away
1890 }
1891 InputTarget target;
1892 target.inputChannel = channel;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08001893 target.flags = InputTarget::Flags::DISPATCH_AS_IS;
arthurhungb89ccb02020-12-30 16:19:01 +08001894 entry->dispatchInProgress = true;
1895 dispatchEventLocked(currentTime, entry, {target});
1896}
1897
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001898void InputDispatcher::logOutboundMotionDetails(const char* prefix, const MotionEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001899 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -08001900 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=%s, displayId=%" PRId32
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001901 ", policyFlags=0x%x, "
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001902 "action=%s, actionButton=0x%x, flags=0x%x, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001903 "metaState=0x%x, buttonState=0x%x,"
1904 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%" PRId64,
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -08001905 prefix, entry.eventTime, entry.deviceId,
1906 inputEventSourceToString(entry.source).c_str(), entry.displayId, entry.policyFlags,
1907 MotionEvent::actionToString(entry.action).c_str(), entry.actionButton, entry.flags,
1908 entry.metaState, entry.buttonState, entry.edgeFlags, entry.xPrecision,
1909 entry.yPrecision, entry.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001910
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001911 for (uint32_t i = 0; i < entry.pointerCount; i++) {
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07001912 ALOGD(" Pointer %d: id=%d, toolType=%s, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001913 "x=%f, y=%f, pressure=%f, size=%f, "
1914 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
1915 "orientation=%f",
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07001916 i, entry.pointerProperties[i].id,
1917 ftl::enum_string(entry.pointerProperties[i].toolType).c_str(),
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001918 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
1919 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
1920 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
1921 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
1922 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
1923 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
1924 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
1925 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
1926 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
1927 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001928 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001929}
1930
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001931void InputDispatcher::dispatchEventLocked(nsecs_t currentTime,
1932 std::shared_ptr<EventEntry> eventEntry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001933 const std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001934 ATRACE_CALL();
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001935 if (DEBUG_DISPATCH_CYCLE) {
1936 ALOGD("dispatchEventToCurrentInputTargets");
1937 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001938
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00001939 updateInteractionTokensLocked(*eventEntry, inputTargets);
1940
Michael Wrightd02c5b62014-02-10 15:10:22 -08001941 ALOG_ASSERT(eventEntry->dispatchInProgress); // should already have been set to true
1942
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001943 pokeUserActivityLocked(*eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001944
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001945 for (const InputTarget& inputTarget : inputTargets) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07001946 std::shared_ptr<Connection> connection =
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07001947 getConnectionLocked(inputTarget.inputChannel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07001948 if (connection != nullptr) {
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08001949 prepareDispatchCycleLocked(currentTime, connection, eventEntry, inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001950 } else {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001951 if (DEBUG_FOCUS) {
1952 ALOGD("Dropping event delivery to target with channel '%s' because it "
1953 "is no longer registered with the input dispatcher.",
1954 inputTarget.inputChannel->getName().c_str());
1955 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001956 }
1957 }
1958}
1959
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07001960void InputDispatcher::cancelEventsForAnrLocked(const std::shared_ptr<Connection>& connection) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001961 // We will not be breaking any connections here, even if the policy wants us to abort dispatch.
1962 // If the policy decides to close the app, we will get a channel removal event via
1963 // unregisterInputChannel, and will clean up the connection that way. We are already not
1964 // sending new pointers to the connection when it blocked, but focused events will continue to
1965 // pile up.
1966 ALOGW("Canceling events for %s because it is unresponsive",
1967 connection->inputChannel->getName().c_str());
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08001968 if (connection->status == Connection::Status::NORMAL) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001969 CancelationOptions options(CancelationOptions::Mode::CANCEL_ALL_EVENTS,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001970 "application not responding");
1971 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001972 }
1973}
1974
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001975void InputDispatcher::resetNoFocusedWindowTimeoutLocked() {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001976 if (DEBUG_FOCUS) {
1977 ALOGD("Resetting ANR timeouts.");
1978 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001979
1980 // Reset input target wait timeout.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001981 mNoFocusedWindowTimeoutTime = std::nullopt;
Chris Yea209fde2020-07-22 13:54:51 -07001982 mAwaitedFocusedApplication.reset();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001983}
1984
Tiger Huang721e26f2018-07-24 22:26:19 +08001985/**
1986 * Get the display id that the given event should go to. If this event specifies a valid display id,
1987 * then it should be dispatched to that display. Otherwise, the event goes to the focused display.
1988 * Focused display is the display that the user most recently interacted with.
1989 */
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001990int32_t InputDispatcher::getTargetDisplayId(const EventEntry& entry) {
Tiger Huang721e26f2018-07-24 22:26:19 +08001991 int32_t displayId;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001992 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001993 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001994 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
1995 displayId = keyEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001996 break;
1997 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001998 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001999 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
2000 displayId = motionEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002001 break;
2002 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00002003 case EventEntry::Type::TOUCH_MODE_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08002004 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002005 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002006 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07002007 case EventEntry::Type::DEVICE_RESET:
arthurhungb89ccb02020-12-30 16:19:01 +08002008 case EventEntry::Type::SENSOR:
2009 case EventEntry::Type::DRAG: {
Dominik Laskowski75788452021-02-09 18:51:25 -08002010 ALOGE("%s events do not have a target display", ftl::enum_string(entry.type).c_str());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002011 return ADISPLAY_ID_NONE;
2012 }
Tiger Huang721e26f2018-07-24 22:26:19 +08002013 }
2014 return displayId == ADISPLAY_ID_NONE ? mFocusedDisplayId : displayId;
2015}
2016
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002017bool InputDispatcher::shouldWaitToSendKeyLocked(nsecs_t currentTime,
2018 const char* focusedWindowName) {
2019 if (mAnrTracker.empty()) {
2020 // already processed all events that we waited for
2021 mKeyIsWaitingForEventsTimeout = std::nullopt;
2022 return false;
2023 }
2024
2025 if (!mKeyIsWaitingForEventsTimeout.has_value()) {
2026 // Start the timer
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00002027 // Wait to send key because there are unprocessed events that may cause focus to change
Siarhei Vishniakou70622952020-07-30 11:17:23 -05002028 mKeyIsWaitingForEventsTimeout = currentTime +
2029 std::chrono::duration_cast<std::chrono::nanoseconds>(KEY_WAITING_FOR_EVENTS_TIMEOUT)
2030 .count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002031 return true;
2032 }
2033
2034 // We still have pending events, and already started the timer
2035 if (currentTime < *mKeyIsWaitingForEventsTimeout) {
2036 return true; // Still waiting
2037 }
2038
2039 // Waited too long, and some connection still hasn't processed all motions
2040 // Just send the key to the focused window
2041 ALOGW("Dispatching key to %s even though there are other unprocessed events",
2042 focusedWindowName);
2043 mKeyIsWaitingForEventsTimeout = std::nullopt;
2044 return false;
2045}
2046
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002047sp<WindowInfoHandle> InputDispatcher::findFocusedWindowTargetLocked(
2048 nsecs_t currentTime, const EventEntry& entry, nsecs_t* nextWakeupTime,
2049 InputEventInjectionResult& outInjectionResult) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002050 std::string reason;
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002051 outInjectionResult = InputEventInjectionResult::FAILED; // Default result
Michael Wrightd02c5b62014-02-10 15:10:22 -08002052
Tiger Huang721e26f2018-07-24 22:26:19 +08002053 int32_t displayId = getTargetDisplayId(entry);
chaviw98318de2021-05-19 16:45:23 -05002054 sp<WindowInfoHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Chris Yea209fde2020-07-22 13:54:51 -07002055 std::shared_ptr<InputApplicationHandle> focusedApplicationHandle =
Tiger Huang721e26f2018-07-24 22:26:19 +08002056 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
2057
Michael Wrightd02c5b62014-02-10 15:10:22 -08002058 // If there is no currently focused window and no focused application
2059 // then drop the event.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002060 if (focusedWindowHandle == nullptr && focusedApplicationHandle == nullptr) {
2061 ALOGI("Dropping %s event because there is no focused window or focused application in "
2062 "display %" PRId32 ".",
Dominik Laskowski75788452021-02-09 18:51:25 -08002063 ftl::enum_string(entry.type).c_str(), displayId);
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002064 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002065 }
2066
Vishnu Nair062a8672021-09-03 16:07:44 -07002067 // Drop key events if requested by input feature
2068 if (focusedWindowHandle != nullptr && shouldDropInput(entry, focusedWindowHandle)) {
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002069 return nullptr;
Vishnu Nair062a8672021-09-03 16:07:44 -07002070 }
2071
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002072 // Compatibility behavior: raise ANR if there is a focused application, but no focused window.
2073 // Only start counting when we have a focused event to dispatch. The ANR is canceled if we
2074 // start interacting with another application via touch (app switch). This code can be removed
2075 // if the "no focused window ANR" is moved to the policy. Input doesn't know whether
2076 // an app is expected to have a focused window.
2077 if (focusedWindowHandle == nullptr && focusedApplicationHandle != nullptr) {
2078 if (!mNoFocusedWindowTimeoutTime.has_value()) {
2079 // We just discovered that there's no focused window. Start the ANR timer
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05002080 std::chrono::nanoseconds timeout = focusedApplicationHandle->getDispatchingTimeout(
2081 DEFAULT_INPUT_DISPATCHING_TIMEOUT);
2082 mNoFocusedWindowTimeoutTime = currentTime + timeout.count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002083 mAwaitedFocusedApplication = focusedApplicationHandle;
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05002084 mAwaitedApplicationDisplayId = displayId;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002085 ALOGW("Waiting because no window has focus but %s may eventually add a "
2086 "window when it finishes starting up. Will wait for %" PRId64 "ms",
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05002087 mAwaitedFocusedApplication->getName().c_str(), millis(timeout));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002088 *nextWakeupTime = *mNoFocusedWindowTimeoutTime;
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002089 outInjectionResult = InputEventInjectionResult::PENDING;
2090 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002091 } else if (currentTime > *mNoFocusedWindowTimeoutTime) {
2092 // Already raised ANR. Drop the event
2093 ALOGE("Dropping %s event because there is no focused window",
Dominik Laskowski75788452021-02-09 18:51:25 -08002094 ftl::enum_string(entry.type).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002095 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002096 } else {
2097 // Still waiting for the focused window
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002098 outInjectionResult = InputEventInjectionResult::PENDING;
2099 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002100 }
2101 }
2102
2103 // we have a valid, non-null focused window
2104 resetNoFocusedWindowTimeoutLocked();
2105
Prabir Pradhan5735a322022-04-11 17:23:34 +00002106 // Verify targeted injection.
2107 if (const auto err = verifyTargetedInjection(focusedWindowHandle, entry); err) {
2108 ALOGW("Dropping injected event: %s", (*err).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002109 outInjectionResult = InputEventInjectionResult::TARGET_MISMATCH;
2110 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002111 }
2112
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002113 if (focusedWindowHandle->getInfo()->inputConfig.test(
2114 WindowInfo::InputConfig::PAUSE_DISPATCHING)) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002115 ALOGI("Waiting because %s is paused", focusedWindowHandle->getName().c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002116 outInjectionResult = InputEventInjectionResult::PENDING;
2117 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002118 }
2119
2120 // If the event is a key event, then we must wait for all previous events to
2121 // complete before delivering it because previous events may have the
2122 // side-effect of transferring focus to a different window and we want to
2123 // ensure that the following keys are sent to the new window.
2124 //
2125 // Suppose the user touches a button in a window then immediately presses "A".
2126 // If the button causes a pop-up window to appear then we want to ensure that
2127 // the "A" key is delivered to the new pop-up window. This is because users
2128 // often anticipate pending UI changes when typing on a keyboard.
2129 // To obtain this behavior, we must serialize key events with respect to all
2130 // prior input events.
2131 if (entry.type == EventEntry::Type::KEY) {
2132 if (shouldWaitToSendKeyLocked(currentTime, focusedWindowHandle->getName().c_str())) {
2133 *nextWakeupTime = *mKeyIsWaitingForEventsTimeout;
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002134 outInjectionResult = InputEventInjectionResult::PENDING;
2135 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002136 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002137 }
2138
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002139 outInjectionResult = InputEventInjectionResult::SUCCEEDED;
2140 return focusedWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002141}
2142
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002143/**
2144 * Given a list of monitors, remove the ones we cannot find a connection for, and the ones
2145 * that are currently unresponsive.
2146 */
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002147std::vector<Monitor> InputDispatcher::selectResponsiveMonitorsLocked(
2148 const std::vector<Monitor>& monitors) const {
2149 std::vector<Monitor> responsiveMonitors;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002150 std::copy_if(monitors.begin(), monitors.end(), std::back_inserter(responsiveMonitors),
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002151 [this](const Monitor& monitor) REQUIRES(mLock) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07002152 std::shared_ptr<Connection> connection =
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002153 getConnectionLocked(monitor.inputChannel->getConnectionToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002154 if (connection == nullptr) {
2155 ALOGE("Could not find connection for monitor %s",
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002156 monitor.inputChannel->getName().c_str());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002157 return false;
2158 }
2159 if (!connection->responsive) {
2160 ALOGW("Unresponsive monitor %s will not get the new gesture",
2161 connection->inputChannel->getName().c_str());
2162 return false;
2163 }
2164 return true;
2165 });
2166 return responsiveMonitors;
2167}
2168
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07002169/**
2170 * In general, touch should be always split between windows. Some exceptions:
2171 * 1. Don't split touch is if we have an active pointer down, and a new pointer is going down that's
2172 * from the same device, *and* the window that's receiving the current pointer does not support
2173 * split touch.
2174 * 2. Don't split mouse events
2175 */
2176bool InputDispatcher::shouldSplitTouch(const TouchState& touchState,
2177 const MotionEntry& entry) const {
2178 if (isFromSource(entry.source, AINPUT_SOURCE_MOUSE)) {
2179 // We should never split mouse events
2180 return false;
2181 }
2182 for (const TouchedWindow& touchedWindow : touchState.windows) {
2183 if (touchedWindow.windowHandle->getInfo()->isSpy()) {
2184 // Spy windows should not affect whether or not touch is split.
2185 continue;
2186 }
2187 if (touchedWindow.windowHandle->getInfo()->supportsSplitTouch()) {
2188 continue;
2189 }
Arthur Hungc539dbb2022-12-08 07:45:36 +00002190 if (touchedWindow.windowHandle->getInfo()->inputConfig.test(
2191 gui::WindowInfo::InputConfig::IS_WALLPAPER)) {
2192 // Wallpaper window should not affect whether or not touch is split
2193 continue;
2194 }
2195
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07002196 // Eventually, touchedWindow will contain the deviceId of each pointer that's currently
2197 // being sent there. For now, use deviceId from touch state.
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08002198 if (entry.deviceId == touchState.deviceId && touchedWindow.pointerIds.any()) {
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07002199 return false;
2200 }
2201 }
2202 return true;
2203}
2204
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002205std::vector<InputTarget> InputDispatcher::findTouchedWindowTargetsLocked(
Siarhei Vishniakou4fe57392022-10-25 13:44:30 -07002206 nsecs_t currentTime, const MotionEntry& entry, bool* outConflictingPointerActions,
2207 InputEventInjectionResult& outInjectionResult) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002208 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002209
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002210 std::vector<InputTarget> targets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002211 // For security reasons, we defer updating the touch state until we are sure that
2212 // event injection will be allowed.
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002213 const int32_t displayId = entry.displayId;
2214 const int32_t action = entry.action;
Siarhei Vishniakoubf880522023-05-01 11:03:22 -07002215 const int32_t maskedAction = MotionEvent::getActionMasked(action);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002216
2217 // Update the touch state as needed based on the properties of the touch event.
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002218 outInjectionResult = InputEventInjectionResult::PENDING;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002219
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002220 // Copy current touch state into tempTouchState.
2221 // This state will be used to update mTouchStatesByDisplay at the end of this function.
2222 // If no state for the specified display exists, then our initial state will be empty.
Yi Kong9b14ac62018-07-17 13:48:38 -07002223 const TouchState* oldState = nullptr;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002224 TouchState tempTouchState;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002225 if (const auto it = mTouchStatesByDisplay.find(displayId); it != mTouchStatesByDisplay.end()) {
2226 oldState = &(it->second);
Prabir Pradhane680f9b2022-02-04 04:24:00 -08002227 tempTouchState = *oldState;
Jeff Brownf086ddb2014-02-11 14:28:48 -08002228 }
2229
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07002230 bool isSplit = shouldSplitTouch(tempTouchState, entry);
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07002231 const bool switchedDevice = (oldState != nullptr) &&
Siarhei Vishniakou5cee1e32022-11-29 12:35:39 -08002232 (oldState->deviceId != entry.deviceId || oldState->source != entry.source);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002233
2234 const bool isHoverAction = (maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE ||
2235 maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2236 maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT);
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002237 // A DOWN could be generated from POINTER_DOWN if the initial pointers did not land into any
2238 // touchable windows.
2239 const bool wasDown = oldState != nullptr && oldState->isDown();
2240 const bool isDown = (maskedAction == AMOTION_EVENT_ACTION_DOWN) ||
2241 (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN && !wasDown);
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07002242 const bool newGesture = isDown || maskedAction == AMOTION_EVENT_ACTION_SCROLL ||
2243 maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2244 maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE;
Prabir Pradhanaa561d12021-09-24 06:57:33 -07002245 const bool isFromMouse = isFromSource(entry.source, AINPUT_SOURCE_MOUSE);
Siarhei Vishniakou5cee1e32022-11-29 12:35:39 -08002246
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002247 // If pointers are already down, let's finish the current gesture and ignore the new events
2248 // from another device. However, if the new event is a down event, let's cancel the current
2249 // touch and let the new one take over.
2250 if (switchedDevice && wasDown && !isDown) {
2251 LOG(INFO) << "Dropping event because a pointer for device " << oldState->deviceId
2252 << " is already down in display " << displayId << ": " << entry.getDescription();
2253 // TODO(b/211379801): test multiple simultaneous input streams.
2254 outInjectionResult = InputEventInjectionResult::FAILED;
2255 return {}; // wrong device
2256 }
2257
Michael Wrightd02c5b62014-02-10 15:10:22 -08002258 if (newGesture) {
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002259 // If a new gesture is starting, clear the touch state completely.
2260 tempTouchState.reset();
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002261 tempTouchState.deviceId = entry.deviceId;
2262 tempTouchState.source = entry.source;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002263 isSplit = false;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04002264 } else if (switchedDevice && maskedAction == AMOTION_EVENT_ACTION_MOVE) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07002265 ALOGI("Dropping move event because a pointer for a different device is already active "
2266 "in display %" PRId32,
2267 displayId);
Siarhei Vishniakou16e4fa02023-02-16 17:48:56 -08002268 // TODO(b/211379801): test multiple simultaneous input streams.
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002269 outInjectionResult = InputEventInjectionResult::FAILED;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002270 return {}; // wrong device
Michael Wrightd02c5b62014-02-10 15:10:22 -08002271 }
2272
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002273 if (isHoverAction) {
2274 // For hover actions, we will treat 'tempTouchState' as a new state, so let's erase
2275 // all of the existing hovering pointers and recompute.
2276 tempTouchState.clearHoveringPointers();
2277 }
2278
Michael Wrightd02c5b62014-02-10 15:10:22 -08002279 if (newGesture || (isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN)) {
2280 /* Case 1: New splittable pointer going down, or need target for hover or scroll. */
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07002281 const auto [x, y] = resolveTouchedPosition(entry);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002282 const int32_t pointerIndex = getMotionEventActionPointerIndex(action);
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002283 // Outside targets should be added upon first dispatched DOWN event. That means, this should
2284 // be a pointer that would generate ACTION_DOWN, *and* touch should not already be down.
Prabir Pradhand65552b2021-10-07 11:23:50 -07002285 const bool isStylus = isPointerFromStylus(entry, pointerIndex);
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002286 auto [newTouchedWindowHandle, outsideTargets] =
2287 findTouchedWindowAtLocked(displayId, x, y, isStylus);
Michael Wright3dd60e22019-03-27 22:06:44 +00002288
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002289 if (isDown) {
2290 targets += outsideTargets;
2291 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002292 // Handle the case where we did not find a window.
Yi Kong9b14ac62018-07-17 13:48:38 -07002293 if (newTouchedWindowHandle == nullptr) {
Prabir Pradhan82e081e2022-12-06 09:50:09 +00002294 ALOGD("No new touched window at (%.1f, %.1f) in display %" PRId32, x, y, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002295 // Try to assign the pointer to the first foreground window we find, if there is one.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002296 newTouchedWindowHandle = tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002297 }
2298
Prabir Pradhan5735a322022-04-11 17:23:34 +00002299 // Verify targeted injection.
2300 if (const auto err = verifyTargetedInjection(newTouchedWindowHandle, entry); err) {
2301 ALOGW("Dropping injected touch event: %s", (*err).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002302 outInjectionResult = os::InputEventInjectionResult::TARGET_MISMATCH;
Prabir Pradhan5735a322022-04-11 17:23:34 +00002303 newTouchedWindowHandle = nullptr;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002304 return {};
Prabir Pradhan5735a322022-04-11 17:23:34 +00002305 }
2306
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002307 // Figure out whether splitting will be allowed for this window.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002308 if (newTouchedWindowHandle != nullptr) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002309 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
2310 // New window supports splitting, but we should never split mouse events.
2311 isSplit = !isFromMouse;
2312 } else if (isSplit) {
2313 // New window does not support splitting but we have already split events.
2314 // Ignore the new window.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002315 newTouchedWindowHandle = nullptr;
2316 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002317 } else {
2318 // No window is touched, so set split to true. This will allow the next pointer down to
Prabir Pradhan713bb3e2021-12-20 02:07:40 -08002319 // be delivered to a new window which supports split touch. Pointers from a mouse device
2320 // should never be split.
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07002321 isSplit = !isFromMouse;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002322 }
2323
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002324 std::vector<sp<WindowInfoHandle>> newTouchedWindows =
Prabir Pradhand65552b2021-10-07 11:23:50 -07002325 findTouchedSpyWindowsAtLocked(displayId, x, y, isStylus);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002326 if (newTouchedWindowHandle != nullptr) {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002327 // Process the foreground window first so that it is the first to receive the event.
2328 newTouchedWindows.insert(newTouchedWindows.begin(), newTouchedWindowHandle);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002329 }
2330
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002331 if (newTouchedWindows.empty()) {
Prabir Pradhan82e081e2022-12-06 09:50:09 +00002332 ALOGI("Dropping event because there is no touchable window at (%.1f, %.1f) on display "
2333 "%d.",
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002334 x, y, displayId);
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002335 outInjectionResult = InputEventInjectionResult::FAILED;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002336 return {};
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002337 }
2338
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002339 for (const sp<WindowInfoHandle>& windowHandle : newTouchedWindows) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07002340 if (!canWindowReceiveMotionLocked(windowHandle, entry)) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002341 continue;
2342 }
2343
Siarhei Vishniakoub681c202023-05-01 11:22:33 -07002344 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2345 maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE) {
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002346 const int32_t pointerId = entry.pointerProperties[0].id;
Siarhei Vishniakoub681c202023-05-01 11:22:33 -07002347 // The "windowHandle" is the target of this hovering pointer.
2348 tempTouchState.addHoveringPointerToWindow(windowHandle, entry.deviceId, pointerId);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002349 }
2350
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002351 // Set target flags.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002352 ftl::Flags<InputTarget::Flags> targetFlags = InputTarget::Flags::DISPATCH_AS_IS;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002353
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002354 if (canReceiveForegroundTouches(*windowHandle->getInfo())) {
2355 // There should only be one touched window that can be "foreground" for the pointer.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002356 targetFlags |= InputTarget::Flags::FOREGROUND;
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002357 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002358
2359 if (isSplit) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002360 targetFlags |= InputTarget::Flags::SPLIT;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002361 }
2362 if (isWindowObscuredAtPointLocked(windowHandle, x, y)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002363 targetFlags |= InputTarget::Flags::WINDOW_IS_OBSCURED;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002364 } else if (isWindowObscuredLocked(windowHandle)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002365 targetFlags |= InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002366 }
Michael Wright3dd60e22019-03-27 22:06:44 +00002367
2368 // Update the temporary touch state.
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08002369 std::bitset<MAX_POINTER_ID + 1> pointerIds;
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002370 if (!isHoverAction) {
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08002371 pointerIds.set(entry.pointerProperties[pointerIndex].id);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002372 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002373
Siarhei Vishniakoue0431e42023-01-28 17:01:39 -08002374 const bool isDownOrPointerDown = maskedAction == AMOTION_EVENT_ACTION_DOWN ||
2375 maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN;
2376
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002377 // TODO(b/211379801): Currently, even if pointerIds are empty (hover case), we would
2378 // still add a window to the touch state. We should avoid doing that, but some of the
2379 // later checks ("at least one foreground window") rely on this in order to dispatch
2380 // the event properly, so that needs to be updated, possibly by looking at InputTargets.
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002381 tempTouchState.addOrUpdateWindow(windowHandle, targetFlags, pointerIds,
Siarhei Vishniakoue0431e42023-01-28 17:01:39 -08002382 isDownOrPointerDown
2383 ? std::make_optional(entry.eventTime)
2384 : std::nullopt);
Arthur Hungc539dbb2022-12-08 07:45:36 +00002385
2386 // If this is the pointer going down and the touched window has a wallpaper
2387 // then also add the touched wallpaper windows so they are locked in for the duration
2388 // of the touch gesture.
2389 // We do not collect wallpapers during HOVER_MOVE or SCROLL because the wallpaper
2390 // engine only supports touch events. We would need to add a mechanism similar
2391 // to View.onGenericMotionEvent to enable wallpapers to handle these events.
Siarhei Vishniakoue0431e42023-01-28 17:01:39 -08002392 if (isDownOrPointerDown) {
Arthur Hungc539dbb2022-12-08 07:45:36 +00002393 if (targetFlags.test(InputTarget::Flags::FOREGROUND) &&
2394 windowHandle->getInfo()->inputConfig.test(
2395 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER)) {
2396 sp<WindowInfoHandle> wallpaper = findWallpaperWindowBelow(windowHandle);
2397 if (wallpaper != nullptr) {
2398 ftl::Flags<InputTarget::Flags> wallpaperFlags =
2399 InputTarget::Flags::WINDOW_IS_OBSCURED |
2400 InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED |
2401 InputTarget::Flags::DISPATCH_AS_IS;
2402 if (isSplit) {
2403 wallpaperFlags |= InputTarget::Flags::SPLIT;
2404 }
2405 tempTouchState.addOrUpdateWindow(wallpaper, wallpaperFlags, pointerIds,
2406 entry.eventTime);
2407 }
2408 }
2409 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002410 }
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00002411
Siarhei Vishniakou060f82b2023-01-27 06:39:14 -08002412 // If a window is already pilfering some pointers, give it this new pointer as well and
2413 // make it pilfering. This will prevent other non-spy windows from getting this pointer,
2414 // which is a specific behaviour that we want.
2415 const int32_t pointerId = entry.pointerProperties[pointerIndex].id;
2416 for (TouchedWindow& touchedWindow : tempTouchState.windows) {
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08002417 if (touchedWindow.pointerIds.test(pointerId) &&
Siarhei Vishniakou060f82b2023-01-27 06:39:14 -08002418 touchedWindow.pilferedPointerIds.count() > 0) {
2419 // This window is already pilfering some pointers, and this new pointer is also
2420 // going to it. Therefore, take over this pointer and don't give it to anyone
2421 // else.
2422 touchedWindow.pilferedPointerIds.set(pointerId);
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00002423 }
2424 }
Siarhei Vishniakou060f82b2023-01-27 06:39:14 -08002425
2426 // Restrict all pilfered pointers to the pilfering windows.
2427 tempTouchState.cancelPointersForNonPilferingWindows();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002428 } else {
2429 /* Case 2: Pointer move, up, cancel or non-splittable pointer down. */
2430
2431 // If the pointer is not currently down, then ignore the event.
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07002432 if (!tempTouchState.isDown() && maskedAction != AMOTION_EVENT_ACTION_HOVER_EXIT) {
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002433 LOG(INFO) << "Dropping event because the pointer is not down or we previously "
2434 "dropped the pointer down event in display "
2435 << displayId << ": " << entry.getDescription();
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002436 outInjectionResult = InputEventInjectionResult::FAILED;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002437 return {};
Michael Wrightd02c5b62014-02-10 15:10:22 -08002438 }
2439
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07002440 // If the pointer is not currently hovering, then ignore the event.
2441 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT) {
2442 const int32_t pointerId = entry.pointerProperties[0].id;
2443 if (oldState == nullptr ||
2444 oldState->getWindowsWithHoveringPointer(entry.deviceId, pointerId).empty()) {
2445 LOG(INFO) << "Dropping event because the hovering pointer is not in any windows in "
2446 "display "
2447 << displayId << ": " << entry.getDescription();
2448 outInjectionResult = InputEventInjectionResult::FAILED;
2449 return {};
2450 }
2451 tempTouchState.removeHoveringPointer(entry.deviceId, pointerId);
2452 }
2453
arthurhung6d4bed92021-03-17 11:59:33 +08002454 addDragEventLocked(entry);
arthurhungb89ccb02020-12-30 16:19:01 +08002455
Michael Wrightd02c5b62014-02-10 15:10:22 -08002456 // Check whether touches should slip outside of the current foreground window.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002457 if (maskedAction == AMOTION_EVENT_ACTION_MOVE && entry.pointerCount == 1 &&
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002458 tempTouchState.isSlippery()) {
Siarhei Vishniakou9306c382022-09-30 15:30:31 -07002459 const auto [x, y] = resolveTouchedPosition(entry);
Harry Cutts33476232023-01-30 19:57:29 +00002460 const bool isStylus = isPointerFromStylus(entry, /*pointerIndex=*/0);
chaviw98318de2021-05-19 16:45:23 -05002461 sp<WindowInfoHandle> oldTouchedWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002462 tempTouchState.getFirstForegroundWindowHandle();
Siarhei Vishniakou0f6558d2023-04-21 12:05:13 -07002463 LOG_ALWAYS_FATAL_IF(oldTouchedWindowHandle == nullptr);
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002464 auto [newTouchedWindowHandle, _] = findTouchedWindowAtLocked(displayId, x, y, isStylus);
Vishnu Nair062a8672021-09-03 16:07:44 -07002465
Prabir Pradhan5735a322022-04-11 17:23:34 +00002466 // Verify targeted injection.
2467 if (const auto err = verifyTargetedInjection(newTouchedWindowHandle, entry); err) {
2468 ALOGW("Dropping injected event: %s", (*err).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002469 outInjectionResult = os::InputEventInjectionResult::TARGET_MISMATCH;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002470 return {};
Prabir Pradhan5735a322022-04-11 17:23:34 +00002471 }
2472
Vishnu Nair062a8672021-09-03 16:07:44 -07002473 // Drop touch events if requested by input feature
2474 if (newTouchedWindowHandle != nullptr &&
2475 shouldDropInput(entry, newTouchedWindowHandle)) {
2476 newTouchedWindowHandle = nullptr;
2477 }
2478
Siarhei Vishniakou0f6558d2023-04-21 12:05:13 -07002479 if (!haveSameToken(oldTouchedWindowHandle, newTouchedWindowHandle)) {
2480 ALOGD("Touch is slipping out of window %s into window %s in display %" PRId32,
2481 oldTouchedWindowHandle->getName().c_str(),
2482 newTouchedWindowHandle->getName().c_str(), displayId);
2483
Michael Wrightd02c5b62014-02-10 15:10:22 -08002484 // Make a slippery exit from the old window.
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08002485 std::bitset<MAX_POINTER_ID + 1> pointerIds;
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002486 const int32_t pointerId = entry.pointerProperties[0].id;
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08002487 pointerIds.set(pointerId);
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002488
2489 const TouchedWindow& touchedWindow =
2490 tempTouchState.getTouchedWindow(oldTouchedWindowHandle);
2491 addWindowTargetLocked(oldTouchedWindowHandle,
2492 InputTarget::Flags::DISPATCH_AS_SLIPPERY_EXIT, pointerIds,
2493 touchedWindow.firstDownTimeInTarget, targets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002494
2495 // Make a slippery entrance into the new window.
2496 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
Prabir Pradhan713bb3e2021-12-20 02:07:40 -08002497 isSplit = !isFromMouse;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002498 }
2499
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002500 ftl::Flags<InputTarget::Flags> targetFlags =
2501 InputTarget::Flags::DISPATCH_AS_SLIPPERY_ENTER;
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002502 if (canReceiveForegroundTouches(*newTouchedWindowHandle->getInfo())) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002503 targetFlags |= InputTarget::Flags::FOREGROUND;
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002504 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002505 if (isSplit) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002506 targetFlags |= InputTarget::Flags::SPLIT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002507 }
2508 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002509 targetFlags |= InputTarget::Flags::WINDOW_IS_OBSCURED;
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002510 } else if (isWindowObscuredLocked(newTouchedWindowHandle)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002511 targetFlags |= InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002512 }
2513
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002514 tempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds,
2515 entry.eventTime);
Arthur Hungc539dbb2022-12-08 07:45:36 +00002516
2517 // Check if the wallpaper window should deliver the corresponding event.
2518 slipWallpaperTouch(targetFlags, oldTouchedWindowHandle, newTouchedWindowHandle,
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002519 tempTouchState, pointerId, targets);
2520 tempTouchState.removeTouchedPointerFromWindow(pointerId, oldTouchedWindowHandle);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002521 }
2522 }
Arthur Hung96483742022-11-15 03:30:48 +00002523
2524 // Update the pointerIds for non-splittable when it received pointer down.
2525 if (!isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN) {
2526 // If no split, we suppose all touched windows should receive pointer down.
2527 const int32_t pointerIndex = getMotionEventActionPointerIndex(action);
2528 for (size_t i = 0; i < tempTouchState.windows.size(); i++) {
2529 TouchedWindow& touchedWindow = tempTouchState.windows[i];
2530 // Ignore drag window for it should just track one pointer.
2531 if (mDragState && mDragState->dragWindow == touchedWindow.windowHandle) {
2532 continue;
2533 }
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08002534 touchedWindow.pointerIds.set(entry.pointerProperties[pointerIndex].id);
Arthur Hung96483742022-11-15 03:30:48 +00002535 }
2536 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002537 }
2538
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002539 // Update dispatching for hover enter and exit.
Sam Dubeyf886dec2023-01-27 13:28:19 +00002540 {
2541 std::vector<TouchedWindow> hoveringWindows =
2542 getHoveringWindowsLocked(oldState, tempTouchState, entry);
2543 for (const TouchedWindow& touchedWindow : hoveringWindows) {
2544 addWindowTargetLocked(touchedWindow.windowHandle, touchedWindow.targetFlags,
2545 touchedWindow.pointerIds, touchedWindow.firstDownTimeInTarget,
2546 targets);
2547 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002548 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002549
Prabir Pradhan5735a322022-04-11 17:23:34 +00002550 // Ensure that all touched windows are valid for injection.
2551 if (entry.injectionState != nullptr) {
2552 std::string errs;
2553 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002554 if (touchedWindow.targetFlags.test(InputTarget::Flags::DISPATCH_AS_OUTSIDE)) {
Prabir Pradhan5735a322022-04-11 17:23:34 +00002555 // Allow ACTION_OUTSIDE events generated by targeted injection to be
2556 // dispatched to any uid, since the coords will be zeroed out later.
2557 continue;
2558 }
2559 const auto err = verifyTargetedInjection(touchedWindow.windowHandle, entry);
2560 if (err) errs += "\n - " + *err;
2561 }
2562 if (!errs.empty()) {
2563 ALOGW("Dropping targeted injection: At least one touched window is not owned by uid "
2564 "%d:%s",
2565 *entry.injectionState->targetUid, errs.c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002566 outInjectionResult = InputEventInjectionResult::TARGET_MISMATCH;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002567 return {};
Prabir Pradhan5735a322022-04-11 17:23:34 +00002568 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002569 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002570
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002571 // Check whether windows listening for outside touches are owned by the same UID. If the owner
2572 // has a different UID, then we will not reveal coordinate information to this window.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002573 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
chaviw98318de2021-05-19 16:45:23 -05002574 sp<WindowInfoHandle> foregroundWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002575 tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002576 if (foregroundWindowHandle) {
2577 const int32_t foregroundWindowUid = foregroundWindowHandle->getInfo()->ownerUid;
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002578 for (InputTarget& target : targets) {
2579 if (target.flags.test(InputTarget::Flags::DISPATCH_AS_OUTSIDE)) {
2580 sp<WindowInfoHandle> targetWindow =
2581 getWindowHandleLocked(target.inputChannel->getConnectionToken());
2582 if (targetWindow->getInfo()->ownerUid != foregroundWindowUid) {
2583 target.flags |= InputTarget::Flags::ZERO_COORDS;
Michael Wright3dd60e22019-03-27 22:06:44 +00002584 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002585 }
2586 }
2587 }
2588 }
2589
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07002590 // Output targets from the touch state.
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002591 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08002592 if (touchedWindow.pointerIds.none() && !touchedWindow.hasHoveringPointers(entry.deviceId)) {
Siarhei Vishniakoue0431e42023-01-28 17:01:39 -08002593 // Windows with hovering pointers are getting persisted inside TouchState.
2594 // Do not send this event to those windows.
2595 continue;
2596 }
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002597 addWindowTargetLocked(touchedWindow.windowHandle, touchedWindow.targetFlags,
2598 touchedWindow.pointerIds, touchedWindow.firstDownTimeInTarget,
2599 targets);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002600 }
Sam Dubey39d37cf2022-12-07 18:05:35 +00002601
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07002602 if (targets.empty()) {
2603 LOG(INFO) << "Dropping event because no targets were found: " << entry.getDescription();
2604 outInjectionResult = InputEventInjectionResult::FAILED;
2605 return {};
2606 }
2607
2608 // If we only have windows getting ACTION_OUTSIDE, then drop the event, because there is no
2609 // window that is actually receiving the entire gesture.
2610 if (std::all_of(targets.begin(), targets.end(), [](const InputTarget& target) {
2611 return target.flags.test(InputTarget::Flags::DISPATCH_AS_OUTSIDE);
2612 })) {
2613 LOG(INFO) << "Dropping event because all windows would just receive ACTION_OUTSIDE: "
2614 << entry.getDescription();
2615 outInjectionResult = InputEventInjectionResult::FAILED;
2616 return {};
2617 }
2618
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002619 outInjectionResult = InputEventInjectionResult::SUCCEEDED;
Sam Dubeyf886dec2023-01-27 13:28:19 +00002620 // Drop the outside or hover touch windows since we will not care about them
2621 // in the next iteration.
2622 tempTouchState.filterNonAsIsTouchWindows();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002623
Michael Wrightd02c5b62014-02-10 15:10:22 -08002624 // Update final pieces of touch state if the injector had permission.
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002625 if (switchedDevice) {
2626 if (DEBUG_FOCUS) {
2627 ALOGD("Conflicting pointer actions: Switched to a different device.");
2628 }
2629 *outConflictingPointerActions = true;
2630 }
2631
2632 if (isHoverAction) {
2633 // Started hovering, therefore no longer down.
Siarhei Vishniakou3ad385b2022-11-04 10:09:53 -07002634 if (oldState && oldState->isDown()) {
Siarhei Vishniakou6e1e9872022-11-08 17:51:35 -08002635 ALOGD_IF(DEBUG_FOCUS,
2636 "Conflicting pointer actions: Hover received while pointer was down.");
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002637 *outConflictingPointerActions = true;
2638 }
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002639 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2640 maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE) {
2641 tempTouchState.deviceId = entry.deviceId;
2642 tempTouchState.source = entry.source;
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002643 }
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002644 } else if (maskedAction == AMOTION_EVENT_ACTION_UP) {
2645 // Pointer went up.
2646 tempTouchState.removeTouchedPointer(entry.pointerProperties[0].id);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002647 } else if (maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002648 // All pointers up or canceled.
2649 tempTouchState.reset();
2650 } else if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
2651 // First pointer went down.
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002652 if (oldState && (oldState->isDown() || oldState->hasHoveringPointers())) {
2653 ALOGD("Conflicting pointer actions: Down received while already down or hovering.");
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002654 *outConflictingPointerActions = true;
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002655 }
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002656 } else if (maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
2657 // One pointer went up.
2658 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
2659 uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002660
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002661 for (size_t i = 0; i < tempTouchState.windows.size();) {
2662 TouchedWindow& touchedWindow = tempTouchState.windows[i];
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08002663 touchedWindow.pointerIds.reset(pointerId);
2664 if (touchedWindow.pointerIds.none()) {
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002665 tempTouchState.windows.erase(tempTouchState.windows.begin() + i);
2666 continue;
2667 }
2668 i += 1;
2669 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002670 }
2671
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002672 // Save changes unless the action was scroll in which case the temporary touch
2673 // state was only valid for this one action.
2674 if (maskedAction != AMOTION_EVENT_ACTION_SCROLL) {
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07002675 if (displayId >= 0) {
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002676 tempTouchState.clearWindowsWithoutPointers();
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002677 mTouchStatesByDisplay[displayId] = tempTouchState;
2678 } else {
2679 mTouchStatesByDisplay.erase(displayId);
2680 }
2681 }
2682
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -08002683 if (tempTouchState.windows.empty()) {
2684 mTouchStatesByDisplay.erase(displayId);
2685 }
2686
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002687 return targets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002688}
2689
arthurhung6d4bed92021-03-17 11:59:33 +08002690void InputDispatcher::finishDragAndDrop(int32_t displayId, float x, float y) {
Prabir Pradhand65552b2021-10-07 11:23:50 -07002691 // Prevent stylus interceptor windows from affecting drag and drop behavior for now, until we
2692 // have an explicit reason to support it.
2693 constexpr bool isStylus = false;
2694
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002695 auto [dropWindow, _] =
Harry Cutts33476232023-01-30 19:57:29 +00002696 findTouchedWindowAtLocked(displayId, x, y, isStylus, /*ignoreDragWindow=*/true);
arthurhung6d4bed92021-03-17 11:59:33 +08002697 if (dropWindow) {
2698 vec2 local = dropWindow->getInfo()->transform.transform(x, y);
Prabir Pradhancef936d2021-07-21 16:17:52 +00002699 sendDropWindowCommandLocked(dropWindow->getToken(), local.x, local.y);
Arthur Hung6d0571e2021-04-09 20:18:16 +08002700 } else {
Arthur Hung54745652022-04-20 07:17:41 +00002701 ALOGW("No window found when drop.");
Prabir Pradhancef936d2021-07-21 16:17:52 +00002702 sendDropWindowCommandLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08002703 }
2704 mDragState.reset();
2705}
2706
2707void InputDispatcher::addDragEventLocked(const MotionEntry& entry) {
Arthur Hung3915c1f2022-05-31 07:17:17 +00002708 if (!mDragState || mDragState->dragWindow->getInfo()->displayId != entry.displayId) {
arthurhungb89ccb02020-12-30 16:19:01 +08002709 return;
2710 }
2711
arthurhung6d4bed92021-03-17 11:59:33 +08002712 if (!mDragState->isStartDrag) {
2713 mDragState->isStartDrag = true;
2714 mDragState->isStylusButtonDownAtStart =
2715 (entry.buttonState & AMOTION_EVENT_BUTTON_STYLUS_PRIMARY) != 0;
2716 }
2717
Arthur Hung54745652022-04-20 07:17:41 +00002718 // Find the pointer index by id.
2719 int32_t pointerIndex = 0;
2720 for (; static_cast<uint32_t>(pointerIndex) < entry.pointerCount; pointerIndex++) {
2721 const PointerProperties& pointerProperties = entry.pointerProperties[pointerIndex];
2722 if (pointerProperties.id == mDragState->pointerId) {
2723 break;
arthurhung6d4bed92021-03-17 11:59:33 +08002724 }
Arthur Hung54745652022-04-20 07:17:41 +00002725 }
arthurhung6d4bed92021-03-17 11:59:33 +08002726
Arthur Hung54745652022-04-20 07:17:41 +00002727 if (uint32_t(pointerIndex) == entry.pointerCount) {
2728 LOG_ALWAYS_FATAL("Should find a valid pointer index by id %d", mDragState->pointerId);
Arthur Hung54745652022-04-20 07:17:41 +00002729 }
2730
2731 const int32_t maskedAction = entry.action & AMOTION_EVENT_ACTION_MASK;
2732 const int32_t x = entry.pointerCoords[pointerIndex].getX();
2733 const int32_t y = entry.pointerCoords[pointerIndex].getY();
2734
2735 switch (maskedAction) {
2736 case AMOTION_EVENT_ACTION_MOVE: {
2737 // Handle the special case : stylus button no longer pressed.
2738 bool isStylusButtonDown =
2739 (entry.buttonState & AMOTION_EVENT_BUTTON_STYLUS_PRIMARY) != 0;
2740 if (mDragState->isStylusButtonDownAtStart && !isStylusButtonDown) {
2741 finishDragAndDrop(entry.displayId, x, y);
2742 return;
2743 }
2744
2745 // Prevent stylus interceptor windows from affecting drag and drop behavior for now,
2746 // until we have an explicit reason to support it.
2747 constexpr bool isStylus = false;
2748
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002749 auto [hoverWindowHandle, _] = findTouchedWindowAtLocked(entry.displayId, x, y, isStylus,
Harry Cutts33476232023-01-30 19:57:29 +00002750 /*ignoreDragWindow=*/true);
Arthur Hung54745652022-04-20 07:17:41 +00002751 // enqueue drag exit if needed.
2752 if (hoverWindowHandle != mDragState->dragHoverWindowHandle &&
2753 !haveSameToken(hoverWindowHandle, mDragState->dragHoverWindowHandle)) {
2754 if (mDragState->dragHoverWindowHandle != nullptr) {
Harry Cutts33476232023-01-30 19:57:29 +00002755 enqueueDragEventLocked(mDragState->dragHoverWindowHandle, /*isExiting=*/true, x,
Arthur Hung54745652022-04-20 07:17:41 +00002756 y);
2757 }
2758 mDragState->dragHoverWindowHandle = hoverWindowHandle;
2759 }
2760 // enqueue drag location if needed.
2761 if (hoverWindowHandle != nullptr) {
Harry Cutts33476232023-01-30 19:57:29 +00002762 enqueueDragEventLocked(hoverWindowHandle, /*isExiting=*/false, x, y);
Arthur Hung54745652022-04-20 07:17:41 +00002763 }
2764 break;
2765 }
2766
2767 case AMOTION_EVENT_ACTION_POINTER_UP:
2768 if (getMotionEventActionPointerIndex(entry.action) != pointerIndex) {
2769 break;
2770 }
2771 // The drag pointer is up.
2772 [[fallthrough]];
2773 case AMOTION_EVENT_ACTION_UP:
2774 finishDragAndDrop(entry.displayId, x, y);
2775 break;
2776 case AMOTION_EVENT_ACTION_CANCEL: {
2777 ALOGD("Receiving cancel when drag and drop.");
2778 sendDropWindowCommandLocked(nullptr, 0, 0);
2779 mDragState.reset();
2780 break;
2781 }
arthurhungb89ccb02020-12-30 16:19:01 +08002782 }
2783}
2784
chaviw98318de2021-05-19 16:45:23 -05002785void InputDispatcher::addWindowTargetLocked(const sp<WindowInfoHandle>& windowHandle,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002786 ftl::Flags<InputTarget::Flags> targetFlags,
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08002787 std::bitset<MAX_POINTER_ID + 1> pointerIds,
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002788 std::optional<nsecs_t> firstDownTimeInTarget,
Siarhei Vishniakouf75cddb2022-10-25 10:42:16 -07002789 std::vector<InputTarget>& inputTargets) const {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002790 std::vector<InputTarget>::iterator it =
2791 std::find_if(inputTargets.begin(), inputTargets.end(),
2792 [&windowHandle](const InputTarget& inputTarget) {
2793 return inputTarget.inputChannel->getConnectionToken() ==
2794 windowHandle->getToken();
2795 });
Chavi Weingarten97b8eec2020-01-09 18:09:08 +00002796
chaviw98318de2021-05-19 16:45:23 -05002797 const WindowInfo* windowInfo = windowHandle->getInfo();
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002798
2799 if (it == inputTargets.end()) {
2800 InputTarget inputTarget;
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05002801 std::shared_ptr<InputChannel> inputChannel =
2802 getInputChannelLocked(windowHandle->getToken());
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002803 if (inputChannel == nullptr) {
2804 ALOGW("Window %s already unregistered input channel", windowHandle->getName().c_str());
2805 return;
2806 }
2807 inputTarget.inputChannel = inputChannel;
2808 inputTarget.flags = targetFlags;
2809 inputTarget.globalScaleFactor = windowInfo->globalScaleFactor;
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002810 inputTarget.firstDownTimeInTarget = firstDownTimeInTarget;
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07002811 const auto& displayInfoIt = mDisplayInfos.find(windowInfo->displayId);
2812 if (displayInfoIt != mDisplayInfos.end()) {
Prabir Pradhanb9b18502021-08-26 12:30:32 -07002813 inputTarget.displayTransform = displayInfoIt->second.transform;
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07002814 } else {
Siarhei Vishniakoua06bb552023-02-07 09:38:56 -08002815 // DisplayInfo not found for this window on display windowInfo->displayId.
2816 // TODO(b/198444055): Make this an error message after 'setInputWindows' API is removed.
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07002817 }
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002818 inputTargets.push_back(inputTarget);
2819 it = inputTargets.end() - 1;
2820 }
2821
2822 ALOG_ASSERT(it->flags == targetFlags);
2823 ALOG_ASSERT(it->globalScaleFactor == windowInfo->globalScaleFactor);
2824
chaviw1ff3d1e2020-07-01 15:53:47 -07002825 it->addPointers(pointerIds, windowInfo->transform);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002826}
2827
Michael Wright3dd60e22019-03-27 22:06:44 +00002828void InputDispatcher::addGlobalMonitoringTargetsLocked(std::vector<InputTarget>& inputTargets,
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002829 int32_t displayId) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002830 auto monitorsIt = mGlobalMonitorsByDisplay.find(displayId);
2831 if (monitorsIt == mGlobalMonitorsByDisplay.end()) return;
Michael Wright3dd60e22019-03-27 22:06:44 +00002832
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002833 for (const Monitor& monitor : selectResponsiveMonitorsLocked(monitorsIt->second)) {
2834 InputTarget target;
2835 target.inputChannel = monitor.inputChannel;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002836 target.flags = InputTarget::Flags::DISPATCH_AS_IS;
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002837 // target.firstDownTimeInTarget is not set for global monitors. It is only required in split
2838 // touch and global monitoring works as intended even without setting firstDownTimeInTarget
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002839 if (const auto& it = mDisplayInfos.find(displayId); it != mDisplayInfos.end()) {
2840 target.displayTransform = it->second.transform;
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002841 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002842 target.setDefaultPointerTransform(target.displayTransform);
2843 inputTargets.push_back(target);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002844 }
2845}
2846
Robert Carrc9bf1d32020-04-13 17:21:08 -07002847/**
2848 * Indicate whether one window handle should be considered as obscuring
2849 * another window handle. We only check a few preconditions. Actually
2850 * checking the bounds is left to the caller.
2851 */
chaviw98318de2021-05-19 16:45:23 -05002852static bool canBeObscuredBy(const sp<WindowInfoHandle>& windowHandle,
2853 const sp<WindowInfoHandle>& otherHandle) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002854 // Compare by token so cloned layers aren't counted
2855 if (haveSameToken(windowHandle, otherHandle)) {
2856 return false;
2857 }
2858 auto info = windowHandle->getInfo();
2859 auto otherInfo = otherHandle->getInfo();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002860 if (otherInfo->inputConfig.test(WindowInfo::InputConfig::NOT_VISIBLE)) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002861 return false;
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002862 } else if (otherInfo->alpha == 0 &&
2863 otherInfo->inputConfig.test(WindowInfo::InputConfig::NOT_TOUCHABLE)) {
Bernardo Rufino653d2e02020-10-20 17:32:40 +00002864 // Those act as if they were invisible, so we don't need to flag them.
2865 // We do want to potentially flag touchable windows even if they have 0
2866 // opacity, since they can consume touches and alter the effects of the
2867 // user interaction (eg. apps that rely on
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002868 // Flags::WINDOW_IS_PARTIALLY_OBSCURED should still be told about those
Bernardo Rufino653d2e02020-10-20 17:32:40 +00002869 // windows), hence we also check for FLAG_NOT_TOUCHABLE.
2870 return false;
Bernardo Rufino8007daf2020-09-22 09:40:01 +00002871 } else if (info->ownerUid == otherInfo->ownerUid) {
2872 // If ownerUid is the same we don't generate occlusion events as there
2873 // is no security boundary within an uid.
Robert Carrc9bf1d32020-04-13 17:21:08 -07002874 return false;
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002875 } else if (otherInfo->inputConfig.test(gui::WindowInfo::InputConfig::TRUSTED_OVERLAY)) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002876 return false;
2877 } else if (otherInfo->displayId != info->displayId) {
2878 return false;
2879 }
2880 return true;
2881}
2882
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002883/**
2884 * Returns touch occlusion information in the form of TouchOcclusionInfo. To check if the touch is
2885 * untrusted, one should check:
2886 *
2887 * 1. If result.hasBlockingOcclusion is true.
2888 * If it's, it means the touch should be blocked due to a window with occlusion mode of
2889 * BLOCK_UNTRUSTED.
2890 *
2891 * 2. If result.obscuringOpacity > mMaximumObscuringOpacityForTouch.
2892 * If it is (and 1 is false), then the touch should be blocked because a stack of windows
2893 * (possibly only one) with occlusion mode of USE_OPACITY from one UID resulted in a composed
2894 * obscuring opacity above the threshold. Note that if there was no window of occlusion mode
2895 * USE_OPACITY, result.obscuringOpacity would've been 0 and since
2896 * mMaximumObscuringOpacityForTouch >= 0, the condition above would never be true.
2897 *
2898 * If neither of those is true, then it means the touch can be allowed.
2899 */
2900InputDispatcher::TouchOcclusionInfo InputDispatcher::computeTouchOcclusionInfoLocked(
chaviw98318de2021-05-19 16:45:23 -05002901 const sp<WindowInfoHandle>& windowHandle, int32_t x, int32_t y) const {
2902 const WindowInfo* windowInfo = windowHandle->getInfo();
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002903 int32_t displayId = windowInfo->displayId;
chaviw98318de2021-05-19 16:45:23 -05002904 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002905 TouchOcclusionInfo info;
2906 info.hasBlockingOcclusion = false;
2907 info.obscuringOpacity = 0;
2908 info.obscuringUid = -1;
2909 std::map<int32_t, float> opacityByUid;
chaviw98318de2021-05-19 16:45:23 -05002910 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002911 if (windowHandle == otherHandle) {
2912 break; // All future windows are below us. Exit early.
2913 }
chaviw98318de2021-05-19 16:45:23 -05002914 const WindowInfo* otherInfo = otherHandle->getInfo();
Bernardo Rufino1ff9d592021-01-18 16:58:57 +00002915 if (canBeObscuredBy(windowHandle, otherHandle) && otherInfo->frameContainsPoint(x, y) &&
2916 !haveSameApplicationToken(windowInfo, otherInfo)) {
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002917 if (DEBUG_TOUCH_OCCLUSION) {
2918 info.debugInfo.push_back(
2919 dumpWindowForTouchOcclusion(otherInfo, /* isTouchedWindow */ false));
2920 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002921 // canBeObscuredBy() has returned true above, which means this window is untrusted, so
2922 // we perform the checks below to see if the touch can be propagated or not based on the
2923 // window's touch occlusion mode
2924 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::BLOCK_UNTRUSTED) {
2925 info.hasBlockingOcclusion = true;
2926 info.obscuringUid = otherInfo->ownerUid;
2927 info.obscuringPackage = otherInfo->packageName;
2928 break;
2929 }
2930 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::USE_OPACITY) {
2931 uint32_t uid = otherInfo->ownerUid;
2932 float opacity =
2933 (opacityByUid.find(uid) == opacityByUid.end()) ? 0 : opacityByUid[uid];
2934 // Given windows A and B:
2935 // opacity(A, B) = 1 - [1 - opacity(A)] * [1 - opacity(B)]
2936 opacity = 1 - (1 - opacity) * (1 - otherInfo->alpha);
2937 opacityByUid[uid] = opacity;
2938 if (opacity > info.obscuringOpacity) {
2939 info.obscuringOpacity = opacity;
2940 info.obscuringUid = uid;
2941 info.obscuringPackage = otherInfo->packageName;
2942 }
2943 }
2944 }
2945 }
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002946 if (DEBUG_TOUCH_OCCLUSION) {
2947 info.debugInfo.push_back(
2948 dumpWindowForTouchOcclusion(windowInfo, /* isTouchedWindow */ true));
2949 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002950 return info;
2951}
2952
chaviw98318de2021-05-19 16:45:23 -05002953std::string InputDispatcher::dumpWindowForTouchOcclusion(const WindowInfo* info,
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002954 bool isTouchedWindow) const {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002955 return StringPrintf(INDENT2 "* %spackage=%s/%" PRId32 ", id=%" PRId32 ", mode=%s, alpha=%.2f, "
2956 "frame=[%" PRId32 ",%" PRId32 "][%" PRId32 ",%" PRId32
2957 "], touchableRegion=%s, window={%s}, inputConfig={%s}, "
2958 "hasToken=%s, applicationInfo.name=%s, applicationInfo.token=%s\n",
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002959 isTouchedWindow ? "[TOUCHED] " : "", info->packageName.c_str(),
2960 info->ownerUid, info->id, toString(info->touchOcclusionMode).c_str(),
2961 info->alpha, info->frameLeft, info->frameTop, info->frameRight,
2962 info->frameBottom, dumpRegion(info->touchableRegion).c_str(),
2963 info->name.c_str(), info->inputConfig.string().c_str(),
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002964 toString(info->token != nullptr), info->applicationInfo.name.c_str(),
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07002965 binderToString(info->applicationInfo.token).c_str());
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002966}
2967
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002968bool InputDispatcher::isTouchTrustedLocked(const TouchOcclusionInfo& occlusionInfo) const {
2969 if (occlusionInfo.hasBlockingOcclusion) {
2970 ALOGW("Untrusted touch due to occlusion by %s/%d", occlusionInfo.obscuringPackage.c_str(),
2971 occlusionInfo.obscuringUid);
2972 return false;
2973 }
2974 if (occlusionInfo.obscuringOpacity > mMaximumObscuringOpacityForTouch) {
2975 ALOGW("Untrusted touch due to occlusion by %s/%d (obscuring opacity = "
2976 "%.2f, maximum allowed = %.2f)",
2977 occlusionInfo.obscuringPackage.c_str(), occlusionInfo.obscuringUid,
2978 occlusionInfo.obscuringOpacity, mMaximumObscuringOpacityForTouch);
2979 return false;
2980 }
2981 return true;
2982}
2983
chaviw98318de2021-05-19 16:45:23 -05002984bool InputDispatcher::isWindowObscuredAtPointLocked(const sp<WindowInfoHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002985 int32_t x, int32_t y) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002986 int32_t displayId = windowHandle->getInfo()->displayId;
chaviw98318de2021-05-19 16:45:23 -05002987 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
2988 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002989 if (windowHandle == otherHandle) {
2990 break; // All future windows are below us. Exit early.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002991 }
chaviw98318de2021-05-19 16:45:23 -05002992 const WindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07002993 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08002994 otherInfo->frameContainsPoint(x, y)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002995 return true;
2996 }
2997 }
2998 return false;
2999}
3000
chaviw98318de2021-05-19 16:45:23 -05003001bool InputDispatcher::isWindowObscuredLocked(const sp<WindowInfoHandle>& windowHandle) const {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07003002 int32_t displayId = windowHandle->getInfo()->displayId;
chaviw98318de2021-05-19 16:45:23 -05003003 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
3004 const WindowInfo* windowInfo = windowHandle->getInfo();
3005 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07003006 if (windowHandle == otherHandle) {
3007 break; // All future windows are below us. Exit early.
Michael Wrightcdcd8f22016-03-22 16:52:13 -07003008 }
chaviw98318de2021-05-19 16:45:23 -05003009 const WindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07003010 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08003011 otherInfo->overlaps(windowInfo)) {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07003012 return true;
3013 }
3014 }
3015 return false;
3016}
3017
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08003018std::string InputDispatcher::getApplicationWindowLabel(
chaviw98318de2021-05-19 16:45:23 -05003019 const InputApplicationHandle* applicationHandle, const sp<WindowInfoHandle>& windowHandle) {
Yi Kong9b14ac62018-07-17 13:48:38 -07003020 if (applicationHandle != nullptr) {
3021 if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07003022 return applicationHandle->getName() + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003023 } else {
3024 return applicationHandle->getName();
3025 }
Yi Kong9b14ac62018-07-17 13:48:38 -07003026 } else if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07003027 return windowHandle->getInfo()->applicationInfo.name + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003028 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003029 return "<unknown application or window>";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003030 }
3031}
3032
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003033void InputDispatcher::pokeUserActivityLocked(const EventEntry& eventEntry) {
Antonio Kantekf16f2832021-09-28 04:39:20 +00003034 if (!isUserActivityEvent(eventEntry)) {
3035 // Not poking user activity if the event type does not represent a user activity
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003036 return;
3037 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003038 int32_t displayId = getTargetDisplayId(eventEntry);
chaviw98318de2021-05-19 16:45:23 -05003039 sp<WindowInfoHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Josep del Riob3981622023-04-18 15:49:45 +00003040 const WindowInfo* windowDisablingUserActivityInfo = nullptr;
Tiger Huang721e26f2018-07-24 22:26:19 +08003041 if (focusedWindowHandle != nullptr) {
chaviw98318de2021-05-19 16:45:23 -05003042 const WindowInfo* info = focusedWindowHandle->getInfo();
Prabir Pradhan51e7db02022-02-07 06:02:57 -08003043 if (info->inputConfig.test(WindowInfo::InputConfig::DISABLE_USER_ACTIVITY)) {
Josep del Riob3981622023-04-18 15:49:45 +00003044 windowDisablingUserActivityInfo = info;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003045 }
3046 }
3047
3048 int32_t eventType = USER_ACTIVITY_EVENT_OTHER;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003049 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003050 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003051 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
3052 if (motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003053 return;
3054 }
Josep del Riob3981622023-04-18 15:49:45 +00003055 if (windowDisablingUserActivityInfo != nullptr) {
3056 if (DEBUG_DISPATCH_CYCLE) {
3057 ALOGD("Not poking user activity: disabled by window '%s'.",
3058 windowDisablingUserActivityInfo->name.c_str());
3059 }
3060 return;
3061 }
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003062 if (MotionEvent::isTouchEvent(motionEntry.source, motionEntry.action)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003063 eventType = USER_ACTIVITY_EVENT_TOUCH;
3064 }
3065 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003066 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003067 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003068 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
3069 if (keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003070 return;
3071 }
Josep del Riob3981622023-04-18 15:49:45 +00003072 // If the key code is unknown, we don't consider it user activity
3073 if (keyEntry.keyCode == AKEYCODE_UNKNOWN) {
3074 return;
3075 }
3076 // Don't inhibit events that were intercepted or are not passed to
3077 // the apps, like system shortcuts
3078 if (windowDisablingUserActivityInfo != nullptr &&
3079 keyEntry.interceptKeyResult != KeyEntry::InterceptKeyResult::SKIP &&
3080 keyEntry.policyFlags & POLICY_FLAG_PASS_TO_USER) {
3081 if (DEBUG_DISPATCH_CYCLE) {
3082 ALOGD("Not poking user activity: disabled by window '%s'.",
3083 windowDisablingUserActivityInfo->name.c_str());
3084 }
3085 return;
3086 }
3087
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003088 eventType = USER_ACTIVITY_EVENT_BUTTON;
3089 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003090 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00003091 default: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003092 LOG_ALWAYS_FATAL("%s events are not user activity",
Dominik Laskowski75788452021-02-09 18:51:25 -08003093 ftl::enum_string(eventEntry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003094 break;
3095 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003096 }
3097
Prabir Pradhancef936d2021-07-21 16:17:52 +00003098 auto command = [this, eventTime = eventEntry.eventTime, eventType, displayId]()
3099 REQUIRES(mLock) {
3100 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00003101 mPolicy.pokeUserActivity(eventTime, eventType, displayId);
Prabir Pradhancef936d2021-07-21 16:17:52 +00003102 };
3103 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003104}
3105
3106void InputDispatcher::prepareDispatchCycleLocked(nsecs_t currentTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003107 const std::shared_ptr<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003108 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003109 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003110 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003111 std::string message =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003112 StringPrintf("prepareDispatchCycleLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003113 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00003114 ATRACE_NAME(message.c_str());
3115 }
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003116 if (DEBUG_DISPATCH_CYCLE) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003117 ALOGD("channel '%s' ~ prepareDispatchCycle - flags=%s, "
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08003118 "globalScaleFactor=%f, pointerIds=%s %s",
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003119 connection->getInputChannelName().c_str(), inputTarget.flags.string().c_str(),
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08003120 inputTarget.globalScaleFactor, bitsetToString(inputTarget.pointerIds).c_str(),
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003121 inputTarget.getPointerInfoString().c_str());
3122 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003123
3124 // Skip this event if the connection status is not normal.
3125 // We don't want to enqueue additional outbound events if the connection is broken.
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003126 if (connection->status != Connection::Status::NORMAL) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003127 if (DEBUG_DISPATCH_CYCLE) {
3128 ALOGD("channel '%s' ~ Dropping event because the channel status is %s",
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003129 connection->getInputChannelName().c_str(),
3130 ftl::enum_string(connection->status).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003131 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003132 return;
3133 }
3134
3135 // Split a motion event if needed.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003136 if (inputTarget.flags.test(InputTarget::Flags::SPLIT)) {
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003137 LOG_ALWAYS_FATAL_IF(eventEntry->type != EventEntry::Type::MOTION,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003138 "Entry type %s should not have Flags::SPLIT",
Dominik Laskowski75788452021-02-09 18:51:25 -08003139 ftl::enum_string(eventEntry->type).c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003140
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003141 const MotionEntry& originalMotionEntry = static_cast<const MotionEntry&>(*eventEntry);
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003142 if (inputTarget.pointerIds.count() != originalMotionEntry.pointerCount) {
Siarhei Vishniakou16e4fa02023-02-16 17:48:56 -08003143 if (!inputTarget.firstDownTimeInTarget.has_value()) {
3144 logDispatchStateLocked();
3145 LOG(FATAL) << "Splitting motion events requires a down time to be set for the "
3146 "target on connection "
3147 << connection->getInputChannelName() << " for "
3148 << originalMotionEntry.getDescription();
3149 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003150 std::unique_ptr<MotionEntry> splitMotionEntry =
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00003151 splitMotionEvent(originalMotionEntry, inputTarget.pointerIds,
3152 inputTarget.firstDownTimeInTarget.value());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003153 if (!splitMotionEntry) {
3154 return; // split event was dropped
3155 }
Arthur Hungb3307ee2021-10-14 10:57:37 +00003156 if (splitMotionEntry->action == AMOTION_EVENT_ACTION_CANCEL) {
3157 std::string reason = std::string("reason=pointer cancel on split window");
3158 android_log_event_list(LOGTAG_INPUT_CANCEL)
3159 << connection->getInputChannelName().c_str() << reason << LOG_ID_EVENTS;
3160 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003161 if (DEBUG_FOCUS) {
3162 ALOGD("channel '%s' ~ Split motion event.",
3163 connection->getInputChannelName().c_str());
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003164 logOutboundMotionDetails(" ", *splitMotionEntry);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003165 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003166 enqueueDispatchEntriesLocked(currentTime, connection, std::move(splitMotionEntry),
3167 inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003168 return;
3169 }
3170 }
3171
3172 // Not splitting. Enqueue dispatch entries for the event as is.
3173 enqueueDispatchEntriesLocked(currentTime, connection, eventEntry, inputTarget);
3174}
3175
3176void InputDispatcher::enqueueDispatchEntriesLocked(nsecs_t currentTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003177 const std::shared_ptr<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003178 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003179 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003180 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003181 std::string message =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003182 StringPrintf("enqueueDispatchEntriesLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003183 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00003184 ATRACE_NAME(message.c_str());
3185 }
Siarhei Vishniakou5cee1e32022-11-29 12:35:39 -08003186 LOG_ALWAYS_FATAL_IF(!inputTarget.flags.any(InputTarget::DISPATCH_MASK),
3187 "No dispatch flags are set for %s", eventEntry->getDescription().c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00003188
hongzuo liu95785e22022-09-06 02:51:35 +00003189 const bool wasEmpty = connection->outboundQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003190
3191 // Enqueue dispatch entries for the requested modes.
chaviw8c9cf542019-03-25 13:02:48 -07003192 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003193 InputTarget::Flags::DISPATCH_AS_HOVER_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07003194 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003195 InputTarget::Flags::DISPATCH_AS_OUTSIDE);
chaviw8c9cf542019-03-25 13:02:48 -07003196 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003197 InputTarget::Flags::DISPATCH_AS_HOVER_ENTER);
chaviw8c9cf542019-03-25 13:02:48 -07003198 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003199 InputTarget::Flags::DISPATCH_AS_IS);
chaviw8c9cf542019-03-25 13:02:48 -07003200 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003201 InputTarget::Flags::DISPATCH_AS_SLIPPERY_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07003202 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003203 InputTarget::Flags::DISPATCH_AS_SLIPPERY_ENTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003204
3205 // If the outbound queue was previously empty, start the dispatch cycle going.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003206 if (wasEmpty && !connection->outboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003207 startDispatchCycleLocked(currentTime, connection);
3208 }
3209}
3210
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003211void InputDispatcher::enqueueDispatchEntryLocked(const std::shared_ptr<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003212 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003213 const InputTarget& inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003214 ftl::Flags<InputTarget::Flags> dispatchMode) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003215 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003216 std::string message = StringPrintf("enqueueDispatchEntry(inputChannel=%s, dispatchMode=%s)",
3217 connection->getInputChannelName().c_str(),
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003218 dispatchMode.string().c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00003219 ATRACE_NAME(message.c_str());
3220 }
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003221 ftl::Flags<InputTarget::Flags> inputTargetFlags = inputTarget.flags;
3222 if (!inputTargetFlags.any(dispatchMode)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003223 return;
3224 }
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003225
3226 inputTargetFlags.clear(InputTarget::DISPATCH_MASK);
3227 inputTargetFlags |= dispatchMode;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003228
3229 // This is a new event.
3230 // Enqueue a new dispatch entry onto the outbound queue for this connection.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003231 std::unique_ptr<DispatchEntry> dispatchEntry =
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003232 createDispatchEntry(inputTarget, eventEntry, inputTargetFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003233
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003234 // Use the eventEntry from dispatchEntry since the entry may have changed and can now be a
3235 // different EventEntry than what was passed in.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003236 EventEntry& newEntry = *(dispatchEntry->eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003237 // Apply target flags and update the connection's input state.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003238 switch (newEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003239 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003240 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003241 dispatchEntry->resolvedEventId = keyEntry.id;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003242 dispatchEntry->resolvedAction = keyEntry.action;
3243 dispatchEntry->resolvedFlags = keyEntry.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003244
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003245 if (!connection->inputState.trackKey(keyEntry, dispatchEntry->resolvedAction,
3246 dispatchEntry->resolvedFlags)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003247 if (DEBUG_DISPATCH_CYCLE) {
3248 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent key "
3249 "event",
3250 connection->getInputChannelName().c_str());
3251 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003252 return; // skip the inconsistent event
3253 }
3254 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003255 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003256
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003257 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003258 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003259 // Assign a default value to dispatchEntry that will never be generated by InputReader,
3260 // and assign a InputDispatcher value if it doesn't change in the if-else chain below.
3261 constexpr int32_t DEFAULT_RESOLVED_EVENT_ID =
3262 static_cast<int32_t>(IdGenerator::Source::OTHER);
3263 dispatchEntry->resolvedEventId = DEFAULT_RESOLVED_EVENT_ID;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003264 if (dispatchMode.test(InputTarget::Flags::DISPATCH_AS_OUTSIDE)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003265 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_OUTSIDE;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003266 } else if (dispatchMode.test(InputTarget::Flags::DISPATCH_AS_HOVER_EXIT)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003267 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_EXIT;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003268 } else if (dispatchMode.test(InputTarget::Flags::DISPATCH_AS_HOVER_ENTER)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003269 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003270 } else if (dispatchMode.test(InputTarget::Flags::DISPATCH_AS_SLIPPERY_EXIT)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003271 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_CANCEL;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003272 } else if (dispatchMode.test(InputTarget::Flags::DISPATCH_AS_SLIPPERY_ENTER)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003273 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_DOWN;
3274 } else {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003275 dispatchEntry->resolvedAction = motionEntry.action;
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003276 dispatchEntry->resolvedEventId = motionEntry.id;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003277 }
3278 if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_HOVER_MOVE &&
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003279 !connection->inputState.isHovering(motionEntry.deviceId, motionEntry.source,
3280 motionEntry.displayId)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003281 if (DEBUG_DISPATCH_CYCLE) {
3282 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: filling in missing hover "
3283 "enter event",
3284 connection->getInputChannelName().c_str());
3285 }
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00003286 // We keep the 'resolvedEventId' here equal to the original 'motionEntry.id' because
3287 // this is a one-to-one event conversion.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003288 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
3289 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003290
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003291 dispatchEntry->resolvedFlags = motionEntry.flags;
Siarhei Vishniakou1ae72f12023-01-29 12:55:30 -08003292 if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_CANCEL) {
3293 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_CANCELED;
3294 }
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003295 if (dispatchEntry->targetFlags.test(InputTarget::Flags::WINDOW_IS_OBSCURED)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003296 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED;
3297 }
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003298 if (dispatchEntry->targetFlags.test(InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003299 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
3300 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003301
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003302 if (!connection->inputState.trackMotion(motionEntry, dispatchEntry->resolvedAction,
3303 dispatchEntry->resolvedFlags)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003304 if (DEBUG_DISPATCH_CYCLE) {
3305 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent motion "
3306 "event",
3307 connection->getInputChannelName().c_str());
3308 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003309 return; // skip the inconsistent event
3310 }
3311
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003312 dispatchEntry->resolvedEventId =
3313 dispatchEntry->resolvedEventId == DEFAULT_RESOLVED_EVENT_ID
3314 ? mIdGenerator.nextId()
3315 : motionEntry.id;
3316 if (ATRACE_ENABLED() && dispatchEntry->resolvedEventId != motionEntry.id) {
3317 std::string message = StringPrintf("Transmute MotionEvent(id=0x%" PRIx32
3318 ") to MotionEvent(id=0x%" PRIx32 ").",
3319 motionEntry.id, dispatchEntry->resolvedEventId);
3320 ATRACE_NAME(message.c_str());
3321 }
3322
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08003323 if ((motionEntry.flags & AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE) &&
3324 (motionEntry.policyFlags & POLICY_FLAG_TRUSTED)) {
3325 // Skip reporting pointer down outside focus to the policy.
3326 break;
3327 }
3328
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003329 dispatchPointerDownOutsideFocus(motionEntry.source, dispatchEntry->resolvedAction,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003330 inputTarget.inputChannel->getConnectionToken());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003331
3332 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003333 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003334 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003335 case EventEntry::Type::TOUCH_MODE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08003336 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
3337 case EventEntry::Type::DRAG: {
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003338 break;
3339 }
Chris Yef59a2f42020-10-16 12:55:26 -07003340 case EventEntry::Type::SENSOR: {
3341 LOG_ALWAYS_FATAL("SENSOR events should not go to apps via input channel");
3342 break;
3343 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003344 case EventEntry::Type::CONFIGURATION_CHANGED:
3345 case EventEntry::Type::DEVICE_RESET: {
3346 LOG_ALWAYS_FATAL("%s events should not go to apps",
Dominik Laskowski75788452021-02-09 18:51:25 -08003347 ftl::enum_string(newEntry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003348 break;
3349 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003350 }
3351
3352 // Remember that we are waiting for this dispatch to complete.
3353 if (dispatchEntry->hasForegroundTarget()) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003354 incrementPendingForegroundDispatches(newEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003355 }
3356
3357 // Enqueue the dispatch entry.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003358 connection->outboundQueue.push_back(dispatchEntry.release());
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003359 traceOutboundQueueLength(*connection);
chaviw8c9cf542019-03-25 13:02:48 -07003360}
3361
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003362/**
3363 * This function is purely for debugging. It helps us understand where the user interaction
3364 * was taking place. For example, if user is touching launcher, we will see a log that user
3365 * started interacting with launcher. In that example, the event would go to the wallpaper as well.
3366 * We will see both launcher and wallpaper in that list.
3367 * Once the interaction with a particular set of connections starts, no new logs will be printed
3368 * until the set of interacted connections changes.
3369 *
3370 * The following items are skipped, to reduce the logspam:
3371 * ACTION_OUTSIDE: any windows that are receiving ACTION_OUTSIDE are not logged
3372 * ACTION_UP: any windows that receive ACTION_UP are not logged (for both keys and motions).
3373 * This includes situations like the soft BACK button key. When the user releases (lifts up the
3374 * finger) the back button, then navigation bar will inject KEYCODE_BACK with ACTION_UP.
3375 * Both of those ACTION_UP events would not be logged
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003376 */
3377void InputDispatcher::updateInteractionTokensLocked(const EventEntry& entry,
3378 const std::vector<InputTarget>& targets) {
3379 // Skip ACTION_UP events, and all events other than keys and motions
3380 if (entry.type == EventEntry::Type::KEY) {
3381 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
3382 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
3383 return;
3384 }
3385 } else if (entry.type == EventEntry::Type::MOTION) {
3386 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
3387 if (motionEntry.action == AMOTION_EVENT_ACTION_UP ||
3388 motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
3389 return;
3390 }
3391 } else {
3392 return; // Not a key or a motion
3393 }
3394
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07003395 std::unordered_set<sp<IBinder>, StrongPointerHash<IBinder>> newConnectionTokens;
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003396 std::vector<std::shared_ptr<Connection>> newConnections;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003397 for (const InputTarget& target : targets) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003398 if (target.flags.test(InputTarget::Flags::DISPATCH_AS_OUTSIDE)) {
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003399 continue; // Skip windows that receive ACTION_OUTSIDE
3400 }
3401
3402 sp<IBinder> token = target.inputChannel->getConnectionToken();
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003403 std::shared_ptr<Connection> connection = getConnectionLocked(token);
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003404 if (connection == nullptr) {
3405 continue;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003406 }
3407 newConnectionTokens.insert(std::move(token));
3408 newConnections.emplace_back(connection);
3409 }
3410 if (newConnectionTokens == mInteractionConnectionTokens) {
3411 return; // no change
3412 }
3413 mInteractionConnectionTokens = newConnectionTokens;
3414
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003415 std::string targetList;
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003416 for (const std::shared_ptr<Connection>& connection : newConnections) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003417 targetList += connection->getWindowName() + ", ";
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003418 }
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003419 std::string message = "Interaction with: " + targetList;
3420 if (targetList.empty()) {
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003421 message += "<none>";
3422 }
3423 android_log_event_list(LOGTAG_INPUT_INTERACTION) << message << LOG_ID_EVENTS;
3424}
3425
chaviwfd6d3512019-03-25 13:23:49 -07003426void InputDispatcher::dispatchPointerDownOutsideFocus(uint32_t source, int32_t action,
Vishnu Nairad321cd2020-08-20 16:40:21 -07003427 const sp<IBinder>& token) {
chaviw8c9cf542019-03-25 13:02:48 -07003428 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
chaviwfd6d3512019-03-25 13:23:49 -07003429 uint32_t maskedSource = source & AINPUT_SOURCE_CLASS_MASK;
3430 if (maskedSource != AINPUT_SOURCE_CLASS_POINTER || maskedAction != AMOTION_EVENT_ACTION_DOWN) {
chaviw8c9cf542019-03-25 13:02:48 -07003431 return;
3432 }
3433
Vishnu Nairc519ff72021-01-21 08:23:08 -08003434 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07003435 if (focusedToken == token) {
3436 // ignore since token is focused
chaviw8c9cf542019-03-25 13:02:48 -07003437 return;
3438 }
3439
Prabir Pradhancef936d2021-07-21 16:17:52 +00003440 auto command = [this, token]() REQUIRES(mLock) {
3441 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00003442 mPolicy.onPointerDownOutsideFocus(token);
Prabir Pradhancef936d2021-07-21 16:17:52 +00003443 };
3444 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003445}
3446
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003447status_t InputDispatcher::publishMotionEvent(Connection& connection,
3448 DispatchEntry& dispatchEntry) const {
3449 const EventEntry& eventEntry = *(dispatchEntry.eventEntry);
3450 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
3451
3452 PointerCoords scaledCoords[MAX_POINTERS];
3453 const PointerCoords* usingCoords = motionEntry.pointerCoords;
3454
3455 // Set the X and Y offset and X and Y scale depending on the input source.
3456 if ((motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) &&
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003457 !(dispatchEntry.targetFlags.test(InputTarget::Flags::ZERO_COORDS))) {
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003458 float globalScaleFactor = dispatchEntry.globalScaleFactor;
3459 if (globalScaleFactor != 1.0f) {
3460 for (uint32_t i = 0; i < motionEntry.pointerCount; i++) {
3461 scaledCoords[i] = motionEntry.pointerCoords[i];
3462 // Don't apply window scale here since we don't want scale to affect raw
3463 // coordinates. The scale will be sent back to the client and applied
3464 // later when requesting relative coordinates.
Harry Cutts33476232023-01-30 19:57:29 +00003465 scaledCoords[i].scale(globalScaleFactor, /*windowXScale=*/1, /*windowYScale=*/1);
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003466 }
3467 usingCoords = scaledCoords;
3468 }
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003469 } else if (dispatchEntry.targetFlags.test(InputTarget::Flags::ZERO_COORDS)) {
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003470 // We don't want the dispatch target to know the coordinates
3471 for (uint32_t i = 0; i < motionEntry.pointerCount; i++) {
3472 scaledCoords[i].clear();
3473 }
3474 usingCoords = scaledCoords;
3475 }
3476
3477 std::array<uint8_t, 32> hmac = getSignature(motionEntry, dispatchEntry);
3478
3479 // Publish the motion event.
3480 return connection.inputPublisher
3481 .publishMotionEvent(dispatchEntry.seq, dispatchEntry.resolvedEventId,
3482 motionEntry.deviceId, motionEntry.source, motionEntry.displayId,
3483 std::move(hmac), dispatchEntry.resolvedAction,
3484 motionEntry.actionButton, dispatchEntry.resolvedFlags,
3485 motionEntry.edgeFlags, motionEntry.metaState,
3486 motionEntry.buttonState, motionEntry.classification,
3487 dispatchEntry.transform, motionEntry.xPrecision,
3488 motionEntry.yPrecision, motionEntry.xCursorPosition,
3489 motionEntry.yCursorPosition, dispatchEntry.rawTransform,
3490 motionEntry.downTime, motionEntry.eventTime,
3491 motionEntry.pointerCount, motionEntry.pointerProperties,
3492 usingCoords);
3493}
3494
Michael Wrightd02c5b62014-02-10 15:10:22 -08003495void InputDispatcher::startDispatchCycleLocked(nsecs_t currentTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003496 const std::shared_ptr<Connection>& connection) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003497 if (ATRACE_ENABLED()) {
3498 std::string message = StringPrintf("startDispatchCycleLocked(inputChannel=%s)",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003499 connection->getInputChannelName().c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00003500 ATRACE_NAME(message.c_str());
3501 }
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003502 if (DEBUG_DISPATCH_CYCLE) {
3503 ALOGD("channel '%s' ~ startDispatchCycle", connection->getInputChannelName().c_str());
3504 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003505
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003506 while (connection->status == Connection::Status::NORMAL && !connection->outboundQueue.empty()) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003507 DispatchEntry* dispatchEntry = connection->outboundQueue.front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003508 dispatchEntry->deliveryTime = currentTime;
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003509 const std::chrono::nanoseconds timeout = getDispatchingTimeoutLocked(connection);
Siarhei Vishniakou70622952020-07-30 11:17:23 -05003510 dispatchEntry->timeoutTime = currentTime + timeout.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003511
3512 // Publish the event.
3513 status_t status;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003514 const EventEntry& eventEntry = *(dispatchEntry->eventEntry);
3515 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003516 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003517 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
3518 std::array<uint8_t, 32> hmac = getSignature(keyEntry, *dispatchEntry);
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08003519 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
3520 LOG(DEBUG) << "Publishing " << *dispatchEntry << " to "
3521 << connection->getInputChannelName();
3522 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003523
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003524 // Publish the key event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003525 status = connection->inputPublisher
3526 .publishKeyEvent(dispatchEntry->seq,
3527 dispatchEntry->resolvedEventId, keyEntry.deviceId,
3528 keyEntry.source, keyEntry.displayId,
3529 std::move(hmac), dispatchEntry->resolvedAction,
3530 dispatchEntry->resolvedFlags, keyEntry.keyCode,
3531 keyEntry.scanCode, keyEntry.metaState,
3532 keyEntry.repeatCount, keyEntry.downTime,
3533 keyEntry.eventTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003534 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003535 }
3536
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003537 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08003538 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
3539 LOG(DEBUG) << "Publishing " << *dispatchEntry << " to "
3540 << connection->getInputChannelName();
3541 }
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003542 status = publishMotionEvent(*connection, *dispatchEntry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003543 break;
3544 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003545
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003546 case EventEntry::Type::FOCUS: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003547 const FocusEntry& focusEntry = static_cast<const FocusEntry&>(eventEntry);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003548 status = connection->inputPublisher.publishFocusEvent(dispatchEntry->seq,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003549 focusEntry.id,
Antonio Kantek3cfec7b2021-11-05 18:26:17 -07003550 focusEntry.hasFocus);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003551 break;
3552 }
3553
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003554 case EventEntry::Type::TOUCH_MODE_CHANGED: {
3555 const TouchModeEntry& touchModeEntry =
3556 static_cast<const TouchModeEntry&>(eventEntry);
3557 status = connection->inputPublisher
3558 .publishTouchModeEvent(dispatchEntry->seq, touchModeEntry.id,
3559 touchModeEntry.inTouchMode);
3560
3561 break;
3562 }
3563
Prabir Pradhan99987712020-11-10 18:43:05 -08003564 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
3565 const auto& captureEntry =
3566 static_cast<const PointerCaptureChangedEntry&>(eventEntry);
3567 status = connection->inputPublisher
3568 .publishCaptureEvent(dispatchEntry->seq, captureEntry.id,
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00003569 captureEntry.pointerCaptureRequest.enable);
Prabir Pradhan99987712020-11-10 18:43:05 -08003570 break;
3571 }
3572
arthurhungb89ccb02020-12-30 16:19:01 +08003573 case EventEntry::Type::DRAG: {
3574 const DragEntry& dragEntry = static_cast<const DragEntry&>(eventEntry);
3575 status = connection->inputPublisher.publishDragEvent(dispatchEntry->seq,
3576 dragEntry.id, dragEntry.x,
3577 dragEntry.y,
3578 dragEntry.isExiting);
3579 break;
3580 }
3581
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003582 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07003583 case EventEntry::Type::DEVICE_RESET:
3584 case EventEntry::Type::SENSOR: {
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003585 LOG_ALWAYS_FATAL("Should never start dispatch cycles for %s events",
Dominik Laskowski75788452021-02-09 18:51:25 -08003586 ftl::enum_string(eventEntry.type).c_str());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003587 return;
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003588 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003589 }
3590
3591 // Check the result.
3592 if (status) {
3593 if (status == WOULD_BLOCK) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003594 if (connection->waitQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003595 ALOGE("channel '%s' ~ Could not publish event because the pipe is full. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003596 "This is unexpected because the wait queue is empty, so the pipe "
3597 "should be empty and we shouldn't have any problems writing an "
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +00003598 "event to it, status=%s(%d)",
3599 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3600 status);
Harry Cutts33476232023-01-30 19:57:29 +00003601 abortBrokenDispatchCycleLocked(currentTime, connection, /*notify=*/true);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003602 } else {
3603 // Pipe is full and we are waiting for the app to finish process some events
3604 // before sending more events to it.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003605 if (DEBUG_DISPATCH_CYCLE) {
3606 ALOGD("channel '%s' ~ Could not publish event because the pipe is full, "
3607 "waiting for the application to catch up",
3608 connection->getInputChannelName().c_str());
3609 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003610 }
3611 } else {
3612 ALOGE("channel '%s' ~ Could not publish event due to an unexpected error, "
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +00003613 "status=%s(%d)",
3614 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3615 status);
Harry Cutts33476232023-01-30 19:57:29 +00003616 abortBrokenDispatchCycleLocked(currentTime, connection, /*notify=*/true);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003617 }
3618 return;
3619 }
3620
3621 // Re-enqueue the event on the wait queue.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003622 connection->outboundQueue.erase(std::remove(connection->outboundQueue.begin(),
3623 connection->outboundQueue.end(),
3624 dispatchEntry));
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003625 traceOutboundQueueLength(*connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003626 connection->waitQueue.push_back(dispatchEntry);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003627 if (connection->responsive) {
3628 mAnrTracker.insert(dispatchEntry->timeoutTime,
3629 connection->inputChannel->getConnectionToken());
3630 }
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003631 traceWaitQueueLength(*connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003632 }
3633}
3634
chaviw09c8d2d2020-08-24 15:48:26 -07003635std::array<uint8_t, 32> InputDispatcher::sign(const VerifiedInputEvent& event) const {
3636 size_t size;
3637 switch (event.type) {
3638 case VerifiedInputEvent::Type::KEY: {
3639 size = sizeof(VerifiedKeyEvent);
3640 break;
3641 }
3642 case VerifiedInputEvent::Type::MOTION: {
3643 size = sizeof(VerifiedMotionEvent);
3644 break;
3645 }
3646 }
3647 const uint8_t* start = reinterpret_cast<const uint8_t*>(&event);
3648 return mHmacKeyManager.sign(start, size);
3649}
3650
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003651const std::array<uint8_t, 32> InputDispatcher::getSignature(
3652 const MotionEntry& motionEntry, const DispatchEntry& dispatchEntry) const {
Siarhei Vishniakoubf880522023-05-01 11:03:22 -07003653 const int32_t actionMasked = MotionEvent::getActionMasked(dispatchEntry.resolvedAction);
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003654 if (actionMasked != AMOTION_EVENT_ACTION_UP && actionMasked != AMOTION_EVENT_ACTION_DOWN) {
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003655 // Only sign events up and down events as the purely move events
3656 // are tied to their up/down counterparts so signing would be redundant.
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003657 return INVALID_HMAC;
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003658 }
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003659
3660 VerifiedMotionEvent verifiedEvent =
3661 verifiedMotionEventFromMotionEntry(motionEntry, dispatchEntry.rawTransform);
3662 verifiedEvent.actionMasked = actionMasked;
3663 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_MOTION_EVENT_FLAGS;
3664 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003665}
3666
3667const std::array<uint8_t, 32> InputDispatcher::getSignature(
3668 const KeyEntry& keyEntry, const DispatchEntry& dispatchEntry) const {
3669 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEntry(keyEntry);
3670 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_KEY_EVENT_FLAGS;
3671 verifiedEvent.action = dispatchEntry.resolvedAction;
chaviw09c8d2d2020-08-24 15:48:26 -07003672 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003673}
3674
Michael Wrightd02c5b62014-02-10 15:10:22 -08003675void InputDispatcher::finishDispatchCycleLocked(nsecs_t currentTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003676 const std::shared_ptr<Connection>& connection,
3677 uint32_t seq, bool handled, nsecs_t consumeTime) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003678 if (DEBUG_DISPATCH_CYCLE) {
3679 ALOGD("channel '%s' ~ finishDispatchCycle - seq=%u, handled=%s",
3680 connection->getInputChannelName().c_str(), seq, toString(handled));
3681 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003682
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003683 if (connection->status == Connection::Status::BROKEN ||
3684 connection->status == Connection::Status::ZOMBIE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003685 return;
3686 }
3687
3688 // Notify other system components and prepare to start the next dispatch cycle.
Prabir Pradhancef936d2021-07-21 16:17:52 +00003689 auto command = [this, currentTime, connection, seq, handled, consumeTime]() REQUIRES(mLock) {
3690 doDispatchCycleFinishedCommand(currentTime, connection, seq, handled, consumeTime);
3691 };
3692 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003693}
3694
3695void InputDispatcher::abortBrokenDispatchCycleLocked(nsecs_t currentTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003696 const std::shared_ptr<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003697 bool notify) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003698 if (DEBUG_DISPATCH_CYCLE) {
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07003699 LOG(DEBUG) << "channel '" << connection->getInputChannelName() << "'~ " << __func__
3700 << " - notify=" << toString(notify);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003701 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003702
3703 // Clear the dispatch queues.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003704 drainDispatchQueue(connection->outboundQueue);
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003705 traceOutboundQueueLength(*connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003706 drainDispatchQueue(connection->waitQueue);
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003707 traceWaitQueueLength(*connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003708
3709 // The connection appears to be unrecoverably broken.
3710 // Ignore already broken or zombie connections.
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003711 if (connection->status == Connection::Status::NORMAL) {
3712 connection->status = Connection::Status::BROKEN;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003713
3714 if (notify) {
3715 // Notify other system components.
Prabir Pradhancef936d2021-07-21 16:17:52 +00003716 ALOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
3717 connection->getInputChannelName().c_str());
3718
3719 auto command = [this, connection]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00003720 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00003721 mPolicy.notifyInputChannelBroken(connection->inputChannel->getConnectionToken());
Prabir Pradhancef936d2021-07-21 16:17:52 +00003722 };
3723 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003724 }
3725 }
3726}
3727
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003728void InputDispatcher::drainDispatchQueue(std::deque<DispatchEntry*>& queue) {
3729 while (!queue.empty()) {
3730 DispatchEntry* dispatchEntry = queue.front();
3731 queue.pop_front();
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003732 releaseDispatchEntry(dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003733 }
3734}
3735
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003736void InputDispatcher::releaseDispatchEntry(DispatchEntry* dispatchEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003737 if (dispatchEntry->hasForegroundTarget()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003738 decrementPendingForegroundDispatches(*(dispatchEntry->eventEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003739 }
3740 delete dispatchEntry;
3741}
3742
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003743int InputDispatcher::handleReceiveCallback(int events, sp<IBinder> connectionToken) {
3744 std::scoped_lock _l(mLock);
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003745 std::shared_ptr<Connection> connection = getConnectionLocked(connectionToken);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003746 if (connection == nullptr) {
3747 ALOGW("Received looper callback for unknown input channel token %p. events=0x%x",
3748 connectionToken.get(), events);
3749 return 0; // remove the callback
3750 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003751
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003752 bool notify;
3753 if (!(events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP))) {
3754 if (!(events & ALOOPER_EVENT_INPUT)) {
3755 ALOGW("channel '%s' ~ Received spurious callback for unhandled poll event. "
3756 "events=0x%x",
3757 connection->getInputChannelName().c_str(), events);
3758 return 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003759 }
3760
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003761 nsecs_t currentTime = now();
3762 bool gotOne = false;
3763 status_t status = OK;
3764 for (;;) {
3765 Result<InputPublisher::ConsumerResponse> result =
3766 connection->inputPublisher.receiveConsumerResponse();
3767 if (!result.ok()) {
3768 status = result.error().code();
3769 break;
3770 }
3771
3772 if (std::holds_alternative<InputPublisher::Finished>(*result)) {
3773 const InputPublisher::Finished& finish =
3774 std::get<InputPublisher::Finished>(*result);
3775 finishDispatchCycleLocked(currentTime, connection, finish.seq, finish.handled,
3776 finish.consumeTime);
3777 } else if (std::holds_alternative<InputPublisher::Timeline>(*result)) {
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00003778 if (shouldReportMetricsForConnection(*connection)) {
3779 const InputPublisher::Timeline& timeline =
3780 std::get<InputPublisher::Timeline>(*result);
3781 mLatencyTracker
3782 .trackGraphicsLatency(timeline.inputEventId,
3783 connection->inputChannel->getConnectionToken(),
3784 std::move(timeline.graphicsTimeline));
3785 }
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003786 }
3787 gotOne = true;
3788 }
3789 if (gotOne) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00003790 runCommandsLockedInterruptable();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003791 if (status == WOULD_BLOCK) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003792 return 1;
3793 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003794 }
3795
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003796 notify = status != DEAD_OBJECT || !connection->monitor;
3797 if (notify) {
3798 ALOGE("channel '%s' ~ Failed to receive finished signal. status=%s(%d)",
3799 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3800 status);
3801 }
3802 } else {
3803 // Monitor channels are never explicitly unregistered.
3804 // We do it automatically when the remote endpoint is closed so don't warn about them.
3805 const bool stillHaveWindowHandle =
3806 getWindowHandleLocked(connection->inputChannel->getConnectionToken()) != nullptr;
3807 notify = !connection->monitor && stillHaveWindowHandle;
3808 if (notify) {
3809 ALOGW("channel '%s' ~ Consumer closed input channel or an error occurred. events=0x%x",
3810 connection->getInputChannelName().c_str(), events);
3811 }
3812 }
3813
3814 // Remove the channel.
3815 removeInputChannelLocked(connection->inputChannel->getConnectionToken(), notify);
3816 return 0; // remove the callback
Michael Wrightd02c5b62014-02-10 15:10:22 -08003817}
3818
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003819void InputDispatcher::synthesizeCancelationEventsForAllConnectionsLocked(
Michael Wrightd02c5b62014-02-10 15:10:22 -08003820 const CancelationOptions& options) {
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003821 for (const auto& [token, connection] : mConnectionsByToken) {
Siarhei Vishniakou2e2ea992020-12-15 02:57:19 +00003822 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003823 }
3824}
3825
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003826void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
Michael Wrightfa13dcf2015-06-12 13:25:11 +01003827 const CancelationOptions& options) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08003828 for (const auto& [_, monitors] : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003829 for (const Monitor& monitor : monitors) {
3830 synthesizeCancelationEventsForInputChannelLocked(monitor.inputChannel, options);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003831 }
Michael Wrightfa13dcf2015-06-12 13:25:11 +01003832 }
3833}
3834
Michael Wrightd02c5b62014-02-10 15:10:22 -08003835void InputDispatcher::synthesizeCancelationEventsForInputChannelLocked(
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05003836 const std::shared_ptr<InputChannel>& channel, const CancelationOptions& options) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003837 std::shared_ptr<Connection> connection = getConnectionLocked(channel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003838 if (connection == nullptr) {
3839 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003840 }
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003841
3842 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003843}
3844
3845void InputDispatcher::synthesizeCancelationEventsForConnectionLocked(
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003846 const std::shared_ptr<Connection>& connection, const CancelationOptions& options) {
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003847 if (connection->status == Connection::Status::BROKEN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003848 return;
3849 }
3850
3851 nsecs_t currentTime = now();
3852
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003853 std::vector<std::unique_ptr<EventEntry>> cancelationEvents =
Siarhei Vishniakou00fca7c2019-10-29 13:05:57 -07003854 connection->inputState.synthesizeCancelationEvents(currentTime, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003855
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003856 if (cancelationEvents.empty()) {
3857 return;
3858 }
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003859 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
3860 ALOGD("channel '%s' ~ Synthesized %zu cancelation events to bring channel back in sync "
Siarhei Vishniakou2e3e4432023-02-09 18:34:11 -08003861 "with reality: %s, mode=%s.",
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003862 connection->getInputChannelName().c_str(), cancelationEvents.size(), options.reason,
Siarhei Vishniakou2e3e4432023-02-09 18:34:11 -08003863 ftl::enum_string(options.mode).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003864 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08003865
Arthur Hungb3307ee2021-10-14 10:57:37 +00003866 std::string reason = std::string("reason=").append(options.reason);
3867 android_log_event_list(LOGTAG_INPUT_CANCEL)
3868 << connection->getInputChannelName().c_str() << reason << LOG_ID_EVENTS;
3869
Svet Ganov5d3bc372020-01-26 23:11:07 -08003870 InputTarget target;
chaviw98318de2021-05-19 16:45:23 -05003871 sp<WindowInfoHandle> windowHandle =
Svet Ganov5d3bc372020-01-26 23:11:07 -08003872 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
3873 if (windowHandle != nullptr) {
chaviw98318de2021-05-19 16:45:23 -05003874 const WindowInfo* windowInfo = windowHandle->getInfo();
chaviw1ff3d1e2020-07-01 15:53:47 -07003875 target.setDefaultPointerTransform(windowInfo->transform);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003876 target.globalScaleFactor = windowInfo->globalScaleFactor;
3877 }
3878 target.inputChannel = connection->inputChannel;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003879 target.flags = InputTarget::Flags::DISPATCH_AS_IS;
Svet Ganov5d3bc372020-01-26 23:11:07 -08003880
hongzuo liu95785e22022-09-06 02:51:35 +00003881 const bool wasEmpty = connection->outboundQueue.empty();
3882
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003883 for (size_t i = 0; i < cancelationEvents.size(); i++) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003884 std::unique_ptr<EventEntry> cancelationEventEntry = std::move(cancelationEvents[i]);
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003885 switch (cancelationEventEntry->type) {
3886 case EventEntry::Type::KEY: {
3887 logOutboundKeyDetails("cancel - ",
3888 static_cast<const KeyEntry&>(*cancelationEventEntry));
3889 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003890 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003891 case EventEntry::Type::MOTION: {
3892 logOutboundMotionDetails("cancel - ",
3893 static_cast<const MotionEntry&>(*cancelationEventEntry));
3894 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003895 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003896 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003897 case EventEntry::Type::TOUCH_MODE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08003898 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
3899 case EventEntry::Type::DRAG: {
Prabir Pradhan99987712020-11-10 18:43:05 -08003900 LOG_ALWAYS_FATAL("Canceling %s events is not supported",
Dominik Laskowski75788452021-02-09 18:51:25 -08003901 ftl::enum_string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003902 break;
3903 }
3904 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07003905 case EventEntry::Type::DEVICE_RESET:
3906 case EventEntry::Type::SENSOR: {
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003907 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Dominik Laskowski75788452021-02-09 18:51:25 -08003908 ftl::enum_string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003909 break;
3910 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003911 }
3912
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003913 enqueueDispatchEntryLocked(connection, std::move(cancelationEventEntry), target,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003914 InputTarget::Flags::DISPATCH_AS_IS);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003915 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003916
hongzuo liu95785e22022-09-06 02:51:35 +00003917 // If the outbound queue was previously empty, start the dispatch cycle going.
3918 if (wasEmpty && !connection->outboundQueue.empty()) {
3919 startDispatchCycleLocked(currentTime, connection);
3920 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003921}
3922
Svet Ganov5d3bc372020-01-26 23:11:07 -08003923void InputDispatcher::synthesizePointerDownEventsForConnectionLocked(
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003924 const nsecs_t downTime, const std::shared_ptr<Connection>& connection,
Arthur Hungc539dbb2022-12-08 07:45:36 +00003925 ftl::Flags<InputTarget::Flags> targetFlags) {
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003926 if (connection->status == Connection::Status::BROKEN) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003927 return;
3928 }
3929
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003930 std::vector<std::unique_ptr<EventEntry>> downEvents =
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00003931 connection->inputState.synthesizePointerDownEvents(downTime);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003932
3933 if (downEvents.empty()) {
3934 return;
3935 }
3936
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003937 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003938 ALOGD("channel '%s' ~ Synthesized %zu down events to ensure consistent event stream.",
3939 connection->getInputChannelName().c_str(), downEvents.size());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003940 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08003941
3942 InputTarget target;
chaviw98318de2021-05-19 16:45:23 -05003943 sp<WindowInfoHandle> windowHandle =
Svet Ganov5d3bc372020-01-26 23:11:07 -08003944 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
3945 if (windowHandle != nullptr) {
chaviw98318de2021-05-19 16:45:23 -05003946 const WindowInfo* windowInfo = windowHandle->getInfo();
chaviw1ff3d1e2020-07-01 15:53:47 -07003947 target.setDefaultPointerTransform(windowInfo->transform);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003948 target.globalScaleFactor = windowInfo->globalScaleFactor;
3949 }
3950 target.inputChannel = connection->inputChannel;
Arthur Hungc539dbb2022-12-08 07:45:36 +00003951 target.flags = targetFlags;
Svet Ganov5d3bc372020-01-26 23:11:07 -08003952
hongzuo liu95785e22022-09-06 02:51:35 +00003953 const bool wasEmpty = connection->outboundQueue.empty();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003954 for (std::unique_ptr<EventEntry>& downEventEntry : downEvents) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003955 switch (downEventEntry->type) {
3956 case EventEntry::Type::MOTION: {
3957 logOutboundMotionDetails("down - ",
3958 static_cast<const MotionEntry&>(*downEventEntry));
3959 break;
3960 }
3961
3962 case EventEntry::Type::KEY:
3963 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003964 case EventEntry::Type::TOUCH_MODE_CHANGED:
Svet Ganov5d3bc372020-01-26 23:11:07 -08003965 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08003966 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07003967 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08003968 case EventEntry::Type::SENSOR:
3969 case EventEntry::Type::DRAG: {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003970 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Dominik Laskowski75788452021-02-09 18:51:25 -08003971 ftl::enum_string(downEventEntry->type).c_str());
Svet Ganov5d3bc372020-01-26 23:11:07 -08003972 break;
3973 }
3974 }
3975
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003976 enqueueDispatchEntryLocked(connection, std::move(downEventEntry), target,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003977 InputTarget::Flags::DISPATCH_AS_IS);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003978 }
3979
hongzuo liu95785e22022-09-06 02:51:35 +00003980 // If the outbound queue was previously empty, start the dispatch cycle going.
3981 if (wasEmpty && !connection->outboundQueue.empty()) {
3982 startDispatchCycleLocked(downTime, connection);
3983 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08003984}
3985
Arthur Hungc539dbb2022-12-08 07:45:36 +00003986void InputDispatcher::synthesizeCancelationEventsForWindowLocked(
3987 const sp<WindowInfoHandle>& windowHandle, const CancelationOptions& options) {
3988 if (windowHandle != nullptr) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003989 std::shared_ptr<Connection> wallpaperConnection =
3990 getConnectionLocked(windowHandle->getToken());
Arthur Hungc539dbb2022-12-08 07:45:36 +00003991 if (wallpaperConnection != nullptr) {
3992 synthesizeCancelationEventsForConnectionLocked(wallpaperConnection, options);
3993 }
3994 }
3995}
3996
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003997std::unique_ptr<MotionEntry> InputDispatcher::splitMotionEvent(
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08003998 const MotionEntry& originalMotionEntry, std::bitset<MAX_POINTER_ID + 1> pointerIds,
3999 nsecs_t splitDownTime) {
4000 ALOG_ASSERT(pointerIds.any());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004001
4002 uint32_t splitPointerIndexMap[MAX_POINTERS];
4003 PointerProperties splitPointerProperties[MAX_POINTERS];
4004 PointerCoords splitPointerCoords[MAX_POINTERS];
4005
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07004006 uint32_t originalPointerCount = originalMotionEntry.pointerCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004007 uint32_t splitPointerCount = 0;
4008
4009 for (uint32_t originalPointerIndex = 0; originalPointerIndex < originalPointerCount;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004010 originalPointerIndex++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004011 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07004012 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08004013 uint32_t pointerId = uint32_t(pointerProperties.id);
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08004014 if (pointerIds.test(pointerId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004015 splitPointerIndexMap[splitPointerCount] = originalPointerIndex;
4016 splitPointerProperties[splitPointerCount].copyFrom(pointerProperties);
4017 splitPointerCoords[splitPointerCount].copyFrom(
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07004018 originalMotionEntry.pointerCoords[originalPointerIndex]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004019 splitPointerCount += 1;
4020 }
4021 }
4022
4023 if (splitPointerCount != pointerIds.count()) {
4024 // This is bad. We are missing some of the pointers that we expected to deliver.
4025 // Most likely this indicates that we received an ACTION_MOVE events that has
4026 // different pointer ids than we expected based on the previous ACTION_DOWN
4027 // or ACTION_POINTER_DOWN events that caused us to decide to split the pointers
4028 // in this way.
4029 ALOGW("Dropping split motion event because the pointer count is %d but "
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08004030 "we expected there to be %zu pointers. This probably means we received "
Siarhei Vishniakou16e4fa02023-02-16 17:48:56 -08004031 "a broken sequence of pointer ids from the input device: %s",
4032 splitPointerCount, pointerIds.count(), originalMotionEntry.getDescription().c_str());
Yi Kong9b14ac62018-07-17 13:48:38 -07004033 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004034 }
4035
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07004036 int32_t action = originalMotionEntry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004037 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004038 if (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN ||
4039 maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004040 int32_t originalPointerIndex = getMotionEventActionPointerIndex(action);
4041 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07004042 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08004043 uint32_t pointerId = uint32_t(pointerProperties.id);
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08004044 if (pointerIds.test(pointerId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004045 if (pointerIds.count() == 1) {
4046 // The first/last pointer went down/up.
4047 action = maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004048 ? AMOTION_EVENT_ACTION_DOWN
arthurhungea3f4fc2020-12-21 23:18:53 +08004049 : (originalMotionEntry.flags & AMOTION_EVENT_FLAG_CANCELED) != 0
4050 ? AMOTION_EVENT_ACTION_CANCEL
4051 : AMOTION_EVENT_ACTION_UP;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004052 } else {
4053 // A secondary pointer went down/up.
4054 uint32_t splitPointerIndex = 0;
4055 while (pointerId != uint32_t(splitPointerProperties[splitPointerIndex].id)) {
4056 splitPointerIndex += 1;
4057 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004058 action = maskedAction |
4059 (splitPointerIndex << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004060 }
4061 } else {
4062 // An unrelated pointer changed.
4063 action = AMOTION_EVENT_ACTION_MOVE;
4064 }
4065 }
4066
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00004067 if (action == AMOTION_EVENT_ACTION_DOWN) {
4068 LOG_ALWAYS_FATAL_IF(splitDownTime != originalMotionEntry.eventTime,
4069 "Split motion event has mismatching downTime and eventTime for "
Siarhei Vishniakou060f82b2023-01-27 06:39:14 -08004070 "ACTION_DOWN, motionEntry=%s, splitDownTime=%" PRId64,
4071 originalMotionEntry.getDescription().c_str(), splitDownTime);
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00004072 }
4073
Garfield Tanff1f1bb2020-01-28 13:24:04 -08004074 int32_t newId = mIdGenerator.nextId();
4075 if (ATRACE_ENABLED()) {
4076 std::string message = StringPrintf("Split MotionEvent(id=0x%" PRIx32
4077 ") to MotionEvent(id=0x%" PRIx32 ").",
4078 originalMotionEntry.id, newId);
4079 ATRACE_NAME(message.c_str());
4080 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004081 std::unique_ptr<MotionEntry> splitMotionEntry =
4082 std::make_unique<MotionEntry>(newId, originalMotionEntry.eventTime,
4083 originalMotionEntry.deviceId, originalMotionEntry.source,
4084 originalMotionEntry.displayId,
4085 originalMotionEntry.policyFlags, action,
4086 originalMotionEntry.actionButton,
4087 originalMotionEntry.flags, originalMotionEntry.metaState,
4088 originalMotionEntry.buttonState,
4089 originalMotionEntry.classification,
4090 originalMotionEntry.edgeFlags,
4091 originalMotionEntry.xPrecision,
4092 originalMotionEntry.yPrecision,
4093 originalMotionEntry.xCursorPosition,
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00004094 originalMotionEntry.yCursorPosition, splitDownTime,
4095 splitPointerCount, splitPointerProperties,
4096 splitPointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004097
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07004098 if (originalMotionEntry.injectionState) {
4099 splitMotionEntry->injectionState = originalMotionEntry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004100 splitMotionEntry->injectionState->refCount += 1;
4101 }
4102
4103 return splitMotionEntry;
4104}
4105
Prabir Pradhan678438e2023-04-13 19:32:51 +00004106void InputDispatcher::notifyConfigurationChanged(const NotifyConfigurationChangedArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004107 if (debugInboundEventDetails()) {
Prabir Pradhan678438e2023-04-13 19:32:51 +00004108 ALOGD("notifyConfigurationChanged - eventTime=%" PRId64, args.eventTime);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004109 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004110
Antonio Kantekf16f2832021-09-28 04:39:20 +00004111 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004112 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004113 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004114
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004115 std::unique_ptr<ConfigurationChangedEntry> newEntry =
Prabir Pradhan678438e2023-04-13 19:32:51 +00004116 std::make_unique<ConfigurationChangedEntry>(args.id, args.eventTime);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004117 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004118 } // release lock
4119
4120 if (needWake) {
4121 mLooper->wake();
4122 }
4123}
4124
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05004125/**
4126 * If one of the meta shortcuts is detected, process them here:
Vaibhav Devmurari34cd5b02023-02-23 14:51:18 +00004127 * Meta + Backspace; Meta + Grave; Meta + Left arrow -> generate BACK
4128 * Most System shortcuts are handled in PhoneWindowManager.java except 'Back' shortcuts. Unlike
4129 * Back, other shortcuts DO NOT need to be sent to applications and are fully handled by the system.
4130 * But for Back key and Back shortcuts, we need to send KEYCODE_BACK to applications which can
4131 * potentially handle the back key presses.
4132 * Note: We don't send any Meta based KeyEvents to applications, so we need to convert to a KeyEvent
4133 * where meta modifier is off before sending. Currently only use case is 'Back'.
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05004134 */
4135void InputDispatcher::accelerateMetaShortcuts(const int32_t deviceId, const int32_t action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004136 int32_t& keyCode, int32_t& metaState) {
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05004137 if (metaState & AMETA_META_ON && action == AKEY_EVENT_ACTION_DOWN) {
4138 int32_t newKeyCode = AKEYCODE_UNKNOWN;
Vaibhav Devmurari34cd5b02023-02-23 14:51:18 +00004139 if (keyCode == AKEYCODE_DEL || keyCode == AKEYCODE_GRAVE || keyCode == AKEYCODE_DPAD_LEFT) {
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05004140 newKeyCode = AKEYCODE_BACK;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05004141 }
4142 if (newKeyCode != AKEYCODE_UNKNOWN) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004143 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05004144 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004145 mReplacedKeys[replacement] = newKeyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05004146 keyCode = newKeyCode;
4147 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
4148 }
4149 } else if (action == AKEY_EVENT_ACTION_UP) {
4150 // In order to maintain a consistent stream of up and down events, check to see if the key
4151 // going up is one we've replaced in a down event and haven't yet replaced in an up event,
4152 // even if the modifier was released between the down and the up events.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004153 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05004154 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004155 auto replacementIt = mReplacedKeys.find(replacement);
4156 if (replacementIt != mReplacedKeys.end()) {
4157 keyCode = replacementIt->second;
4158 mReplacedKeys.erase(replacementIt);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05004159 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
4160 }
4161 }
4162}
4163
Prabir Pradhan678438e2023-04-13 19:32:51 +00004164void InputDispatcher::notifyKey(const NotifyKeyArgs& args) {
Prabir Pradhan96282b02023-02-24 22:36:17 +00004165 ALOGD_IF(debugInboundEventDetails(),
4166 "notifyKey - id=%" PRIx32 ", eventTime=%" PRId64
4167 ", deviceId=%d, source=%s, displayId=%" PRId32
4168 "policyFlags=0x%x, action=%s, flags=0x%x, keyCode=%s, scanCode=0x%x, metaState=0x%x, "
4169 "downTime=%" PRId64,
Prabir Pradhan678438e2023-04-13 19:32:51 +00004170 args.id, args.eventTime, args.deviceId, inputEventSourceToString(args.source).c_str(),
4171 args.displayId, args.policyFlags, KeyEvent::actionToString(args.action), args.flags,
4172 KeyEvent::getLabel(args.keyCode), args.scanCode, args.metaState, args.downTime);
Siarhei Vishniakou6773db62023-04-21 11:30:20 -07004173 Result<void> keyCheck = validateKeyEvent(args.action);
4174 if (!keyCheck.ok()) {
4175 LOG(ERROR) << "invalid key event: " << keyCheck.error();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004176 return;
4177 }
4178
Prabir Pradhan678438e2023-04-13 19:32:51 +00004179 uint32_t policyFlags = args.policyFlags;
4180 int32_t flags = args.flags;
4181 int32_t metaState = args.metaState;
Siarhei Vishniakou622bd322018-10-29 18:02:27 -07004182 // InputDispatcher tracks and generates key repeats on behalf of
4183 // whatever notifies it, so repeatCount should always be set to 0
4184 constexpr int32_t repeatCount = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004185 if ((policyFlags & POLICY_FLAG_VIRTUAL) || (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY)) {
4186 policyFlags |= POLICY_FLAG_VIRTUAL;
4187 flags |= AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
4188 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004189 if (policyFlags & POLICY_FLAG_FUNCTION) {
4190 metaState |= AMETA_FUNCTION_ON;
4191 }
4192
4193 policyFlags |= POLICY_FLAG_TRUSTED;
4194
Prabir Pradhan678438e2023-04-13 19:32:51 +00004195 int32_t keyCode = args.keyCode;
4196 accelerateMetaShortcuts(args.deviceId, args.action, keyCode, metaState);
Michael Wright78f24442014-08-06 15:55:28 -07004197
Michael Wrightd02c5b62014-02-10 15:10:22 -08004198 KeyEvent event;
Prabir Pradhan678438e2023-04-13 19:32:51 +00004199 event.initialize(args.id, args.deviceId, args.source, args.displayId, INVALID_HMAC, args.action,
4200 flags, keyCode, args.scanCode, metaState, repeatCount, args.downTime,
4201 args.eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004202
Michael Wright2b3c3302018-03-02 17:19:13 +00004203 android::base::Timer t;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004204 mPolicy.interceptKeyBeforeQueueing(event, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00004205 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4206 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004207 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00004208 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004209
Antonio Kantekf16f2832021-09-28 04:39:20 +00004210 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004211 { // acquire lock
4212 mLock.lock();
4213
4214 if (shouldSendKeyToInputFilterLocked(args)) {
4215 mLock.unlock();
4216
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004217 policyFlags |= POLICY_FLAG_FILTERED;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004218 if (!mPolicy.filterInputEvent(event, policyFlags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004219 return; // event was consumed by the filter
4220 }
4221
4222 mLock.lock();
4223 }
4224
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004225 std::unique_ptr<KeyEntry> newEntry =
Prabir Pradhan678438e2023-04-13 19:32:51 +00004226 std::make_unique<KeyEntry>(args.id, args.eventTime, args.deviceId, args.source,
4227 args.displayId, policyFlags, args.action, flags, keyCode,
4228 args.scanCode, metaState, repeatCount, args.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004229
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004230 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004231 mLock.unlock();
4232 } // release lock
4233
4234 if (needWake) {
4235 mLooper->wake();
4236 }
4237}
4238
Prabir Pradhan678438e2023-04-13 19:32:51 +00004239bool InputDispatcher::shouldSendKeyToInputFilterLocked(const NotifyKeyArgs& args) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004240 return mInputFilterEnabled;
4241}
4242
Prabir Pradhan678438e2023-04-13 19:32:51 +00004243void InputDispatcher::notifyMotion(const NotifyMotionArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004244 if (debugInboundEventDetails()) {
Prabir Pradhan96282b02023-02-24 22:36:17 +00004245 ALOGD("notifyMotion - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=%s, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004246 "displayId=%" PRId32 ", policyFlags=0x%x, "
Siarhei Vishniakou6ebd0692022-10-20 15:05:45 -07004247 "action=%s, actionButton=0x%x, flags=0x%x, metaState=0x%x, buttonState=0x%x, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004248 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, xCursorPosition=%f, "
4249 "yCursorPosition=%f, downTime=%" PRId64,
Prabir Pradhan678438e2023-04-13 19:32:51 +00004250 args.id, args.eventTime, args.deviceId, inputEventSourceToString(args.source).c_str(),
4251 args.displayId, args.policyFlags, MotionEvent::actionToString(args.action).c_str(),
4252 args.actionButton, args.flags, args.metaState, args.buttonState, args.edgeFlags,
4253 args.xPrecision, args.yPrecision, args.xCursorPosition, args.yCursorPosition,
4254 args.downTime);
4255 for (uint32_t i = 0; i < args.pointerCount; i++) {
Prabir Pradhan96282b02023-02-24 22:36:17 +00004256 ALOGD(" Pointer %d: id=%d, toolType=%s, x=%f, y=%f, pressure=%f, size=%f, "
4257 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, orientation=%f",
Prabir Pradhan678438e2023-04-13 19:32:51 +00004258 i, args.pointerProperties[i].id,
4259 ftl::enum_string(args.pointerProperties[i].toolType).c_str(),
4260 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
4261 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
4262 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
4263 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
4264 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
4265 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
4266 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
4267 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
4268 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004269 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004270 }
Siarhei Vishniakou4ca97272023-03-01 11:31:35 -08004271
Siarhei Vishniakou6773db62023-04-21 11:30:20 -07004272 Result<void> motionCheck = validateMotionEvent(args.action, args.actionButton,
4273 args.pointerCount, args.pointerProperties);
4274 if (!motionCheck.ok()) {
4275 LOG(ERROR) << "Invalid event: " << args.dump() << "; reason: " << motionCheck.error();
Siarhei Vishniakou4ca97272023-03-01 11:31:35 -08004276 return;
4277 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004278
Prabir Pradhan678438e2023-04-13 19:32:51 +00004279 uint32_t policyFlags = args.policyFlags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004280 policyFlags |= POLICY_FLAG_TRUSTED;
Michael Wright2b3c3302018-03-02 17:19:13 +00004281
4282 android::base::Timer t;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004283 mPolicy.interceptMotionBeforeQueueing(args.displayId, args.eventTime, policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00004284 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4285 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004286 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00004287 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004288
Antonio Kantekf16f2832021-09-28 04:39:20 +00004289 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004290 { // acquire lock
4291 mLock.lock();
Siarhei Vishniakou5bf25d92023-02-08 15:43:38 -08004292 if (!(policyFlags & POLICY_FLAG_PASS_TO_USER)) {
4293 // Set the flag anyway if we already have an ongoing gesture. That would allow us to
4294 // complete the processing of the current stroke.
Prabir Pradhan678438e2023-04-13 19:32:51 +00004295 const auto touchStateIt = mTouchStatesByDisplay.find(args.displayId);
Siarhei Vishniakou5bf25d92023-02-08 15:43:38 -08004296 if (touchStateIt != mTouchStatesByDisplay.end()) {
4297 const TouchState& touchState = touchStateIt->second;
Prabir Pradhan678438e2023-04-13 19:32:51 +00004298 if (touchState.deviceId == args.deviceId && touchState.isDown()) {
Siarhei Vishniakou5bf25d92023-02-08 15:43:38 -08004299 policyFlags |= POLICY_FLAG_PASS_TO_USER;
4300 }
4301 }
4302 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004303
4304 if (shouldSendMotionToInputFilterLocked(args)) {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004305 ui::Transform displayTransform;
Prabir Pradhan678438e2023-04-13 19:32:51 +00004306 if (const auto it = mDisplayInfos.find(args.displayId); it != mDisplayInfos.end()) {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004307 displayTransform = it->second.transform;
4308 }
4309
Michael Wrightd02c5b62014-02-10 15:10:22 -08004310 mLock.unlock();
4311
4312 MotionEvent event;
Prabir Pradhan678438e2023-04-13 19:32:51 +00004313 event.initialize(args.id, args.deviceId, args.source, args.displayId, INVALID_HMAC,
4314 args.action, args.actionButton, args.flags, args.edgeFlags,
4315 args.metaState, args.buttonState, args.classification,
4316 displayTransform, args.xPrecision, args.yPrecision,
4317 args.xCursorPosition, args.yCursorPosition, displayTransform,
4318 args.downTime, args.eventTime, args.pointerCount,
4319 args.pointerProperties, args.pointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004320
4321 policyFlags |= POLICY_FLAG_FILTERED;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004322 if (!mPolicy.filterInputEvent(event, policyFlags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004323 return; // event was consumed by the filter
4324 }
4325
4326 mLock.lock();
4327 }
4328
4329 // Just enqueue a new motion event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004330 std::unique_ptr<MotionEntry> newEntry =
Prabir Pradhan678438e2023-04-13 19:32:51 +00004331 std::make_unique<MotionEntry>(args.id, args.eventTime, args.deviceId, args.source,
4332 args.displayId, policyFlags, args.action,
4333 args.actionButton, args.flags, args.metaState,
4334 args.buttonState, args.classification, args.edgeFlags,
4335 args.xPrecision, args.yPrecision,
4336 args.xCursorPosition, args.yCursorPosition,
4337 args.downTime, args.pointerCount,
4338 args.pointerProperties, args.pointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004339
Prabir Pradhan678438e2023-04-13 19:32:51 +00004340 if (args.id != android::os::IInputConstants::INVALID_INPUT_EVENT_ID &&
4341 IdGenerator::getSource(args.id) == IdGenerator::Source::INPUT_READER &&
Siarhei Vishniakou363e7292021-07-09 03:22:42 +00004342 !mInputFilterEnabled) {
Prabir Pradhan678438e2023-04-13 19:32:51 +00004343 const bool isDown = args.action == AMOTION_EVENT_ACTION_DOWN;
4344 mLatencyTracker.trackListener(args.id, isDown, args.eventTime, args.readTime);
Siarhei Vishniakou363e7292021-07-09 03:22:42 +00004345 }
4346
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004347 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004348 mLock.unlock();
4349 } // release lock
4350
4351 if (needWake) {
4352 mLooper->wake();
4353 }
4354}
4355
Prabir Pradhan678438e2023-04-13 19:32:51 +00004356void InputDispatcher::notifySensor(const NotifySensorArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004357 if (debugInboundEventDetails()) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004358 ALOGD("notifySensor - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=0x%x, "
4359 " sensorType=%s",
Prabir Pradhan678438e2023-04-13 19:32:51 +00004360 args.id, args.eventTime, args.deviceId, args.source,
4361 ftl::enum_string(args.sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004362 }
Chris Yef59a2f42020-10-16 12:55:26 -07004363
Antonio Kantekf16f2832021-09-28 04:39:20 +00004364 bool needWake = false;
Chris Yef59a2f42020-10-16 12:55:26 -07004365 { // acquire lock
4366 mLock.lock();
4367
4368 // Just enqueue a new sensor event.
4369 std::unique_ptr<SensorEntry> newEntry =
Prabir Pradhan678438e2023-04-13 19:32:51 +00004370 std::make_unique<SensorEntry>(args.id, args.eventTime, args.deviceId, args.source,
4371 /* policyFlags=*/0, args.hwTimestamp, args.sensorType,
4372 args.accuracy, args.accuracyChanged, args.values);
Chris Yef59a2f42020-10-16 12:55:26 -07004373
4374 needWake = enqueueInboundEventLocked(std::move(newEntry));
4375 mLock.unlock();
4376 } // release lock
4377
4378 if (needWake) {
4379 mLooper->wake();
4380 }
4381}
4382
Prabir Pradhan678438e2023-04-13 19:32:51 +00004383void InputDispatcher::notifyVibratorState(const NotifyVibratorStateArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004384 if (debugInboundEventDetails()) {
Prabir Pradhan678438e2023-04-13 19:32:51 +00004385 ALOGD("notifyVibratorState - eventTime=%" PRId64 ", device=%d, isOn=%d", args.eventTime,
4386 args.deviceId, args.isOn);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004387 }
Prabir Pradhana41d2442023-04-20 21:30:40 +00004388 mPolicy.notifyVibratorState(args.deviceId, args.isOn);
Chris Yefb552902021-02-03 17:18:37 -08004389}
4390
Prabir Pradhan678438e2023-04-13 19:32:51 +00004391bool InputDispatcher::shouldSendMotionToInputFilterLocked(const NotifyMotionArgs& args) {
Jackal Guof9696682018-10-05 12:23:23 +08004392 return mInputFilterEnabled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004393}
4394
Prabir Pradhan678438e2023-04-13 19:32:51 +00004395void InputDispatcher::notifySwitch(const NotifySwitchArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004396 if (debugInboundEventDetails()) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004397 ALOGD("notifySwitch - eventTime=%" PRId64 ", policyFlags=0x%x, switchValues=0x%08x, "
4398 "switchMask=0x%08x",
Prabir Pradhan678438e2023-04-13 19:32:51 +00004399 args.eventTime, args.policyFlags, args.switchValues, args.switchMask);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004400 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004401
Prabir Pradhan678438e2023-04-13 19:32:51 +00004402 uint32_t policyFlags = args.policyFlags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004403 policyFlags |= POLICY_FLAG_TRUSTED;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004404 mPolicy.notifySwitch(args.eventTime, args.switchValues, args.switchMask, policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004405}
4406
Prabir Pradhan678438e2023-04-13 19:32:51 +00004407void InputDispatcher::notifyDeviceReset(const NotifyDeviceResetArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004408 if (debugInboundEventDetails()) {
Prabir Pradhan678438e2023-04-13 19:32:51 +00004409 ALOGD("notifyDeviceReset - eventTime=%" PRId64 ", deviceId=%d", args.eventTime,
4410 args.deviceId);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004411 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004412
Antonio Kantekf16f2832021-09-28 04:39:20 +00004413 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004414 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004415 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004416
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004417 std::unique_ptr<DeviceResetEntry> newEntry =
Prabir Pradhan678438e2023-04-13 19:32:51 +00004418 std::make_unique<DeviceResetEntry>(args.id, args.eventTime, args.deviceId);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004419 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004420 } // release lock
4421
4422 if (needWake) {
4423 mLooper->wake();
4424 }
4425}
4426
Prabir Pradhan678438e2023-04-13 19:32:51 +00004427void InputDispatcher::notifyPointerCaptureChanged(const NotifyPointerCaptureChangedArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004428 if (debugInboundEventDetails()) {
Prabir Pradhan678438e2023-04-13 19:32:51 +00004429 ALOGD("notifyPointerCaptureChanged - eventTime=%" PRId64 ", enabled=%s", args.eventTime,
4430 args.request.enable ? "true" : "false");
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004431 }
Prabir Pradhan7e186182020-11-10 13:56:45 -08004432
Antonio Kantekf16f2832021-09-28 04:39:20 +00004433 bool needWake = false;
Prabir Pradhan99987712020-11-10 18:43:05 -08004434 { // acquire lock
4435 std::scoped_lock _l(mLock);
Prabir Pradhan678438e2023-04-13 19:32:51 +00004436 auto entry =
4437 std::make_unique<PointerCaptureChangedEntry>(args.id, args.eventTime, args.request);
Prabir Pradhan99987712020-11-10 18:43:05 -08004438 needWake = enqueueInboundEventLocked(std::move(entry));
4439 } // release lock
4440
4441 if (needWake) {
4442 mLooper->wake();
4443 }
Prabir Pradhan7e186182020-11-10 13:56:45 -08004444}
4445
Prabir Pradhan5735a322022-04-11 17:23:34 +00004446InputEventInjectionResult InputDispatcher::injectInputEvent(const InputEvent* event,
4447 std::optional<int32_t> targetUid,
4448 InputEventInjectionSync syncMode,
4449 std::chrono::milliseconds timeout,
4450 uint32_t policyFlags) {
Siarhei Vishniakou6773db62023-04-21 11:30:20 -07004451 Result<void> eventValidation = validateInputEvent(*event);
4452 if (!eventValidation.ok()) {
4453 LOG(INFO) << "Injection failed: invalid event: " << eventValidation.error();
4454 return InputEventInjectionResult::FAILED;
4455 }
4456
Prabir Pradhan65613802023-02-22 23:36:58 +00004457 if (debugInboundEventDetails()) {
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004458 LOG(DEBUG) << __func__ << ": targetUid=" << toString(targetUid)
4459 << ", syncMode=" << ftl::enum_string(syncMode) << ", timeout=" << timeout.count()
4460 << "ms, policyFlags=0x" << std::hex << policyFlags << std::dec
4461 << ", event=" << *event;
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004462 }
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07004463 nsecs_t endTime = now() + std::chrono::duration_cast<std::chrono::nanoseconds>(timeout).count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004464
Prabir Pradhan5735a322022-04-11 17:23:34 +00004465 policyFlags |= POLICY_FLAG_INJECTED | POLICY_FLAG_TRUSTED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004466
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004467 // For all injected events, set device id = VIRTUAL_KEYBOARD_ID. The only exception is events
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004468 // that have gone through the InputFilter. If the event passed through the InputFilter, assign
4469 // the provided device id. If the InputFilter is accessibility, and it modifies or synthesizes
4470 // the injected event, it is responsible for setting POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY.
4471 // For those events, we will set FLAG_IS_ACCESSIBILITY_EVENT to allow apps to distinguish them
4472 // from events that originate from actual hardware.
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004473 int32_t resolvedDeviceId = VIRTUAL_KEYBOARD_ID;
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004474 if (policyFlags & POLICY_FLAG_FILTERED) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004475 resolvedDeviceId = event->getDeviceId();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004476 }
4477
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004478 std::queue<std::unique_ptr<EventEntry>> injectedEntries;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004479 switch (event->getType()) {
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004480 case InputEventType::KEY: {
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004481 const KeyEvent& incomingKey = static_cast<const KeyEvent&>(*event);
Siarhei Vishniakou6773db62023-04-21 11:30:20 -07004482 const int32_t action = incomingKey.getAction();
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004483 int32_t flags = incomingKey.getFlags();
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004484 if (policyFlags & POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY) {
4485 flags |= AKEY_EVENT_FLAG_IS_ACCESSIBILITY_EVENT;
4486 }
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004487 int32_t keyCode = incomingKey.getKeyCode();
4488 int32_t metaState = incomingKey.getMetaState();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004489 accelerateMetaShortcuts(resolvedDeviceId, action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004490 /*byref*/ keyCode, /*byref*/ metaState);
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004491 KeyEvent keyEvent;
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004492 keyEvent.initialize(incomingKey.getId(), resolvedDeviceId, incomingKey.getSource(),
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004493 incomingKey.getDisplayId(), INVALID_HMAC, action, flags, keyCode,
4494 incomingKey.getScanCode(), metaState, incomingKey.getRepeatCount(),
4495 incomingKey.getDownTime(), incomingKey.getEventTime());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004496
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004497 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
4498 policyFlags |= POLICY_FLAG_VIRTUAL;
Michael Wright2b3c3302018-03-02 17:19:13 +00004499 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004500
4501 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
4502 android::base::Timer t;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004503 mPolicy.interceptKeyBeforeQueueing(keyEvent, /*byref*/ policyFlags);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004504 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4505 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
4506 std::to_string(t.duration().count()).c_str());
4507 }
4508 }
4509
4510 mLock.lock();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004511 std::unique_ptr<KeyEntry> injectedEntry =
4512 std::make_unique<KeyEntry>(incomingKey.getId(), incomingKey.getEventTime(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004513 resolvedDeviceId, incomingKey.getSource(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004514 incomingKey.getDisplayId(), policyFlags, action,
4515 flags, keyCode, incomingKey.getScanCode(), metaState,
4516 incomingKey.getRepeatCount(),
4517 incomingKey.getDownTime());
4518 injectedEntries.push(std::move(injectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004519 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004520 }
4521
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004522 case InputEventType::MOTION: {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004523 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(*event);
Prabir Pradhanaa561d12021-09-24 06:57:33 -07004524 const bool isPointerEvent =
4525 isFromSource(event->getSource(), AINPUT_SOURCE_CLASS_POINTER);
4526 // If a pointer event has no displayId specified, inject it to the default display.
4527 const uint32_t displayId = isPointerEvent && (event->getDisplayId() == ADISPLAY_ID_NONE)
4528 ? ADISPLAY_ID_DEFAULT
4529 : event->getDisplayId();
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004530 int32_t flags = motionEvent.getFlags();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004531
4532 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004533 nsecs_t eventTime = motionEvent.getEventTime();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004534 android::base::Timer t;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004535 mPolicy.interceptMotionBeforeQueueing(displayId, eventTime, /*byref*/ policyFlags);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004536 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4537 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
4538 std::to_string(t.duration().count()).c_str());
4539 }
4540 }
4541
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004542 if (policyFlags & POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY) {
4543 flags |= AMOTION_EVENT_FLAG_IS_ACCESSIBILITY_EVENT;
4544 }
4545
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004546 mLock.lock();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004547 const nsecs_t* sampleEventTimes = motionEvent.getSampleEventTimes();
4548 const PointerCoords* samplePointerCoords = motionEvent.getSamplePointerCoords();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004549 std::unique_ptr<MotionEntry> injectedEntry =
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004550 std::make_unique<MotionEntry>(motionEvent.getId(), *sampleEventTimes,
4551 resolvedDeviceId, motionEvent.getSource(),
Siarhei Vishniakou6773db62023-04-21 11:30:20 -07004552 displayId, policyFlags, motionEvent.getAction(),
4553 motionEvent.getActionButton(), flags,
4554 motionEvent.getMetaState(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004555 motionEvent.getButtonState(),
4556 motionEvent.getClassification(),
4557 motionEvent.getEdgeFlags(),
4558 motionEvent.getXPrecision(),
4559 motionEvent.getYPrecision(),
4560 motionEvent.getRawXCursorPosition(),
4561 motionEvent.getRawYCursorPosition(),
Siarhei Vishniakou6773db62023-04-21 11:30:20 -07004562 motionEvent.getDownTime(),
4563 motionEvent.getPointerCount(),
4564 motionEvent.getPointerProperties(),
4565 samplePointerCoords);
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004566 transformMotionEntryForInjectionLocked(*injectedEntry, motionEvent.getTransform());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004567 injectedEntries.push(std::move(injectedEntry));
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004568 for (size_t i = motionEvent.getHistorySize(); i > 0; i--) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004569 sampleEventTimes += 1;
Siarhei Vishniakou6773db62023-04-21 11:30:20 -07004570 samplePointerCoords += motionEvent.getPointerCount();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004571 std::unique_ptr<MotionEntry> nextInjectedEntry =
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004572 std::make_unique<MotionEntry>(motionEvent.getId(), *sampleEventTimes,
4573 resolvedDeviceId, motionEvent.getSource(),
Siarhei Vishniakou6773db62023-04-21 11:30:20 -07004574 displayId, policyFlags,
4575 motionEvent.getAction(),
4576 motionEvent.getActionButton(), flags,
4577 motionEvent.getMetaState(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004578 motionEvent.getButtonState(),
4579 motionEvent.getClassification(),
4580 motionEvent.getEdgeFlags(),
4581 motionEvent.getXPrecision(),
4582 motionEvent.getYPrecision(),
4583 motionEvent.getRawXCursorPosition(),
4584 motionEvent.getRawYCursorPosition(),
4585 motionEvent.getDownTime(),
Siarhei Vishniakou6773db62023-04-21 11:30:20 -07004586 motionEvent.getPointerCount(),
4587 motionEvent.getPointerProperties(),
Prabir Pradhan5beda762021-12-10 09:30:08 +00004588 samplePointerCoords);
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004589 transformMotionEntryForInjectionLocked(*nextInjectedEntry,
4590 motionEvent.getTransform());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004591 injectedEntries.push(std::move(nextInjectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004592 }
4593 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004594 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004595
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004596 default:
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004597 LOG(WARNING) << "Cannot inject " << ftl::enum_string(event->getType()) << " events";
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004598 return InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004599 }
4600
Prabir Pradhan5735a322022-04-11 17:23:34 +00004601 InjectionState* injectionState = new InjectionState(targetUid);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004602 if (syncMode == InputEventInjectionSync::NONE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004603 injectionState->injectionIsAsync = true;
4604 }
4605
4606 injectionState->refCount += 1;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004607 injectedEntries.back()->injectionState = injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004608
4609 bool needWake = false;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004610 while (!injectedEntries.empty()) {
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08004611 if (DEBUG_INJECTION) {
4612 LOG(DEBUG) << "Injecting " << injectedEntries.front()->getDescription();
4613 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004614 needWake |= enqueueInboundEventLocked(std::move(injectedEntries.front()));
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004615 injectedEntries.pop();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004616 }
4617
4618 mLock.unlock();
4619
4620 if (needWake) {
4621 mLooper->wake();
4622 }
4623
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004624 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004625 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004626 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004627
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004628 if (syncMode == InputEventInjectionSync::NONE) {
4629 injectionResult = InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004630 } else {
4631 for (;;) {
4632 injectionResult = injectionState->injectionResult;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004633 if (injectionResult != InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004634 break;
4635 }
4636
4637 nsecs_t remainingTimeout = endTime - now();
4638 if (remainingTimeout <= 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004639 if (DEBUG_INJECTION) {
4640 ALOGD("injectInputEvent - Timed out waiting for injection result "
4641 "to become available.");
4642 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004643 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004644 break;
4645 }
4646
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004647 mInjectionResultAvailable.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004648 }
4649
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004650 if (injectionResult == InputEventInjectionResult::SUCCEEDED &&
4651 syncMode == InputEventInjectionSync::WAIT_FOR_FINISHED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004652 while (injectionState->pendingForegroundDispatches != 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004653 if (DEBUG_INJECTION) {
4654 ALOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
4655 injectionState->pendingForegroundDispatches);
4656 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004657 nsecs_t remainingTimeout = endTime - now();
4658 if (remainingTimeout <= 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004659 if (DEBUG_INJECTION) {
4660 ALOGD("injectInputEvent - Timed out waiting for pending foreground "
4661 "dispatches to finish.");
4662 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004663 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004664 break;
4665 }
4666
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004667 mInjectionSyncFinished.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004668 }
4669 }
4670 }
4671
4672 injectionState->release();
4673 } // release lock
4674
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004675 if (DEBUG_INJECTION) {
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08004676 LOG(DEBUG) << "injectInputEvent - Finished with result "
4677 << ftl::enum_string(injectionResult);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004678 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004679
4680 return injectionResult;
4681}
4682
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004683std::unique_ptr<VerifiedInputEvent> InputDispatcher::verifyInputEvent(const InputEvent& event) {
Gang Wange9087892020-01-07 12:17:14 -05004684 std::array<uint8_t, 32> calculatedHmac;
4685 std::unique_ptr<VerifiedInputEvent> result;
4686 switch (event.getType()) {
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004687 case InputEventType::KEY: {
Gang Wange9087892020-01-07 12:17:14 -05004688 const KeyEvent& keyEvent = static_cast<const KeyEvent&>(event);
4689 VerifiedKeyEvent verifiedKeyEvent = verifiedKeyEventFromKeyEvent(keyEvent);
4690 result = std::make_unique<VerifiedKeyEvent>(verifiedKeyEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004691 calculatedHmac = sign(verifiedKeyEvent);
Gang Wange9087892020-01-07 12:17:14 -05004692 break;
4693 }
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004694 case InputEventType::MOTION: {
Gang Wange9087892020-01-07 12:17:14 -05004695 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(event);
4696 VerifiedMotionEvent verifiedMotionEvent =
4697 verifiedMotionEventFromMotionEvent(motionEvent);
4698 result = std::make_unique<VerifiedMotionEvent>(verifiedMotionEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004699 calculatedHmac = sign(verifiedMotionEvent);
Gang Wange9087892020-01-07 12:17:14 -05004700 break;
4701 }
4702 default: {
4703 ALOGE("Cannot verify events of type %" PRId32, event.getType());
4704 return nullptr;
4705 }
4706 }
4707 if (calculatedHmac == INVALID_HMAC) {
4708 return nullptr;
4709 }
tyiu1573a672023-02-21 22:38:32 +00004710 if (0 != CRYPTO_memcmp(calculatedHmac.data(), event.getHmac().data(), calculatedHmac.size())) {
Gang Wange9087892020-01-07 12:17:14 -05004711 return nullptr;
4712 }
4713 return result;
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004714}
4715
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004716void InputDispatcher::setInjectionResult(EventEntry& entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004717 InputEventInjectionResult injectionResult) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004718 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004719 if (injectionState) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004720 if (DEBUG_INJECTION) {
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08004721 LOG(DEBUG) << "Setting input event injection result to "
4722 << ftl::enum_string(injectionResult);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004723 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004724
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004725 if (injectionState->injectionIsAsync && !(entry.policyFlags & POLICY_FLAG_FILTERED)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004726 // Log the outcome since the injector did not wait for the injection result.
4727 switch (injectionResult) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004728 case InputEventInjectionResult::SUCCEEDED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004729 ALOGV("Asynchronous input event injection succeeded.");
4730 break;
Prabir Pradhan5735a322022-04-11 17:23:34 +00004731 case InputEventInjectionResult::TARGET_MISMATCH:
4732 ALOGV("Asynchronous input event injection target mismatch.");
4733 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004734 case InputEventInjectionResult::FAILED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004735 ALOGW("Asynchronous input event injection failed.");
4736 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004737 case InputEventInjectionResult::TIMED_OUT:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004738 ALOGW("Asynchronous input event injection timed out.");
4739 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004740 case InputEventInjectionResult::PENDING:
4741 ALOGE("Setting result to 'PENDING' for asynchronous injection");
4742 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004743 }
4744 }
4745
4746 injectionState->injectionResult = injectionResult;
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004747 mInjectionResultAvailable.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004748 }
4749}
4750
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004751void InputDispatcher::transformMotionEntryForInjectionLocked(
4752 MotionEntry& entry, const ui::Transform& injectedTransform) const {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004753 // Input injection works in the logical display coordinate space, but the input pipeline works
4754 // display space, so we need to transform the injected events accordingly.
4755 const auto it = mDisplayInfos.find(entry.displayId);
4756 if (it == mDisplayInfos.end()) return;
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004757 const auto& transformToDisplay = it->second.transform.inverse() * injectedTransform;
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004758
Prabir Pradhand9a2ebe2022-07-20 19:25:13 +00004759 if (entry.xCursorPosition != AMOTION_EVENT_INVALID_CURSOR_POSITION &&
4760 entry.yCursorPosition != AMOTION_EVENT_INVALID_CURSOR_POSITION) {
4761 const vec2 cursor =
4762 MotionEvent::calculateTransformedXY(entry.source, transformToDisplay,
4763 {entry.xCursorPosition, entry.yCursorPosition});
4764 entry.xCursorPosition = cursor.x;
4765 entry.yCursorPosition = cursor.y;
4766 }
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004767 for (uint32_t i = 0; i < entry.pointerCount; i++) {
Prabir Pradhan8e6ce222022-02-24 09:08:54 -08004768 entry.pointerCoords[i] =
4769 MotionEvent::calculateTransformedCoords(entry.source, transformToDisplay,
4770 entry.pointerCoords[i]);
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004771 }
4772}
4773
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004774void InputDispatcher::incrementPendingForegroundDispatches(EventEntry& entry) {
4775 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004776 if (injectionState) {
4777 injectionState->pendingForegroundDispatches += 1;
4778 }
4779}
4780
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004781void InputDispatcher::decrementPendingForegroundDispatches(EventEntry& entry) {
4782 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004783 if (injectionState) {
4784 injectionState->pendingForegroundDispatches -= 1;
4785
4786 if (injectionState->pendingForegroundDispatches == 0) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004787 mInjectionSyncFinished.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004788 }
4789 }
4790}
4791
chaviw98318de2021-05-19 16:45:23 -05004792const std::vector<sp<WindowInfoHandle>>& InputDispatcher::getWindowHandlesLocked(
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004793 int32_t displayId) const {
chaviw98318de2021-05-19 16:45:23 -05004794 static const std::vector<sp<WindowInfoHandle>> EMPTY_WINDOW_HANDLES;
Vishnu Nairad321cd2020-08-20 16:40:21 -07004795 auto it = mWindowHandlesByDisplay.find(displayId);
4796 return it != mWindowHandlesByDisplay.end() ? it->second : EMPTY_WINDOW_HANDLES;
Arthur Hungb92218b2018-08-14 12:00:21 +08004797}
4798
chaviw98318de2021-05-19 16:45:23 -05004799sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(
chaviwfbe5d9c2018-12-26 12:23:37 -08004800 const sp<IBinder>& windowHandleToken) const {
arthurhungbe737672020-06-24 12:29:21 +08004801 if (windowHandleToken == nullptr) {
4802 return nullptr;
4803 }
4804
Arthur Hungb92218b2018-08-14 12:00:21 +08004805 for (auto& it : mWindowHandlesByDisplay) {
chaviw98318de2021-05-19 16:45:23 -05004806 const std::vector<sp<WindowInfoHandle>>& windowHandles = it.second;
4807 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
chaviwfbe5d9c2018-12-26 12:23:37 -08004808 if (windowHandle->getToken() == windowHandleToken) {
Arthur Hungb92218b2018-08-14 12:00:21 +08004809 return windowHandle;
4810 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004811 }
4812 }
Yi Kong9b14ac62018-07-17 13:48:38 -07004813 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004814}
4815
chaviw98318de2021-05-19 16:45:23 -05004816sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(const sp<IBinder>& windowHandleToken,
4817 int displayId) const {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004818 if (windowHandleToken == nullptr) {
4819 return nullptr;
4820 }
4821
chaviw98318de2021-05-19 16:45:23 -05004822 for (const sp<WindowInfoHandle>& windowHandle : getWindowHandlesLocked(displayId)) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004823 if (windowHandle->getToken() == windowHandleToken) {
4824 return windowHandle;
4825 }
4826 }
4827 return nullptr;
4828}
4829
chaviw98318de2021-05-19 16:45:23 -05004830sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(
4831 const sp<WindowInfoHandle>& windowHandle) const {
Mady Mellor017bcd12020-06-23 19:12:00 +00004832 for (auto& it : mWindowHandlesByDisplay) {
chaviw98318de2021-05-19 16:45:23 -05004833 const std::vector<sp<WindowInfoHandle>>& windowHandles = it.second;
4834 for (const sp<WindowInfoHandle>& handle : windowHandles) {
arthurhungbe737672020-06-24 12:29:21 +08004835 if (handle->getId() == windowHandle->getId() &&
4836 handle->getToken() == windowHandle->getToken()) {
Mady Mellor017bcd12020-06-23 19:12:00 +00004837 if (windowHandle->getInfo()->displayId != it.first) {
4838 ALOGE("Found window %s in display %" PRId32
4839 ", but it should belong to display %" PRId32,
4840 windowHandle->getName().c_str(), it.first,
4841 windowHandle->getInfo()->displayId);
4842 }
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004843 return handle;
Arthur Hungb92218b2018-08-14 12:00:21 +08004844 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004845 }
4846 }
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004847 return nullptr;
4848}
4849
chaviw98318de2021-05-19 16:45:23 -05004850sp<WindowInfoHandle> InputDispatcher::getFocusedWindowHandleLocked(int displayId) const {
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004851 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(displayId);
4852 return getWindowHandleLocked(focusedToken, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004853}
4854
Prabir Pradhan33e3baa2022-12-06 20:30:22 +00004855ui::Transform InputDispatcher::getTransformLocked(int32_t displayId) const {
4856 auto displayInfoIt = mDisplayInfos.find(displayId);
4857 return displayInfoIt != mDisplayInfos.end() ? displayInfoIt->second.transform
4858 : kIdentityTransform;
4859}
4860
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004861bool InputDispatcher::canWindowReceiveMotionLocked(const sp<WindowInfoHandle>& window,
4862 const MotionEntry& motionEntry) const {
4863 const WindowInfo& info = *window->getInfo();
4864
4865 // Skip spy window targets that are not valid for targeted injection.
4866 if (const auto err = verifyTargetedInjection(window, motionEntry); err) {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004867 return false;
4868 }
4869
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004870 if (info.inputConfig.test(WindowInfo::InputConfig::PAUSE_DISPATCHING)) {
4871 ALOGI("Not sending touch event to %s because it is paused", window->getName().c_str());
4872 return false;
4873 }
4874
4875 if (info.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL)) {
4876 ALOGW("Not sending touch gesture to %s because it has config NO_INPUT_CHANNEL",
4877 window->getName().c_str());
4878 return false;
4879 }
4880
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07004881 std::shared_ptr<Connection> connection = getConnectionLocked(window->getToken());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004882 if (connection == nullptr) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004883 ALOGW("Not sending touch to %s because there's no corresponding connection",
4884 window->getName().c_str());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004885 return false;
4886 }
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004887
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004888 if (!connection->responsive) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004889 ALOGW("Not sending touch to %s because it is not responsive", window->getName().c_str());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004890 return false;
4891 }
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004892
4893 // Drop events that can't be trusted due to occlusion
4894 const auto [x, y] = resolveTouchedPosition(motionEntry);
4895 TouchOcclusionInfo occlusionInfo = computeTouchOcclusionInfoLocked(window, x, y);
4896 if (!isTouchTrustedLocked(occlusionInfo)) {
4897 if (DEBUG_TOUCH_OCCLUSION) {
Prabir Pradhan82e081e2022-12-06 09:50:09 +00004898 ALOGD("Stack of obscuring windows during untrusted touch (%.1f, %.1f):", x, y);
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004899 for (const auto& log : occlusionInfo.debugInfo) {
4900 ALOGD("%s", log.c_str());
4901 }
4902 }
4903 ALOGW("Dropping untrusted touch event due to %s/%d", occlusionInfo.obscuringPackage.c_str(),
4904 occlusionInfo.obscuringUid);
4905 return false;
4906 }
4907
4908 // Drop touch events if requested by input feature
4909 if (shouldDropInput(motionEntry, window)) {
4910 return false;
4911 }
4912
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004913 return true;
4914}
4915
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004916std::shared_ptr<InputChannel> InputDispatcher::getInputChannelLocked(
4917 const sp<IBinder>& token) const {
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00004918 auto connectionIt = mConnectionsByToken.find(token);
4919 if (connectionIt == mConnectionsByToken.end()) {
Robert Carr5c8a0262018-10-03 16:30:44 -07004920 return nullptr;
4921 }
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00004922 return connectionIt->second->inputChannel;
Robert Carr5c8a0262018-10-03 16:30:44 -07004923}
4924
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004925void InputDispatcher::updateWindowHandlesForDisplayLocked(
chaviw98318de2021-05-19 16:45:23 -05004926 const std::vector<sp<WindowInfoHandle>>& windowInfoHandles, int32_t displayId) {
4927 if (windowInfoHandles.empty()) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004928 // Remove all handles on a display if there are no windows left.
4929 mWindowHandlesByDisplay.erase(displayId);
4930 return;
4931 }
4932
4933 // Since we compare the pointer of input window handles across window updates, we need
4934 // to make sure the handle object for the same window stays unchanged across updates.
chaviw98318de2021-05-19 16:45:23 -05004935 const std::vector<sp<WindowInfoHandle>>& oldHandles = getWindowHandlesLocked(displayId);
4936 std::unordered_map<int32_t /*id*/, sp<WindowInfoHandle>> oldHandlesById;
4937 for (const sp<WindowInfoHandle>& handle : oldHandles) {
chaviwaf87b3e2019-10-01 16:59:28 -07004938 oldHandlesById[handle->getId()] = handle;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004939 }
4940
chaviw98318de2021-05-19 16:45:23 -05004941 std::vector<sp<WindowInfoHandle>> newHandles;
4942 for (const sp<WindowInfoHandle>& handle : windowInfoHandles) {
chaviw98318de2021-05-19 16:45:23 -05004943 const WindowInfo* info = handle->getInfo();
Siarhei Vishniakou64452932020-11-06 17:51:32 -06004944 if (getInputChannelLocked(handle->getToken()) == nullptr) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004945 const bool noInputChannel =
Prabir Pradhan51e7db02022-02-07 06:02:57 -08004946 info->inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08004947 const bool canReceiveInput =
4948 !info->inputConfig.test(WindowInfo::InputConfig::NOT_TOUCHABLE) ||
4949 !info->inputConfig.test(WindowInfo::InputConfig::NOT_FOCUSABLE);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004950 if (canReceiveInput && !noInputChannel) {
John Recke0710582019-09-26 13:46:12 -07004951 ALOGV("Window handle %s has no registered input channel",
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004952 handle->getName().c_str());
Robert Carr2984b7a2020-04-13 17:06:45 -07004953 continue;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004954 }
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004955 }
4956
4957 if (info->displayId != displayId) {
4958 ALOGE("Window %s updated by wrong display %d, should belong to display %d",
4959 handle->getName().c_str(), displayId, info->displayId);
4960 continue;
4961 }
4962
Robert Carredd13602020-04-13 17:24:34 -07004963 if ((oldHandlesById.find(handle->getId()) != oldHandlesById.end()) &&
4964 (oldHandlesById.at(handle->getId())->getToken() == handle->getToken())) {
chaviw98318de2021-05-19 16:45:23 -05004965 const sp<WindowInfoHandle>& oldHandle = oldHandlesById.at(handle->getId());
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004966 oldHandle->updateFrom(handle);
4967 newHandles.push_back(oldHandle);
4968 } else {
4969 newHandles.push_back(handle);
4970 }
4971 }
4972
4973 // Insert or replace
4974 mWindowHandlesByDisplay[displayId] = newHandles;
4975}
4976
Arthur Hung72d8dc32020-03-28 00:48:39 +00004977void InputDispatcher::setInputWindows(
chaviw98318de2021-05-19 16:45:23 -05004978 const std::unordered_map<int32_t, std::vector<sp<WindowInfoHandle>>>& handlesPerDisplay) {
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07004979 // TODO(b/198444055): Remove setInputWindows from InputDispatcher.
Arthur Hung72d8dc32020-03-28 00:48:39 +00004980 { // acquire lock
4981 std::scoped_lock _l(mLock);
Siarhei Vishniakou2508b872020-12-03 16:33:53 -10004982 for (const auto& [displayId, handles] : handlesPerDisplay) {
4983 setInputWindowsLocked(handles, displayId);
Arthur Hung72d8dc32020-03-28 00:48:39 +00004984 }
4985 }
4986 // Wake up poll loop since it may need to make new input dispatching choices.
4987 mLooper->wake();
4988}
4989
Arthur Hungb92218b2018-08-14 12:00:21 +08004990/**
4991 * Called from InputManagerService, update window handle list by displayId that can receive input.
4992 * A window handle contains information about InputChannel, Touch Region, Types, Focused,...
4993 * If set an empty list, remove all handles from the specific display.
4994 * For focused handle, check if need to change and send a cancel event to previous one.
4995 * For removed handle, check if need to send a cancel event if already in touch.
4996 */
Arthur Hung72d8dc32020-03-28 00:48:39 +00004997void InputDispatcher::setInputWindowsLocked(
chaviw98318de2021-05-19 16:45:23 -05004998 const std::vector<sp<WindowInfoHandle>>& windowInfoHandles, int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004999 if (DEBUG_FOCUS) {
5000 std::string windowList;
chaviw98318de2021-05-19 16:45:23 -05005001 for (const sp<WindowInfoHandle>& iwh : windowInfoHandles) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005002 windowList += iwh->getName() + " ";
5003 }
5004 ALOGD("setInputWindows displayId=%" PRId32 " %s", displayId, windowList.c_str());
5005 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005006
Prabir Pradhand65552b2021-10-07 11:23:50 -07005007 // Check preconditions for new input windows
chaviw98318de2021-05-19 16:45:23 -05005008 for (const sp<WindowInfoHandle>& window : windowInfoHandles) {
Prabir Pradhand65552b2021-10-07 11:23:50 -07005009 const WindowInfo& info = *window->getInfo();
5010
5011 // Ensure all tokens are null if the window has feature NO_INPUT_CHANNEL
Prabir Pradhan51e7db02022-02-07 06:02:57 -08005012 const bool noInputWindow = info.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005013 if (noInputWindow && window->getToken() != nullptr) {
5014 ALOGE("%s has feature NO_INPUT_WINDOW, but a non-null token. Clearing",
5015 window->getName().c_str());
5016 window->releaseChannel();
5017 }
Prabir Pradhand65552b2021-10-07 11:23:50 -07005018
Prabir Pradhan5c85e052021-12-22 02:27:12 -08005019 // Ensure all spy windows are trusted overlays
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005020 LOG_ALWAYS_FATAL_IF(info.isSpy() &&
5021 !info.inputConfig.test(
5022 WindowInfo::InputConfig::TRUSTED_OVERLAY),
Prabir Pradhan5c85e052021-12-22 02:27:12 -08005023 "%s has feature SPY, but is not a trusted overlay.",
5024 window->getName().c_str());
5025
Prabir Pradhand65552b2021-10-07 11:23:50 -07005026 // Ensure all stylus interceptors are trusted overlays
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005027 LOG_ALWAYS_FATAL_IF(info.interceptsStylus() &&
5028 !info.inputConfig.test(
5029 WindowInfo::InputConfig::TRUSTED_OVERLAY),
Prabir Pradhand65552b2021-10-07 11:23:50 -07005030 "%s has feature INTERCEPTS_STYLUS, but is not a trusted overlay.",
5031 window->getName().c_str());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005032 }
5033
Arthur Hung72d8dc32020-03-28 00:48:39 +00005034 // Copy old handles for release if they are no longer present.
chaviw98318de2021-05-19 16:45:23 -05005035 const std::vector<sp<WindowInfoHandle>> oldWindowHandles = getWindowHandlesLocked(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005036
Prabir Pradhan93a0f912021-04-21 13:47:42 -07005037 // Save the old windows' orientation by ID before it gets updated.
5038 std::unordered_map<int32_t, uint32_t> oldWindowOrientations;
chaviw98318de2021-05-19 16:45:23 -05005039 for (const sp<WindowInfoHandle>& handle : oldWindowHandles) {
Prabir Pradhan93a0f912021-04-21 13:47:42 -07005040 oldWindowOrientations.emplace(handle->getId(),
5041 handle->getInfo()->transform.getOrientation());
5042 }
5043
chaviw98318de2021-05-19 16:45:23 -05005044 updateWindowHandlesForDisplayLocked(windowInfoHandles, displayId);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005045
chaviw98318de2021-05-19 16:45:23 -05005046 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Arthur Hung72d8dc32020-03-28 00:48:39 +00005047
Vishnu Nairc519ff72021-01-21 08:23:08 -08005048 std::optional<FocusResolver::FocusChanges> changes =
5049 mFocusResolver.setInputWindows(displayId, windowHandles);
5050 if (changes) {
5051 onFocusChangedLocked(*changes);
Arthur Hung72d8dc32020-03-28 00:48:39 +00005052 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005053
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005054 std::unordered_map<int32_t, TouchState>::iterator stateIt =
5055 mTouchStatesByDisplay.find(displayId);
5056 if (stateIt != mTouchStatesByDisplay.end()) {
5057 TouchState& state = stateIt->second;
Arthur Hung72d8dc32020-03-28 00:48:39 +00005058 for (size_t i = 0; i < state.windows.size();) {
5059 TouchedWindow& touchedWindow = state.windows[i];
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07005060 if (getWindowHandleLocked(touchedWindow.windowHandle) == nullptr) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005061 if (DEBUG_FOCUS) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00005062 ALOGD("Touched window was removed: %s in display %" PRId32,
5063 touchedWindow.windowHandle->getName().c_str(), displayId);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005064 }
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005065 std::shared_ptr<InputChannel> touchedInputChannel =
Arthur Hung72d8dc32020-03-28 00:48:39 +00005066 getInputChannelLocked(touchedWindow.windowHandle->getToken());
5067 if (touchedInputChannel != nullptr) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00005068 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
Arthur Hung72d8dc32020-03-28 00:48:39 +00005069 "touched window was removed");
5070 synthesizeCancelationEventsForInputChannelLocked(touchedInputChannel, options);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00005071 // Since we are about to drop the touch, cancel the events for the wallpaper as
5072 // well.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005073 if (touchedWindow.targetFlags.test(InputTarget::Flags::FOREGROUND) &&
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005074 touchedWindow.windowHandle->getInfo()->inputConfig.test(
5075 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER)) {
Siarhei Vishniakouca205502021-07-16 21:31:58 +00005076 sp<WindowInfoHandle> wallpaper = state.getWallpaperWindow();
Arthur Hungc539dbb2022-12-08 07:45:36 +00005077 synthesizeCancelationEventsForWindowLocked(wallpaper, options);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00005078 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005079 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00005080 state.windows.erase(state.windows.begin() + i);
5081 } else {
5082 ++i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005083 }
5084 }
arthurhungb89ccb02020-12-30 16:19:01 +08005085
arthurhung6d4bed92021-03-17 11:59:33 +08005086 // If drag window is gone, it would receive a cancel event and broadcast the DRAG_END. We
arthurhungb89ccb02020-12-30 16:19:01 +08005087 // could just clear the state here.
Arthur Hung3915c1f2022-05-31 07:17:17 +00005088 if (mDragState && mDragState->dragWindow->getInfo()->displayId == displayId &&
arthurhung6d4bed92021-03-17 11:59:33 +08005089 std::find(windowHandles.begin(), windowHandles.end(), mDragState->dragWindow) ==
arthurhungb89ccb02020-12-30 16:19:01 +08005090 windowHandles.end()) {
Arthur Hung3915c1f2022-05-31 07:17:17 +00005091 ALOGI("Drag window went away: %s", mDragState->dragWindow->getName().c_str());
5092 sendDropWindowCommandLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08005093 mDragState.reset();
arthurhungb89ccb02020-12-30 16:19:01 +08005094 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00005095 }
Arthur Hung25e2af12020-03-26 12:58:37 +00005096
Prabir Pradhan8b89c2f2021-07-29 16:30:14 +00005097 // Determine if the orientation of any of the input windows have changed, and cancel all
5098 // pointer events if necessary.
5099 for (const sp<WindowInfoHandle>& oldWindowHandle : oldWindowHandles) {
5100 const sp<WindowInfoHandle> newWindowHandle = getWindowHandleLocked(oldWindowHandle);
5101 if (newWindowHandle != nullptr &&
5102 newWindowHandle->getInfo()->transform.getOrientation() !=
5103 oldWindowOrientations[oldWindowHandle->getId()]) {
5104 std::shared_ptr<InputChannel> inputChannel =
5105 getInputChannelLocked(newWindowHandle->getToken());
5106 if (inputChannel != nullptr) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00005107 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
Prabir Pradhan8b89c2f2021-07-29 16:30:14 +00005108 "touched window's orientation changed");
5109 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
Prabir Pradhan93a0f912021-04-21 13:47:42 -07005110 }
5111 }
5112 }
5113
Arthur Hung72d8dc32020-03-28 00:48:39 +00005114 // Release information for windows that are no longer present.
5115 // This ensures that unused input channels are released promptly.
5116 // Otherwise, they might stick around until the window handle is destroyed
5117 // which might not happen until the next GC.
chaviw98318de2021-05-19 16:45:23 -05005118 for (const sp<WindowInfoHandle>& oldWindowHandle : oldWindowHandles) {
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07005119 if (getWindowHandleLocked(oldWindowHandle) == nullptr) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00005120 if (DEBUG_FOCUS) {
5121 ALOGD("Window went away: %s", oldWindowHandle->getName().c_str());
Arthur Hung25e2af12020-03-26 12:58:37 +00005122 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00005123 oldWindowHandle->releaseChannel();
Arthur Hung25e2af12020-03-26 12:58:37 +00005124 }
chaviw291d88a2019-02-14 10:33:58 -08005125 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005126}
5127
5128void InputDispatcher::setFocusedApplication(
Chris Yea209fde2020-07-22 13:54:51 -07005129 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005130 if (DEBUG_FOCUS) {
5131 ALOGD("setFocusedApplication displayId=%" PRId32 " %s", displayId,
5132 inputApplicationHandle ? inputApplicationHandle->getName().c_str() : "<nullptr>");
5133 }
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05005134 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005135 std::scoped_lock _l(mLock);
Vishnu Nair599f1412021-06-21 10:39:58 -07005136 setFocusedApplicationLocked(displayId, inputApplicationHandle);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005137 } // release lock
5138
5139 // Wake up poll loop since it may need to make new input dispatching choices.
5140 mLooper->wake();
5141}
5142
Vishnu Nair599f1412021-06-21 10:39:58 -07005143void InputDispatcher::setFocusedApplicationLocked(
5144 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
5145 std::shared_ptr<InputApplicationHandle> oldFocusedApplicationHandle =
5146 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
5147
5148 if (sharedPointersEqual(oldFocusedApplicationHandle, inputApplicationHandle)) {
5149 return; // This application is already focused. No need to wake up or change anything.
5150 }
5151
5152 // Set the new application handle.
5153 if (inputApplicationHandle != nullptr) {
5154 mFocusedApplicationHandlesByDisplay[displayId] = inputApplicationHandle;
5155 } else {
5156 mFocusedApplicationHandlesByDisplay.erase(displayId);
5157 }
5158
5159 // No matter what the old focused application was, stop waiting on it because it is
5160 // no longer focused.
5161 resetNoFocusedWindowTimeoutLocked();
5162}
5163
Tiger Huang721e26f2018-07-24 22:26:19 +08005164/**
5165 * Sets the focused display, which is responsible for receiving focus-dispatched input events where
5166 * the display not specified.
5167 *
5168 * We track any unreleased events for each window. If a window loses the ability to receive the
5169 * released event, we will send a cancel event to it. So when the focused display is changed, we
5170 * cancel all the unreleased display-unspecified events for the focused window on the old focused
5171 * display. The display-specified events won't be affected.
5172 */
5173void InputDispatcher::setFocusedDisplay(int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005174 if (DEBUG_FOCUS) {
5175 ALOGD("setFocusedDisplay displayId=%" PRId32, displayId);
5176 }
Tiger Huang721e26f2018-07-24 22:26:19 +08005177 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005178 std::scoped_lock _l(mLock);
Tiger Huang721e26f2018-07-24 22:26:19 +08005179
5180 if (mFocusedDisplayId != displayId) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07005181 sp<IBinder> oldFocusedWindowToken =
Vishnu Nairc519ff72021-01-21 08:23:08 -08005182 mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07005183 if (oldFocusedWindowToken != nullptr) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005184 std::shared_ptr<InputChannel> inputChannel =
Vishnu Nairad321cd2020-08-20 16:40:21 -07005185 getInputChannelLocked(oldFocusedWindowToken);
Tiger Huang721e26f2018-07-24 22:26:19 +08005186 if (inputChannel != nullptr) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005187 CancelationOptions
Michael Wrightfb04fd52022-11-24 22:31:11 +00005188 options(CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005189 "The display which contains this window no longer has focus.");
Michael Wright3dd60e22019-03-27 22:06:44 +00005190 options.displayId = ADISPLAY_ID_NONE;
Tiger Huang721e26f2018-07-24 22:26:19 +08005191 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
5192 }
5193 }
5194 mFocusedDisplayId = displayId;
5195
Chris Ye3c2d6f52020-08-09 10:39:48 -07005196 // Find new focused window and validate
Vishnu Nairc519ff72021-01-21 08:23:08 -08005197 sp<IBinder> newFocusedWindowToken = mFocusResolver.getFocusedWindowToken(displayId);
Prabir Pradhancef936d2021-07-21 16:17:52 +00005198 sendFocusChangedCommandLocked(oldFocusedWindowToken, newFocusedWindowToken);
Robert Carrf759f162018-11-13 12:57:11 -08005199
Vishnu Nairad321cd2020-08-20 16:40:21 -07005200 if (newFocusedWindowToken == nullptr) {
Tiger Huang721e26f2018-07-24 22:26:19 +08005201 ALOGW("Focused display #%" PRId32 " does not have a focused window.", displayId);
Vishnu Nairc519ff72021-01-21 08:23:08 -08005202 if (mFocusResolver.hasFocusedWindowTokens()) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07005203 ALOGE("But another display has a focused window\n%s",
Vishnu Nairc519ff72021-01-21 08:23:08 -08005204 mFocusResolver.dumpFocusedWindows().c_str());
Tiger Huang721e26f2018-07-24 22:26:19 +08005205 }
5206 }
5207 }
Tiger Huang721e26f2018-07-24 22:26:19 +08005208 } // release lock
5209
5210 // Wake up poll loop since it may need to make new input dispatching choices.
5211 mLooper->wake();
5212}
5213
Michael Wrightd02c5b62014-02-10 15:10:22 -08005214void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005215 if (DEBUG_FOCUS) {
5216 ALOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
5217 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005218
5219 bool changed;
5220 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005221 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005222
5223 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
5224 if (mDispatchFrozen && !frozen) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005225 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005226 }
5227
5228 if (mDispatchEnabled && !enabled) {
5229 resetAndDropEverythingLocked("dispatcher is being disabled");
5230 }
5231
5232 mDispatchEnabled = enabled;
5233 mDispatchFrozen = frozen;
5234 changed = true;
5235 } else {
5236 changed = false;
5237 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005238 } // release lock
5239
5240 if (changed) {
5241 // Wake up poll loop since it may need to make new input dispatching choices.
5242 mLooper->wake();
5243 }
5244}
5245
5246void InputDispatcher::setInputFilterEnabled(bool enabled) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005247 if (DEBUG_FOCUS) {
5248 ALOGD("setInputFilterEnabled: enabled=%d", enabled);
5249 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005250
5251 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005252 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005253
5254 if (mInputFilterEnabled == enabled) {
5255 return;
5256 }
5257
5258 mInputFilterEnabled = enabled;
5259 resetAndDropEverythingLocked("input filter is being enabled or disabled");
5260 } // release lock
5261
5262 // Wake up poll loop since there might be work to do to drop everything.
5263 mLooper->wake();
5264}
5265
Antonio Kanteka042c022022-07-06 16:51:07 -07005266bool InputDispatcher::setInTouchMode(bool inTouchMode, int32_t pid, int32_t uid, bool hasPermission,
5267 int32_t displayId) {
Antonio Kantekf16f2832021-09-28 04:39:20 +00005268 bool needWake = false;
5269 {
5270 std::scoped_lock lock(mLock);
Antonio Kantek15beb512022-06-13 22:35:41 +00005271 ALOGD_IF(DEBUG_TOUCH_MODE,
5272 "Request to change touch mode to %s (calling pid=%d, uid=%d, "
5273 "hasPermission=%s, target displayId=%d, mTouchModePerDisplay[displayId]=%s)",
5274 toString(inTouchMode), pid, uid, toString(hasPermission), displayId,
5275 mTouchModePerDisplay.count(displayId) == 0
5276 ? "not set"
5277 : std::to_string(mTouchModePerDisplay[displayId]).c_str());
5278
Antonio Kantek15beb512022-06-13 22:35:41 +00005279 auto touchModeIt = mTouchModePerDisplay.find(displayId);
5280 if (touchModeIt != mTouchModePerDisplay.end() && touchModeIt->second == inTouchMode) {
Antonio Kantekea47acb2021-12-23 12:41:25 -08005281 return false;
Antonio Kantekf16f2832021-09-28 04:39:20 +00005282 }
Antonio Kantekea47acb2021-12-23 12:41:25 -08005283 if (!hasPermission) {
Antonio Kantek48710e42022-03-24 14:19:30 -07005284 if (!focusedWindowIsOwnedByLocked(pid, uid) &&
5285 !recentWindowsAreOwnedByLocked(pid, uid)) {
5286 ALOGD("Touch mode switch rejected, caller (pid=%d, uid=%d) doesn't own the focused "
5287 "window nor none of the previously interacted window",
5288 pid, uid);
Antonio Kantekea47acb2021-12-23 12:41:25 -08005289 return false;
5290 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00005291 }
Antonio Kantek15beb512022-06-13 22:35:41 +00005292 mTouchModePerDisplay[displayId] = inTouchMode;
5293 auto entry = std::make_unique<TouchModeEntry>(mIdGenerator.nextId(), now(), inTouchMode,
5294 displayId);
Antonio Kantekf16f2832021-09-28 04:39:20 +00005295 needWake = enqueueInboundEventLocked(std::move(entry));
5296 } // release lock
5297
5298 if (needWake) {
5299 mLooper->wake();
5300 }
Antonio Kantekea47acb2021-12-23 12:41:25 -08005301 return true;
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -08005302}
5303
Antonio Kantek48710e42022-03-24 14:19:30 -07005304bool InputDispatcher::focusedWindowIsOwnedByLocked(int32_t pid, int32_t uid) {
5305 const sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
5306 if (focusedToken == nullptr) {
5307 return false;
5308 }
5309 sp<WindowInfoHandle> windowHandle = getWindowHandleLocked(focusedToken);
5310 return isWindowOwnedBy(windowHandle, pid, uid);
5311}
5312
5313bool InputDispatcher::recentWindowsAreOwnedByLocked(int32_t pid, int32_t uid) {
5314 return std::find_if(mInteractionConnectionTokens.begin(), mInteractionConnectionTokens.end(),
5315 [&](const sp<IBinder>& connectionToken) REQUIRES(mLock) {
5316 const sp<WindowInfoHandle> windowHandle =
5317 getWindowHandleLocked(connectionToken);
5318 return isWindowOwnedBy(windowHandle, pid, uid);
5319 }) != mInteractionConnectionTokens.end();
5320}
5321
Bernardo Rufinoea97d182020-08-19 14:43:14 +01005322void InputDispatcher::setMaximumObscuringOpacityForTouch(float opacity) {
5323 if (opacity < 0 || opacity > 1) {
5324 LOG_ALWAYS_FATAL("Maximum obscuring opacity for touch should be >= 0 and <= 1");
5325 return;
5326 }
5327
5328 std::scoped_lock lock(mLock);
5329 mMaximumObscuringOpacityForTouch = opacity;
5330}
5331
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005332std::tuple<TouchState*, TouchedWindow*, int32_t /*displayId*/>
5333InputDispatcher::findTouchStateWindowAndDisplayLocked(const sp<IBinder>& token) {
Arthur Hungabbb9d82021-09-01 14:52:30 +00005334 for (auto& [displayId, state] : mTouchStatesByDisplay) {
5335 for (TouchedWindow& w : state.windows) {
5336 if (w.windowHandle->getToken() == token) {
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005337 return std::make_tuple(&state, &w, displayId);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005338 }
5339 }
5340 }
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005341 return std::make_tuple(nullptr, nullptr, ADISPLAY_ID_DEFAULT);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005342}
5343
arthurhungb89ccb02020-12-30 16:19:01 +08005344bool InputDispatcher::transferTouchFocus(const sp<IBinder>& fromToken, const sp<IBinder>& toToken,
5345 bool isDragDrop) {
chaviwfbe5d9c2018-12-26 12:23:37 -08005346 if (fromToken == toToken) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005347 if (DEBUG_FOCUS) {
5348 ALOGD("Trivial transfer to same window.");
5349 }
chaviwfbe5d9c2018-12-26 12:23:37 -08005350 return true;
5351 }
5352
Michael Wrightd02c5b62014-02-10 15:10:22 -08005353 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005354 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005355
Arthur Hungabbb9d82021-09-01 14:52:30 +00005356 // Find the target touch state and touched window by fromToken.
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005357 auto [state, touchedWindow, displayId] = findTouchStateWindowAndDisplayLocked(fromToken);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005358 if (state == nullptr || touchedWindow == nullptr) {
5359 ALOGD("Focus transfer failed because from window is not being touched.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005360 return false;
5361 }
Arthur Hungabbb9d82021-09-01 14:52:30 +00005362
Arthur Hungabbb9d82021-09-01 14:52:30 +00005363 sp<WindowInfoHandle> toWindowHandle = getWindowHandleLocked(toToken, displayId);
5364 if (toWindowHandle == nullptr) {
5365 ALOGW("Cannot transfer focus because to window not found.");
5366 return false;
5367 }
5368
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005369 if (DEBUG_FOCUS) {
5370 ALOGD("transferTouchFocus: fromWindowHandle=%s, toWindowHandle=%s",
Arthur Hungabbb9d82021-09-01 14:52:30 +00005371 touchedWindow->windowHandle->getName().c_str(),
5372 toWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005373 }
5374
Arthur Hungabbb9d82021-09-01 14:52:30 +00005375 // Erase old window.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005376 ftl::Flags<InputTarget::Flags> oldTargetFlags = touchedWindow->targetFlags;
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08005377 std::bitset<MAX_POINTER_ID + 1> pointerIds = touchedWindow->pointerIds;
Arthur Hungc539dbb2022-12-08 07:45:36 +00005378 sp<WindowInfoHandle> fromWindowHandle = touchedWindow->windowHandle;
Arthur Hungabbb9d82021-09-01 14:52:30 +00005379 state->removeWindowByToken(fromToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005380
Arthur Hungabbb9d82021-09-01 14:52:30 +00005381 // Add new window.
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00005382 nsecs_t downTimeInTarget = now();
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005383 ftl::Flags<InputTarget::Flags> newTargetFlags =
5384 oldTargetFlags & (InputTarget::Flags::SPLIT | InputTarget::Flags::DISPATCH_AS_IS);
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00005385 if (canReceiveForegroundTouches(*toWindowHandle->getInfo())) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005386 newTargetFlags |= InputTarget::Flags::FOREGROUND;
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00005387 }
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00005388 state->addOrUpdateWindow(toWindowHandle, newTargetFlags, pointerIds, downTimeInTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005389
Arthur Hungabbb9d82021-09-01 14:52:30 +00005390 // Store the dragging window.
5391 if (isDragDrop) {
Arthur Hungb75c2aa2022-07-15 09:35:36 +00005392 if (pointerIds.count() != 1) {
5393 ALOGW("The drag and drop cannot be started when there is no pointer or more than 1"
5394 " pointer on the window.");
Arthur Hung54745652022-04-20 07:17:41 +00005395 return false;
5396 }
Arthur Hungb75c2aa2022-07-15 09:35:36 +00005397 // Track the pointer id for drag window and generate the drag state.
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08005398 const size_t id = firstMarkedBit(pointerIds);
Arthur Hung54745652022-04-20 07:17:41 +00005399 mDragState = std::make_unique<DragState>(toWindowHandle, id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005400 }
5401
Arthur Hungabbb9d82021-09-01 14:52:30 +00005402 // Synthesize cancel for old window and down for new window.
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07005403 std::shared_ptr<Connection> fromConnection = getConnectionLocked(fromToken);
5404 std::shared_ptr<Connection> toConnection = getConnectionLocked(toToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005405 if (fromConnection != nullptr && toConnection != nullptr) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08005406 fromConnection->inputState.mergePointerStateTo(toConnection->inputState);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005407 CancelationOptions
Michael Wrightfb04fd52022-11-24 22:31:11 +00005408 options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005409 "transferring touch focus from this window to another window");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005410 synthesizeCancelationEventsForConnectionLocked(fromConnection, options);
Arthur Hungc539dbb2022-12-08 07:45:36 +00005411 synthesizePointerDownEventsForConnectionLocked(downTimeInTarget, toConnection,
5412 newTargetFlags);
5413
5414 // Check if the wallpaper window should deliver the corresponding event.
5415 transferWallpaperTouch(oldTargetFlags, newTargetFlags, fromWindowHandle, toWindowHandle,
5416 *state, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005417 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005418 } // release lock
5419
5420 // Wake up poll loop since it may need to make new input dispatching choices.
5421 mLooper->wake();
5422 return true;
5423}
5424
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005425/**
5426 * Get the touched foreground window on the given display.
5427 * Return null if there are no windows touched on that display, or if more than one foreground
5428 * window is being touched.
5429 */
5430sp<WindowInfoHandle> InputDispatcher::findTouchedForegroundWindowLocked(int32_t displayId) const {
5431 auto stateIt = mTouchStatesByDisplay.find(displayId);
5432 if (stateIt == mTouchStatesByDisplay.end()) {
5433 ALOGI("No touch state on display %" PRId32, displayId);
5434 return nullptr;
5435 }
5436
5437 const TouchState& state = stateIt->second;
5438 sp<WindowInfoHandle> touchedForegroundWindow;
5439 // If multiple foreground windows are touched, return nullptr
5440 for (const TouchedWindow& window : state.windows) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005441 if (window.targetFlags.test(InputTarget::Flags::FOREGROUND)) {
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005442 if (touchedForegroundWindow != nullptr) {
5443 ALOGI("Two or more foreground windows: %s and %s",
5444 touchedForegroundWindow->getName().c_str(),
5445 window.windowHandle->getName().c_str());
5446 return nullptr;
5447 }
5448 touchedForegroundWindow = window.windowHandle;
5449 }
5450 }
5451 return touchedForegroundWindow;
5452}
5453
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005454// Binder call
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005455bool InputDispatcher::transferTouch(const sp<IBinder>& destChannelToken, int32_t displayId) {
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005456 sp<IBinder> fromToken;
5457 { // acquire lock
5458 std::scoped_lock _l(mLock);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005459 sp<WindowInfoHandle> toWindowHandle = getWindowHandleLocked(destChannelToken, displayId);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005460 if (toWindowHandle == nullptr) {
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005461 ALOGW("Could not find window associated with token=%p on display %" PRId32,
5462 destChannelToken.get(), displayId);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005463 return false;
5464 }
5465
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005466 sp<WindowInfoHandle> from = findTouchedForegroundWindowLocked(displayId);
5467 if (from == nullptr) {
5468 ALOGE("Could not find a source window in %s for %p", __func__, destChannelToken.get());
5469 return false;
5470 }
5471
5472 fromToken = from->getToken();
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005473 } // release lock
5474
5475 return transferTouchFocus(fromToken, destChannelToken);
5476}
5477
Michael Wrightd02c5b62014-02-10 15:10:22 -08005478void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005479 if (DEBUG_FOCUS) {
5480 ALOGD("Resetting and dropping all events (%s).", reason);
5481 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005482
Michael Wrightfb04fd52022-11-24 22:31:11 +00005483 CancelationOptions options(CancelationOptions::Mode::CANCEL_ALL_EVENTS, reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005484 synthesizeCancelationEventsForAllConnectionsLocked(options);
5485
5486 resetKeyRepeatLocked();
5487 releasePendingEventLocked();
5488 drainInboundQueueLocked();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005489 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005490
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005491 mAnrTracker.clear();
Jeff Brownf086ddb2014-02-11 14:28:48 -08005492 mTouchStatesByDisplay.clear();
Michael Wright78f24442014-08-06 15:55:28 -07005493 mReplacedKeys.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005494}
5495
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005496void InputDispatcher::logDispatchStateLocked() const {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005497 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005498 dumpDispatchStateLocked(dump);
5499
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005500 std::istringstream stream(dump);
5501 std::string line;
5502
5503 while (std::getline(stream, line, '\n')) {
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07005504 ALOGI("%s", line.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005505 }
5506}
5507
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005508std::string InputDispatcher::dumpPointerCaptureStateLocked() const {
Prabir Pradhan99987712020-11-10 18:43:05 -08005509 std::string dump;
5510
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005511 dump += StringPrintf(INDENT "Pointer Capture Requested: %s\n",
5512 toString(mCurrentPointerCaptureRequest.enable));
Prabir Pradhan99987712020-11-10 18:43:05 -08005513
5514 std::string windowName = "None";
5515 if (mWindowTokenWithPointerCapture) {
chaviw98318de2021-05-19 16:45:23 -05005516 const sp<WindowInfoHandle> captureWindowHandle =
Prabir Pradhan99987712020-11-10 18:43:05 -08005517 getWindowHandleLocked(mWindowTokenWithPointerCapture);
5518 windowName = captureWindowHandle ? captureWindowHandle->getName().c_str()
5519 : "token has capture without window";
5520 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005521 dump += StringPrintf(INDENT "Current Window with Pointer Capture: %s\n", windowName.c_str());
Prabir Pradhan99987712020-11-10 18:43:05 -08005522
5523 return dump;
5524}
5525
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005526void InputDispatcher::dumpDispatchStateLocked(std::string& dump) const {
Siarhei Vishniakou043a3ec2019-05-01 11:30:46 -07005527 dump += StringPrintf(INDENT "DispatchEnabled: %s\n", toString(mDispatchEnabled));
5528 dump += StringPrintf(INDENT "DispatchFrozen: %s\n", toString(mDispatchFrozen));
5529 dump += StringPrintf(INDENT "InputFilterEnabled: %s\n", toString(mInputFilterEnabled));
Tiger Huang721e26f2018-07-24 22:26:19 +08005530 dump += StringPrintf(INDENT "FocusedDisplayId: %" PRId32 "\n", mFocusedDisplayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005531
Tiger Huang721e26f2018-07-24 22:26:19 +08005532 if (!mFocusedApplicationHandlesByDisplay.empty()) {
5533 dump += StringPrintf(INDENT "FocusedApplications:\n");
5534 for (auto& it : mFocusedApplicationHandlesByDisplay) {
5535 const int32_t displayId = it.first;
Chris Yea209fde2020-07-22 13:54:51 -07005536 const std::shared_ptr<InputApplicationHandle>& applicationHandle = it.second;
Siarhei Vishniakou70622952020-07-30 11:17:23 -05005537 const std::chrono::duration timeout =
5538 applicationHandle->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005539 dump += StringPrintf(INDENT2 "displayId=%" PRId32
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005540 ", name='%s', dispatchingTimeout=%" PRId64 "ms\n",
Siarhei Vishniakou70622952020-07-30 11:17:23 -05005541 displayId, applicationHandle->getName().c_str(), millis(timeout));
Tiger Huang721e26f2018-07-24 22:26:19 +08005542 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005543 } else {
Tiger Huang721e26f2018-07-24 22:26:19 +08005544 dump += StringPrintf(INDENT "FocusedApplications: <none>\n");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005545 }
Tiger Huang721e26f2018-07-24 22:26:19 +08005546
Vishnu Nairc519ff72021-01-21 08:23:08 -08005547 dump += mFocusResolver.dump();
Prabir Pradhan99987712020-11-10 18:43:05 -08005548 dump += dumpPointerCaptureStateLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005549
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005550 if (!mTouchStatesByDisplay.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005551 dump += StringPrintf(INDENT "TouchStatesByDisplay:\n");
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005552 for (const auto& [displayId, state] : mTouchStatesByDisplay) {
Siarhei Vishniakou6e1e9872022-11-08 17:51:35 -08005553 std::string touchStateDump = addLinePrefix(state.dump(), INDENT2);
5554 dump += INDENT2 + std::to_string(displayId) + " : " + touchStateDump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005555 }
5556 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005557 dump += INDENT "TouchStates: <no displays touched>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005558 }
5559
arthurhung6d4bed92021-03-17 11:59:33 +08005560 if (mDragState) {
5561 dump += StringPrintf(INDENT "DragState:\n");
5562 mDragState->dump(dump, INDENT2);
5563 }
5564
Arthur Hungb92218b2018-08-14 12:00:21 +08005565 if (!mWindowHandlesByDisplay.empty()) {
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005566 for (const auto& [displayId, windowHandles] : mWindowHandlesByDisplay) {
5567 dump += StringPrintf(INDENT "Display: %" PRId32 "\n", displayId);
5568 if (const auto& it = mDisplayInfos.find(displayId); it != mDisplayInfos.end()) {
5569 const auto& displayInfo = it->second;
5570 dump += StringPrintf(INDENT2 "logicalSize=%dx%d\n", displayInfo.logicalWidth,
5571 displayInfo.logicalHeight);
5572 displayInfo.transform.dump(dump, "transform", INDENT4);
5573 } else {
5574 dump += INDENT2 "No DisplayInfo found!\n";
5575 }
5576
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08005577 if (!windowHandles.empty()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08005578 dump += INDENT2 "Windows:\n";
5579 for (size_t i = 0; i < windowHandles.size(); i++) {
chaviw98318de2021-05-19 16:45:23 -05005580 const sp<WindowInfoHandle>& windowHandle = windowHandles[i];
5581 const WindowInfo* windowInfo = windowHandle->getInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005582
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00005583 dump += StringPrintf(INDENT3 "%zu: name='%s', id=%" PRId32 ", displayId=%d, "
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005584 "inputConfig=%s, alpha=%.2f, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005585 "frame=[%d,%d][%d,%d], globalScale=%f, "
Bernardo Rufino49d99e42021-01-18 15:16:59 +00005586 "applicationInfo.name=%s, "
5587 "applicationInfo.token=%s, "
chaviw1ff3d1e2020-07-01 15:53:47 -07005588 "touchableRegion=",
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00005589 i, windowInfo->name.c_str(), windowInfo->id,
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005590 windowInfo->displayId,
5591 windowInfo->inputConfig.string().c_str(),
5592 windowInfo->alpha, windowInfo->frameLeft,
5593 windowInfo->frameTop, windowInfo->frameRight,
5594 windowInfo->frameBottom, windowInfo->globalScaleFactor,
Bernardo Rufino49d99e42021-01-18 15:16:59 +00005595 windowInfo->applicationInfo.name.c_str(),
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07005596 binderToString(windowInfo->applicationInfo.token).c_str());
Bernardo Rufino53fc31e2020-11-03 11:01:07 +00005597 dump += dumpRegion(windowInfo->touchableRegion);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005598 dump += StringPrintf(", ownerPid=%d, ownerUid=%d, dispatchingTimeout=%" PRId64
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005599 "ms, hasToken=%s, "
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005600 "touchOcclusionMode=%s\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005601 windowInfo->ownerPid, windowInfo->ownerUid,
Bernardo Rufinoc2f1fad2020-11-04 17:30:57 +00005602 millis(windowInfo->dispatchingTimeout),
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07005603 binderToString(windowInfo->token).c_str(),
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005604 toString(windowInfo->touchOcclusionMode).c_str());
chaviw85b44202020-07-24 11:46:21 -07005605 windowInfo->transform.dump(dump, "transform", INDENT4);
Arthur Hungb92218b2018-08-14 12:00:21 +08005606 }
5607 } else {
5608 dump += INDENT2 "Windows: <none>\n";
5609 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005610 }
5611 } else {
Arthur Hungb92218b2018-08-14 12:00:21 +08005612 dump += INDENT "Displays: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005613 }
5614
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005615 if (!mGlobalMonitorsByDisplay.empty()) {
5616 for (const auto& [displayId, monitors] : mGlobalMonitorsByDisplay) {
5617 dump += StringPrintf(INDENT "Global monitors on display %d:\n", displayId);
Michael Wright3dd60e22019-03-27 22:06:44 +00005618 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005619 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005620 } else {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005621 dump += INDENT "Global Monitors: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005622 }
5623
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005624 const nsecs_t currentTime = now();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005625
5626 // Dump recently dispatched or dropped events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005627 if (!mRecentQueue.empty()) {
5628 dump += StringPrintf(INDENT "RecentQueue: length=%zu\n", mRecentQueue.size());
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005629 for (const std::shared_ptr<EventEntry>& entry : mRecentQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005630 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005631 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005632 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005633 }
5634 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005635 dump += INDENT "RecentQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005636 }
5637
5638 // Dump event currently being dispatched.
5639 if (mPendingEvent) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005640 dump += INDENT "PendingEvent:\n";
5641 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005642 dump += mPendingEvent->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005643 dump += StringPrintf(", age=%" PRId64 "ms\n",
5644 ns2ms(currentTime - mPendingEvent->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005645 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005646 dump += INDENT "PendingEvent: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005647 }
5648
5649 // Dump inbound events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005650 if (!mInboundQueue.empty()) {
5651 dump += StringPrintf(INDENT "InboundQueue: length=%zu\n", mInboundQueue.size());
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005652 for (const std::shared_ptr<EventEntry>& entry : mInboundQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005653 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005654 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005655 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005656 }
5657 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005658 dump += INDENT "InboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005659 }
5660
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005661 if (!mReplacedKeys.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005662 dump += INDENT "ReplacedKeys:\n";
Michael Wright3cec4462022-11-24 22:05:46 +00005663 for (const auto& [replacement, newKeyCode] : mReplacedKeys) {
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005664 dump += StringPrintf(INDENT2 "originalKeyCode=%d, deviceId=%d -> newKeyCode=%d\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005665 replacement.keyCode, replacement.deviceId, newKeyCode);
Michael Wright78f24442014-08-06 15:55:28 -07005666 }
5667 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005668 dump += INDENT "ReplacedKeys: <empty>\n";
Michael Wright78f24442014-08-06 15:55:28 -07005669 }
5670
Prabir Pradhancef936d2021-07-21 16:17:52 +00005671 if (!mCommandQueue.empty()) {
5672 dump += StringPrintf(INDENT "CommandQueue: size=%zu\n", mCommandQueue.size());
5673 } else {
5674 dump += INDENT "CommandQueue: <empty>\n";
5675 }
5676
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005677 if (!mConnectionsByToken.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005678 dump += INDENT "Connections:\n";
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005679 for (const auto& [token, connection] : mConnectionsByToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005680 dump += StringPrintf(INDENT2 "%i: channelName='%s', windowName='%s', "
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005681 "status=%s, monitor=%s, responsive=%s\n",
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005682 connection->inputChannel->getFd().get(),
5683 connection->getInputChannelName().c_str(),
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08005684 connection->getWindowName().c_str(),
5685 ftl::enum_string(connection->status).c_str(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005686 toString(connection->monitor), toString(connection->responsive));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005687
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005688 if (!connection->outboundQueue.empty()) {
5689 dump += StringPrintf(INDENT3 "OutboundQueue: length=%zu\n",
5690 connection->outboundQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005691 dump += dumpQueue(connection->outboundQueue, currentTime);
5692
Michael Wrightd02c5b62014-02-10 15:10:22 -08005693 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005694 dump += INDENT3 "OutboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005695 }
5696
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005697 if (!connection->waitQueue.empty()) {
5698 dump += StringPrintf(INDENT3 "WaitQueue: length=%zu\n",
5699 connection->waitQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005700 dump += dumpQueue(connection->waitQueue, currentTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005701 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005702 dump += INDENT3 "WaitQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005703 }
5704 }
5705 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005706 dump += INDENT "Connections: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005707 }
5708
5709 if (isAppSwitchPendingLocked()) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005710 dump += StringPrintf(INDENT "AppSwitch: pending, due in %" PRId64 "ms\n",
5711 ns2ms(mAppSwitchDueTime - now()));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005712 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005713 dump += INDENT "AppSwitch: not pending\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005714 }
5715
Antonio Kantek15beb512022-06-13 22:35:41 +00005716 if (!mTouchModePerDisplay.empty()) {
5717 dump += INDENT "TouchModePerDisplay:\n";
5718 for (const auto& [displayId, touchMode] : mTouchModePerDisplay) {
5719 dump += StringPrintf(INDENT2 "Display: %" PRId32 " TouchMode: %s\n", displayId,
5720 std::to_string(touchMode).c_str());
5721 }
5722 } else {
5723 dump += INDENT "TouchModePerDisplay: <none>\n";
5724 }
5725
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005726 dump += INDENT "Configuration:\n";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005727 dump += StringPrintf(INDENT2 "KeyRepeatDelay: %" PRId64 "ms\n", ns2ms(mConfig.keyRepeatDelay));
5728 dump += StringPrintf(INDENT2 "KeyRepeatTimeout: %" PRId64 "ms\n",
5729 ns2ms(mConfig.keyRepeatTimeout));
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00005730 dump += mLatencyTracker.dump(INDENT2);
Siarhei Vishniakoua04181f2021-03-26 05:56:49 +00005731 dump += mLatencyAggregator.dump(INDENT2);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005732}
5733
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005734void InputDispatcher::dumpMonitors(std::string& dump, const std::vector<Monitor>& monitors) const {
Michael Wright3dd60e22019-03-27 22:06:44 +00005735 const size_t numMonitors = monitors.size();
5736 for (size_t i = 0; i < numMonitors; i++) {
5737 const Monitor& monitor = monitors[i];
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005738 const std::shared_ptr<InputChannel>& channel = monitor.inputChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005739 dump += StringPrintf(INDENT2 "%zu: '%s', ", i, channel->getName().c_str());
5740 dump += "\n";
5741 }
5742}
5743
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005744class LooperEventCallback : public LooperCallback {
5745public:
5746 LooperEventCallback(std::function<int(int events)> callback) : mCallback(callback) {}
5747 int handleEvent(int /*fd*/, int events, void* /*data*/) override { return mCallback(events); }
5748
5749private:
5750 std::function<int(int events)> mCallback;
5751};
5752
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005753Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputChannel(const std::string& name) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00005754 if (DEBUG_CHANNEL_CREATION) {
5755 ALOGD("channel '%s' ~ createInputChannel", name.c_str());
5756 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005757
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005758 std::unique_ptr<InputChannel> serverChannel;
Garfield Tan15601662020-09-22 15:32:38 -07005759 std::unique_ptr<InputChannel> clientChannel;
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005760 status_t result = InputChannel::openInputChannelPair(name, serverChannel, clientChannel);
Garfield Tan15601662020-09-22 15:32:38 -07005761
5762 if (result) {
5763 return base::Error(result) << "Failed to open input channel pair with name " << name;
5764 }
5765
Michael Wrightd02c5b62014-02-10 15:10:22 -08005766 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005767 std::scoped_lock _l(mLock);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005768 const sp<IBinder>& token = serverChannel->getConnectionToken();
Garfield Tan15601662020-09-22 15:32:38 -07005769 int fd = serverChannel->getFd();
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07005770 std::shared_ptr<Connection> connection =
5771 std::make_shared<Connection>(std::move(serverChannel), /*monitor=*/false,
5772 mIdGenerator);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005773
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005774 if (mConnectionsByToken.find(token) != mConnectionsByToken.end()) {
5775 ALOGE("Created a new connection, but the token %p is already known", token.get());
5776 }
5777 mConnectionsByToken.emplace(token, connection);
5778
5779 std::function<int(int events)> callback = std::bind(&InputDispatcher::handleReceiveCallback,
5780 this, std::placeholders::_1, token);
5781
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005782 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, sp<LooperEventCallback>::make(callback),
5783 nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005784 } // release lock
5785
5786 // Wake the looper because some connections have changed.
5787 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07005788 return clientChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005789}
5790
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005791Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputMonitor(int32_t displayId,
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005792 const std::string& name,
5793 int32_t pid) {
Garfield Tan15601662020-09-22 15:32:38 -07005794 std::shared_ptr<InputChannel> serverChannel;
5795 std::unique_ptr<InputChannel> clientChannel;
5796 status_t result = openInputChannelPair(name, serverChannel, clientChannel);
5797 if (result) {
5798 return base::Error(result) << "Failed to open input channel pair with name " << name;
5799 }
5800
Michael Wright3dd60e22019-03-27 22:06:44 +00005801 { // acquire lock
5802 std::scoped_lock _l(mLock);
5803
5804 if (displayId < 0) {
Garfield Tan15601662020-09-22 15:32:38 -07005805 return base::Error(BAD_VALUE) << "Attempted to create input monitor with name " << name
5806 << " without a specified display.";
Michael Wright3dd60e22019-03-27 22:06:44 +00005807 }
5808
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07005809 std::shared_ptr<Connection> connection =
5810 std::make_shared<Connection>(serverChannel, /*monitor=*/true, mIdGenerator);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005811 const sp<IBinder>& token = serverChannel->getConnectionToken();
Garfield Tan15601662020-09-22 15:32:38 -07005812 const int fd = serverChannel->getFd();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005813
5814 if (mConnectionsByToken.find(token) != mConnectionsByToken.end()) {
5815 ALOGE("Created a new connection, but the token %p is already known", token.get());
5816 }
5817 mConnectionsByToken.emplace(token, connection);
5818 std::function<int(int events)> callback = std::bind(&InputDispatcher::handleReceiveCallback,
5819 this, std::placeholders::_1, token);
Michael Wright3dd60e22019-03-27 22:06:44 +00005820
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005821 mGlobalMonitorsByDisplay[displayId].emplace_back(serverChannel, pid);
Michael Wright3dd60e22019-03-27 22:06:44 +00005822
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005823 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, sp<LooperEventCallback>::make(callback),
5824 nullptr);
Michael Wright3dd60e22019-03-27 22:06:44 +00005825 }
Garfield Tan15601662020-09-22 15:32:38 -07005826
Michael Wright3dd60e22019-03-27 22:06:44 +00005827 // Wake the looper because some connections have changed.
5828 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07005829 return clientChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005830}
5831
Garfield Tan15601662020-09-22 15:32:38 -07005832status_t InputDispatcher::removeInputChannel(const sp<IBinder>& connectionToken) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005833 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005834 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005835
Harry Cutts33476232023-01-30 19:57:29 +00005836 status_t status = removeInputChannelLocked(connectionToken, /*notify=*/false);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005837 if (status) {
5838 return status;
5839 }
5840 } // release lock
5841
5842 // Wake the poll loop because removing the connection may have changed the current
5843 // synchronization state.
5844 mLooper->wake();
5845 return OK;
5846}
5847
Garfield Tan15601662020-09-22 15:32:38 -07005848status_t InputDispatcher::removeInputChannelLocked(const sp<IBinder>& connectionToken,
5849 bool notify) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07005850 std::shared_ptr<Connection> connection = getConnectionLocked(connectionToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005851 if (connection == nullptr) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005852 // Connection can be removed via socket hang up or an explicit call to 'removeInputChannel'
Michael Wrightd02c5b62014-02-10 15:10:22 -08005853 return BAD_VALUE;
5854 }
5855
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005856 removeConnectionLocked(connection);
Robert Carr5c8a0262018-10-03 16:30:44 -07005857
Michael Wrightd02c5b62014-02-10 15:10:22 -08005858 if (connection->monitor) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005859 removeMonitorChannelLocked(connectionToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005860 }
5861
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005862 mLooper->removeFd(connection->inputChannel->getFd());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005863
5864 nsecs_t currentTime = now();
5865 abortBrokenDispatchCycleLocked(currentTime, connection, notify);
5866
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08005867 connection->status = Connection::Status::ZOMBIE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005868 return OK;
5869}
5870
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005871void InputDispatcher::removeMonitorChannelLocked(const sp<IBinder>& connectionToken) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005872 for (auto it = mGlobalMonitorsByDisplay.begin(); it != mGlobalMonitorsByDisplay.end();) {
5873 auto& [displayId, monitors] = *it;
5874 std::erase_if(monitors, [connectionToken](const Monitor& monitor) {
5875 return monitor.inputChannel->getConnectionToken() == connectionToken;
5876 });
Michael Wright3dd60e22019-03-27 22:06:44 +00005877
Michael Wright3dd60e22019-03-27 22:06:44 +00005878 if (monitors.empty()) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005879 it = mGlobalMonitorsByDisplay.erase(it);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005880 } else {
5881 ++it;
5882 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005883 }
5884}
5885
Michael Wright3dd60e22019-03-27 22:06:44 +00005886status_t InputDispatcher::pilferPointers(const sp<IBinder>& token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005887 std::scoped_lock _l(mLock);
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00005888 return pilferPointersLocked(token);
5889}
Michael Wright3dd60e22019-03-27 22:06:44 +00005890
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00005891status_t InputDispatcher::pilferPointersLocked(const sp<IBinder>& token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005892 const std::shared_ptr<InputChannel> requestingChannel = getInputChannelLocked(token);
5893 if (!requestingChannel) {
5894 ALOGW("Attempted to pilfer pointers from an un-registered channel or invalid token");
5895 return BAD_VALUE;
Michael Wright3dd60e22019-03-27 22:06:44 +00005896 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005897
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005898 auto [statePtr, windowPtr, displayId] = findTouchStateWindowAndDisplayLocked(token);
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08005899 if (statePtr == nullptr || windowPtr == nullptr || windowPtr->pointerIds.none()) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005900 ALOGW("Attempted to pilfer points from a channel without any on-going pointer streams."
5901 " Ignoring.");
5902 return BAD_VALUE;
5903 }
5904
5905 TouchState& state = *statePtr;
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00005906 TouchedWindow& window = *windowPtr;
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005907 // Send cancel events to all the input channels we're stealing from.
Michael Wrightfb04fd52022-11-24 22:31:11 +00005908 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005909 "input channel stole pointer stream");
5910 options.deviceId = state.deviceId;
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005911 options.displayId = displayId;
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07005912 options.pointerIds = window.pointerIds;
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005913 std::string canceledWindows;
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00005914 for (const TouchedWindow& w : state.windows) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005915 const std::shared_ptr<InputChannel> channel =
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00005916 getInputChannelLocked(w.windowHandle->getToken());
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005917 if (channel != nullptr && channel->getConnectionToken() != token) {
5918 synthesizeCancelationEventsForInputChannelLocked(channel, options);
5919 canceledWindows += canceledWindows.empty() ? "[" : ", ";
5920 canceledWindows += channel->getName();
5921 }
5922 }
5923 canceledWindows += canceledWindows.empty() ? "[]" : "]";
5924 ALOGI("Channel %s is stealing touch from %s", requestingChannel->getName().c_str(),
5925 canceledWindows.c_str());
5926
Prabir Pradhane680f9b2022-02-04 04:24:00 -08005927 // Prevent the gesture from being sent to any other windows.
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00005928 // This only blocks relevant pointers to be sent to other windows
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08005929 window.pilferedPointerIds |= window.pointerIds;
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00005930
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07005931 state.cancelPointersForWindowsExcept(window.pointerIds, token);
Michael Wright3dd60e22019-03-27 22:06:44 +00005932 return OK;
5933}
5934
Prabir Pradhan99987712020-11-10 18:43:05 -08005935void InputDispatcher::requestPointerCapture(const sp<IBinder>& windowToken, bool enabled) {
5936 { // acquire lock
5937 std::scoped_lock _l(mLock);
5938 if (DEBUG_FOCUS) {
chaviw98318de2021-05-19 16:45:23 -05005939 const sp<WindowInfoHandle> windowHandle = getWindowHandleLocked(windowToken);
Prabir Pradhan99987712020-11-10 18:43:05 -08005940 ALOGI("Request to %s Pointer Capture from: %s.", enabled ? "enable" : "disable",
5941 windowHandle != nullptr ? windowHandle->getName().c_str()
5942 : "token without window");
5943 }
5944
Vishnu Nairc519ff72021-01-21 08:23:08 -08005945 const sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Prabir Pradhan99987712020-11-10 18:43:05 -08005946 if (focusedToken != windowToken) {
5947 ALOGW("Ignoring request to %s Pointer Capture: window does not have focus.",
5948 enabled ? "enable" : "disable");
5949 return;
5950 }
5951
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005952 if (enabled == mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08005953 ALOGW("Ignoring request to %s Pointer Capture: "
5954 "window has %s requested pointer capture.",
5955 enabled ? "enable" : "disable", enabled ? "already" : "not");
5956 return;
5957 }
5958
Christine Franksb768bb42021-11-29 12:11:31 -08005959 if (enabled) {
5960 if (std::find(mIneligibleDisplaysForPointerCapture.begin(),
5961 mIneligibleDisplaysForPointerCapture.end(),
5962 mFocusedDisplayId) != mIneligibleDisplaysForPointerCapture.end()) {
5963 ALOGW("Ignoring request to enable Pointer Capture: display is not eligible");
5964 return;
5965 }
5966 }
5967
Prabir Pradhan99987712020-11-10 18:43:05 -08005968 setPointerCaptureLocked(enabled);
5969 } // release lock
5970
5971 // Wake the thread to process command entries.
5972 mLooper->wake();
5973}
5974
Christine Franksb768bb42021-11-29 12:11:31 -08005975void InputDispatcher::setDisplayEligibilityForPointerCapture(int32_t displayId, bool isEligible) {
5976 { // acquire lock
5977 std::scoped_lock _l(mLock);
5978 std::erase(mIneligibleDisplaysForPointerCapture, displayId);
5979 if (!isEligible) {
5980 mIneligibleDisplaysForPointerCapture.push_back(displayId);
5981 }
5982 } // release lock
5983}
5984
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005985std::optional<int32_t> InputDispatcher::findMonitorPidByTokenLocked(const sp<IBinder>& token) {
5986 for (const auto& [_, monitors] : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00005987 for (const Monitor& monitor : monitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005988 if (monitor.inputChannel->getConnectionToken() == token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005989 return monitor.pid;
Michael Wright3dd60e22019-03-27 22:06:44 +00005990 }
5991 }
5992 }
5993 return std::nullopt;
5994}
5995
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07005996std::shared_ptr<Connection> InputDispatcher::getConnectionLocked(
5997 const sp<IBinder>& inputConnectionToken) const {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07005998 if (inputConnectionToken == nullptr) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005999 return nullptr;
Arthur Hung3b413f22018-10-26 18:05:34 +08006000 }
6001
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00006002 for (const auto& [token, connection] : mConnectionsByToken) {
6003 if (token == inputConnectionToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07006004 return connection;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006005 }
6006 }
Robert Carr4e670e52018-08-15 13:26:12 -07006007
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07006008 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006009}
6010
Siarhei Vishniakouad991402020-10-28 11:40:09 -05006011std::string InputDispatcher::getConnectionNameLocked(const sp<IBinder>& connectionToken) const {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006012 std::shared_ptr<Connection> connection = getConnectionLocked(connectionToken);
Siarhei Vishniakouad991402020-10-28 11:40:09 -05006013 if (connection == nullptr) {
6014 return "<nullptr>";
6015 }
6016 return connection->getInputChannelName();
6017}
6018
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006019void InputDispatcher::removeConnectionLocked(const std::shared_ptr<Connection>& connection) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006020 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00006021 mConnectionsByToken.erase(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07006022}
6023
Prabir Pradhancef936d2021-07-21 16:17:52 +00006024void InputDispatcher::doDispatchCycleFinishedCommand(nsecs_t finishTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006025 const std::shared_ptr<Connection>& connection,
6026 uint32_t seq, bool handled,
6027 nsecs_t consumeTime) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006028 // Handle post-event policy actions.
6029 std::deque<DispatchEntry*>::iterator dispatchEntryIt = connection->findWaitQueueEntry(seq);
6030 if (dispatchEntryIt == connection->waitQueue.end()) {
6031 return;
6032 }
6033 DispatchEntry* dispatchEntry = *dispatchEntryIt;
6034 const nsecs_t eventDuration = finishTime - dispatchEntry->deliveryTime;
6035 if (eventDuration > SLOW_EVENT_PROCESSING_WARNING_TIMEOUT) {
6036 ALOGI("%s spent %" PRId64 "ms processing %s", connection->getWindowName().c_str(),
6037 ns2ms(eventDuration), dispatchEntry->eventEntry->getDescription().c_str());
6038 }
6039 if (shouldReportFinishedEvent(*dispatchEntry, *connection)) {
6040 mLatencyTracker.trackFinishedEvent(dispatchEntry->eventEntry->id,
6041 connection->inputChannel->getConnectionToken(),
6042 dispatchEntry->deliveryTime, consumeTime, finishTime);
6043 }
6044
6045 bool restartEvent;
6046 if (dispatchEntry->eventEntry->type == EventEntry::Type::KEY) {
6047 KeyEntry& keyEntry = static_cast<KeyEntry&>(*(dispatchEntry->eventEntry));
6048 restartEvent =
6049 afterKeyEventLockedInterruptable(connection, dispatchEntry, keyEntry, handled);
6050 } else if (dispatchEntry->eventEntry->type == EventEntry::Type::MOTION) {
6051 MotionEntry& motionEntry = static_cast<MotionEntry&>(*(dispatchEntry->eventEntry));
6052 restartEvent = afterMotionEventLockedInterruptable(connection, dispatchEntry, motionEntry,
6053 handled);
6054 } else {
6055 restartEvent = false;
6056 }
6057
6058 // Dequeue the event and start the next cycle.
6059 // Because the lock might have been released, it is possible that the
6060 // contents of the wait queue to have been drained, so we need to double-check
6061 // a few things.
6062 dispatchEntryIt = connection->findWaitQueueEntry(seq);
6063 if (dispatchEntryIt != connection->waitQueue.end()) {
6064 dispatchEntry = *dispatchEntryIt;
6065 connection->waitQueue.erase(dispatchEntryIt);
6066 const sp<IBinder>& connectionToken = connection->inputChannel->getConnectionToken();
6067 mAnrTracker.erase(dispatchEntry->timeoutTime, connectionToken);
6068 if (!connection->responsive) {
6069 connection->responsive = isConnectionResponsive(*connection);
6070 if (connection->responsive) {
6071 // The connection was unresponsive, and now it's responsive.
6072 processConnectionResponsiveLocked(*connection);
6073 }
6074 }
6075 traceWaitQueueLength(*connection);
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08006076 if (restartEvent && connection->status == Connection::Status::NORMAL) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006077 connection->outboundQueue.push_front(dispatchEntry);
6078 traceOutboundQueueLength(*connection);
6079 } else {
6080 releaseDispatchEntry(dispatchEntry);
6081 }
6082 }
6083
6084 // Start the next dispatch cycle for this connection.
6085 startDispatchCycleLocked(now(), connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006086}
6087
Prabir Pradhancef936d2021-07-21 16:17:52 +00006088void InputDispatcher::sendFocusChangedCommandLocked(const sp<IBinder>& oldToken,
6089 const sp<IBinder>& newToken) {
6090 auto command = [this, oldToken, newToken]() REQUIRES(mLock) {
6091 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00006092 mPolicy.notifyFocusChanged(oldToken, newToken);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006093 };
6094 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08006095}
6096
Prabir Pradhancef936d2021-07-21 16:17:52 +00006097void InputDispatcher::sendDropWindowCommandLocked(const sp<IBinder>& token, float x, float y) {
6098 auto command = [this, token, x, y]() REQUIRES(mLock) {
6099 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00006100 mPolicy.notifyDropWindow(token, x, y);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006101 };
6102 postCommandLocked(std::move(command));
Robert Carrf759f162018-11-13 12:57:11 -08006103}
6104
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006105void InputDispatcher::onAnrLocked(const std::shared_ptr<Connection>& connection) {
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006106 if (connection == nullptr) {
6107 LOG_ALWAYS_FATAL("Caller must check for nullness");
6108 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006109 // Since we are allowing the policy to extend the timeout, maybe the waitQueue
6110 // is already healthy again. Don't raise ANR in this situation
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006111 if (connection->waitQueue.empty()) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006112 ALOGI("Not raising ANR because the connection %s has recovered",
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006113 connection->inputChannel->getName().c_str());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006114 return;
6115 }
6116 /**
6117 * The "oldestEntry" is the entry that was first sent to the application. That entry, however,
6118 * may not be the one that caused the timeout to occur. One possibility is that window timeout
6119 * has changed. This could cause newer entries to time out before the already dispatched
6120 * entries. In that situation, the newest entries caused ANR. But in all likelihood, the app
6121 * processes the events linearly. So providing information about the oldest entry seems to be
6122 * most useful.
6123 */
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006124 DispatchEntry* oldestEntry = *connection->waitQueue.begin();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006125 const nsecs_t currentWait = now() - oldestEntry->deliveryTime;
6126 std::string reason =
6127 android::base::StringPrintf("%s is not responding. Waited %" PRId64 "ms for %s",
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006128 connection->inputChannel->getName().c_str(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006129 ns2ms(currentWait),
6130 oldestEntry->eventEntry->getDescription().c_str());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006131 sp<IBinder> connectionToken = connection->inputChannel->getConnectionToken();
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -06006132 updateLastAnrStateLocked(getWindowHandleLocked(connectionToken), reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006133
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006134 processConnectionUnresponsiveLocked(*connection, std::move(reason));
6135
6136 // Stop waking up for events on this connection, it is already unresponsive
6137 cancelEventsForAnrLocked(connection);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006138}
6139
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05006140void InputDispatcher::onAnrLocked(std::shared_ptr<InputApplicationHandle> application) {
6141 std::string reason =
6142 StringPrintf("%s does not have a focused window", application->getName().c_str());
6143 updateLastAnrStateLocked(*application, reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006144
Prabir Pradhancef936d2021-07-21 16:17:52 +00006145 auto command = [this, application = std::move(application)]() REQUIRES(mLock) {
6146 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00006147 mPolicy.notifyNoFocusedWindowAnr(application);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006148 };
6149 postCommandLocked(std::move(command));
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00006150}
6151
chaviw98318de2021-05-19 16:45:23 -05006152void InputDispatcher::updateLastAnrStateLocked(const sp<WindowInfoHandle>& window,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006153 const std::string& reason) {
6154 const std::string windowLabel = getApplicationWindowLabel(nullptr, window);
6155 updateLastAnrStateLocked(windowLabel, reason);
6156}
6157
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05006158void InputDispatcher::updateLastAnrStateLocked(const InputApplicationHandle& application,
6159 const std::string& reason) {
6160 const std::string windowLabel = getApplicationWindowLabel(&application, nullptr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006161 updateLastAnrStateLocked(windowLabel, reason);
6162}
6163
6164void InputDispatcher::updateLastAnrStateLocked(const std::string& windowLabel,
6165 const std::string& reason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006166 // Capture a record of the InputDispatcher state at the time of the ANR.
Yi Kong9b14ac62018-07-17 13:48:38 -07006167 time_t t = time(nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006168 struct tm tm;
6169 localtime_r(&t, &tm);
6170 char timestr[64];
6171 strftime(timestr, sizeof(timestr), "%F %T", &tm);
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006172 mLastAnrState.clear();
6173 mLastAnrState += INDENT "ANR:\n";
6174 mLastAnrState += StringPrintf(INDENT2 "Time: %s\n", timestr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006175 mLastAnrState += StringPrintf(INDENT2 "Reason: %s\n", reason.c_str());
6176 mLastAnrState += StringPrintf(INDENT2 "Window: %s\n", windowLabel.c_str());
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006177 dumpDispatchStateLocked(mLastAnrState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006178}
6179
Prabir Pradhancef936d2021-07-21 16:17:52 +00006180void InputDispatcher::doInterceptKeyBeforeDispatchingCommand(const sp<IBinder>& focusedWindowToken,
6181 KeyEntry& entry) {
6182 const KeyEvent event = createKeyEvent(entry);
6183 nsecs_t delay = 0;
6184 { // release lock
6185 scoped_unlock unlock(mLock);
6186 android::base::Timer t;
Prabir Pradhana41d2442023-04-20 21:30:40 +00006187 delay = mPolicy.interceptKeyBeforeDispatching(focusedWindowToken, event, entry.policyFlags);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006188 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
6189 ALOGW("Excessive delay in interceptKeyBeforeDispatching; took %s ms",
6190 std::to_string(t.duration().count()).c_str());
6191 }
6192 } // acquire lock
Michael Wrightd02c5b62014-02-10 15:10:22 -08006193
6194 if (delay < 0) {
Michael Wright5caf55a2022-11-24 22:31:42 +00006195 entry.interceptKeyResult = KeyEntry::InterceptKeyResult::SKIP;
Prabir Pradhancef936d2021-07-21 16:17:52 +00006196 } else if (delay == 0) {
Michael Wright5caf55a2022-11-24 22:31:42 +00006197 entry.interceptKeyResult = KeyEntry::InterceptKeyResult::CONTINUE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006198 } else {
Michael Wright5caf55a2022-11-24 22:31:42 +00006199 entry.interceptKeyResult = KeyEntry::InterceptKeyResult::TRY_AGAIN_LATER;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006200 entry.interceptKeyWakeupTime = now() + delay;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006201 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006202}
6203
Prabir Pradhancef936d2021-07-21 16:17:52 +00006204void InputDispatcher::sendWindowUnresponsiveCommandLocked(const sp<IBinder>& token,
Prabir Pradhanedd96402022-02-15 01:46:16 -08006205 std::optional<int32_t> pid,
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006206 std::string reason) {
Prabir Pradhanedd96402022-02-15 01:46:16 -08006207 auto command = [this, token, pid, reason = std::move(reason)]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006208 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00006209 mPolicy.notifyWindowUnresponsive(token, pid, reason);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006210 };
6211 postCommandLocked(std::move(command));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006212}
6213
Prabir Pradhanedd96402022-02-15 01:46:16 -08006214void InputDispatcher::sendWindowResponsiveCommandLocked(const sp<IBinder>& token,
6215 std::optional<int32_t> pid) {
6216 auto command = [this, token, pid]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006217 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00006218 mPolicy.notifyWindowResponsive(token, pid);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006219 };
6220 postCommandLocked(std::move(command));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006221}
6222
6223/**
6224 * Tell the policy that a connection has become unresponsive so that it can start ANR.
6225 * Check whether the connection of interest is a monitor or a window, and add the corresponding
6226 * command entry to the command queue.
6227 */
6228void InputDispatcher::processConnectionUnresponsiveLocked(const Connection& connection,
6229 std::string reason) {
6230 const sp<IBinder>& connectionToken = connection.inputChannel->getConnectionToken();
Prabir Pradhanedd96402022-02-15 01:46:16 -08006231 std::optional<int32_t> pid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006232 if (connection.monitor) {
6233 ALOGW("Monitor %s is unresponsive: %s", connection.inputChannel->getName().c_str(),
6234 reason.c_str());
Prabir Pradhanedd96402022-02-15 01:46:16 -08006235 pid = findMonitorPidByTokenLocked(connectionToken);
6236 } else {
6237 // The connection is a window
6238 ALOGW("Window %s is unresponsive: %s", connection.inputChannel->getName().c_str(),
6239 reason.c_str());
6240 const sp<WindowInfoHandle> handle = getWindowHandleLocked(connectionToken);
6241 if (handle != nullptr) {
6242 pid = handle->getInfo()->ownerPid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006243 }
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006244 }
Prabir Pradhanedd96402022-02-15 01:46:16 -08006245 sendWindowUnresponsiveCommandLocked(connectionToken, pid, std::move(reason));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006246}
6247
6248/**
6249 * Tell the policy that a connection has become responsive so that it can stop ANR.
6250 */
6251void InputDispatcher::processConnectionResponsiveLocked(const Connection& connection) {
6252 const sp<IBinder>& connectionToken = connection.inputChannel->getConnectionToken();
Prabir Pradhanedd96402022-02-15 01:46:16 -08006253 std::optional<int32_t> pid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006254 if (connection.monitor) {
Prabir Pradhanedd96402022-02-15 01:46:16 -08006255 pid = findMonitorPidByTokenLocked(connectionToken);
6256 } else {
6257 // The connection is a window
6258 const sp<WindowInfoHandle> handle = getWindowHandleLocked(connectionToken);
6259 if (handle != nullptr) {
6260 pid = handle->getInfo()->ownerPid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006261 }
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006262 }
Prabir Pradhanedd96402022-02-15 01:46:16 -08006263 sendWindowResponsiveCommandLocked(connectionToken, pid);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006264}
6265
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006266bool InputDispatcher::afterKeyEventLockedInterruptable(
6267 const std::shared_ptr<Connection>& connection, DispatchEntry* dispatchEntry,
6268 KeyEntry& keyEntry, bool handled) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006269 if (keyEntry.flags & AKEY_EVENT_FLAG_FALLBACK) {
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006270 if (!handled) {
6271 // Report the key as unhandled, since the fallback was not handled.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006272 mReporter->reportUnhandledKey(keyEntry.id);
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006273 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006274 return false;
6275 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006276
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006277 // Get the fallback key state.
6278 // Clear it out after dispatching the UP.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006279 int32_t originalKeyCode = keyEntry.keyCode;
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006280 std::optional<int32_t> fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006281 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006282 connection->inputState.removeFallbackKey(originalKeyCode);
6283 }
6284
6285 if (handled || !dispatchEntry->hasForegroundTarget()) {
6286 // If the application handles the original key for which we previously
6287 // generated a fallback or if the window is not a foreground window,
6288 // then cancel the associated fallback key, if any.
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006289 if (fallbackKeyCode) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006290 // Dispatch the unhandled key to the policy with the cancel flag.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006291 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6292 ALOGD("Unhandled key event: Asking policy to cancel fallback action. "
6293 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6294 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount,
6295 keyEntry.policyFlags);
6296 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006297 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006298 event.setFlags(event.getFlags() | AKEY_EVENT_FLAG_CANCELED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006299
6300 mLock.unlock();
6301
Prabir Pradhana41d2442023-04-20 21:30:40 +00006302 if (const auto unhandledKeyFallback =
6303 mPolicy.dispatchUnhandledKey(connection->inputChannel->getConnectionToken(),
6304 event, keyEntry.policyFlags);
6305 unhandledKeyFallback) {
6306 event = *unhandledKeyFallback;
6307 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006308
6309 mLock.lock();
6310
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006311 // Cancel the fallback key.
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006312 if (*fallbackKeyCode != AKEYCODE_UNKNOWN) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00006313 CancelationOptions options(CancelationOptions::Mode::CANCEL_FALLBACK_EVENTS,
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006314 "application handled the original non-fallback key "
6315 "or is no longer a foreground target, "
6316 "canceling previously dispatched fallback key");
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006317 options.keyCode = *fallbackKeyCode;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006318 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006319 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006320 connection->inputState.removeFallbackKey(originalKeyCode);
6321 }
6322 } else {
6323 // If the application did not handle a non-fallback key, first check
6324 // that we are in a good state to perform unhandled key event processing
6325 // Then ask the policy what to do with it.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006326 bool initialDown = keyEntry.action == AKEY_EVENT_ACTION_DOWN && keyEntry.repeatCount == 0;
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006327 if (!fallbackKeyCode && !initialDown) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006328 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6329 ALOGD("Unhandled key event: Skipping unhandled key event processing "
6330 "since this is not an initial down. "
6331 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6332 originalKeyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
6333 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006334 return false;
6335 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006336
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006337 // Dispatch the unhandled key to the policy.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006338 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6339 ALOGD("Unhandled key event: Asking policy to perform fallback action. "
6340 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6341 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
6342 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006343 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006344
6345 mLock.unlock();
6346
Prabir Pradhana41d2442023-04-20 21:30:40 +00006347 bool fallback = false;
6348 if (auto fb = mPolicy.dispatchUnhandledKey(connection->inputChannel->getConnectionToken(),
6349 event, keyEntry.policyFlags);
6350 fb) {
6351 fallback = true;
6352 event = *fb;
6353 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006354
6355 mLock.lock();
6356
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08006357 if (connection->status != Connection::Status::NORMAL) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006358 connection->inputState.removeFallbackKey(originalKeyCode);
6359 return false;
6360 }
6361
6362 // Latch the fallback keycode for this key on an initial down.
6363 // The fallback keycode cannot change at any other point in the lifecycle.
6364 if (initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006365 if (fallback) {
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006366 *fallbackKeyCode = event.getKeyCode();
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006367 } else {
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006368 *fallbackKeyCode = AKEYCODE_UNKNOWN;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006369 }
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006370 connection->inputState.setFallbackKey(originalKeyCode, *fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006371 }
6372
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006373 ALOG_ASSERT(fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006374
6375 // Cancel the fallback key if the policy decides not to send it anymore.
6376 // We will continue to dispatch the key to the policy but we will no
6377 // longer dispatch a fallback key to the application.
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006378 if (*fallbackKeyCode != AKEYCODE_UNKNOWN &&
6379 (!fallback || *fallbackKeyCode != event.getKeyCode())) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006380 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6381 if (fallback) {
6382 ALOGD("Unhandled key event: Policy requested to send key %d"
6383 "as a fallback for %d, but on the DOWN it had requested "
6384 "to send %d instead. Fallback canceled.",
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006385 event.getKeyCode(), originalKeyCode, *fallbackKeyCode);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006386 } else {
6387 ALOGD("Unhandled key event: Policy did not request fallback for %d, "
6388 "but on the DOWN it had requested to send %d. "
6389 "Fallback canceled.",
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006390 originalKeyCode, *fallbackKeyCode);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006391 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006392 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006393
Michael Wrightfb04fd52022-11-24 22:31:11 +00006394 CancelationOptions options(CancelationOptions::Mode::CANCEL_FALLBACK_EVENTS,
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006395 "canceling fallback, policy no longer desires it");
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006396 options.keyCode = *fallbackKeyCode;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006397 synthesizeCancelationEventsForConnectionLocked(connection, options);
6398
6399 fallback = false;
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006400 *fallbackKeyCode = AKEYCODE_UNKNOWN;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006401 if (keyEntry.action != AKEY_EVENT_ACTION_UP) {
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006402 connection->inputState.setFallbackKey(originalKeyCode, *fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006403 }
6404 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006405
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006406 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6407 {
6408 std::string msg;
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006409 const std::map<int32_t, int32_t>& fallbackKeys =
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006410 connection->inputState.getFallbackKeys();
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006411 for (const auto& [key, value] : fallbackKeys) {
6412 msg += StringPrintf(", %d->%d", key, value);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006413 }
6414 ALOGD("Unhandled key event: %zu currently tracked fallback keys%s.",
6415 fallbackKeys.size(), msg.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006416 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006417 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006418
6419 if (fallback) {
6420 // Restart the dispatch cycle using the fallback key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006421 keyEntry.eventTime = event.getEventTime();
6422 keyEntry.deviceId = event.getDeviceId();
6423 keyEntry.source = event.getSource();
6424 keyEntry.displayId = event.getDisplayId();
6425 keyEntry.flags = event.getFlags() | AKEY_EVENT_FLAG_FALLBACK;
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006426 keyEntry.keyCode = *fallbackKeyCode;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006427 keyEntry.scanCode = event.getScanCode();
6428 keyEntry.metaState = event.getMetaState();
6429 keyEntry.repeatCount = event.getRepeatCount();
6430 keyEntry.downTime = event.getDownTime();
6431 keyEntry.syntheticRepeat = false;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006432
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006433 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6434 ALOGD("Unhandled key event: Dispatching fallback key. "
6435 "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006436 originalKeyCode, *fallbackKeyCode, keyEntry.metaState);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006437 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006438 return true; // restart the event
6439 } else {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006440 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6441 ALOGD("Unhandled key event: No fallback key.");
6442 }
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006443
6444 // Report the key as unhandled, since there is no fallback key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006445 mReporter->reportUnhandledKey(keyEntry.id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006446 }
6447 }
6448 return false;
6449}
6450
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006451bool InputDispatcher::afterMotionEventLockedInterruptable(
6452 const std::shared_ptr<Connection>& connection, DispatchEntry* dispatchEntry,
6453 MotionEntry& motionEntry, bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006454 return false;
6455}
6456
Michael Wrightd02c5b62014-02-10 15:10:22 -08006457void InputDispatcher::traceInboundQueueLengthLocked() {
6458 if (ATRACE_ENABLED()) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07006459 ATRACE_INT("iq", mInboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006460 }
6461}
6462
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006463void InputDispatcher::traceOutboundQueueLength(const Connection& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006464 if (ATRACE_ENABLED()) {
6465 char counterName[40];
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006466 snprintf(counterName, sizeof(counterName), "oq:%s", connection.getWindowName().c_str());
6467 ATRACE_INT(counterName, connection.outboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006468 }
6469}
6470
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006471void InputDispatcher::traceWaitQueueLength(const Connection& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006472 if (ATRACE_ENABLED()) {
6473 char counterName[40];
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006474 snprintf(counterName, sizeof(counterName), "wq:%s", connection.getWindowName().c_str());
6475 ATRACE_INT(counterName, connection.waitQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006476 }
6477}
6478
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006479void InputDispatcher::dump(std::string& dump) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006480 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006481
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006482 dump += "Input Dispatcher State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08006483 dumpDispatchStateLocked(dump);
6484
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006485 if (!mLastAnrState.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006486 dump += "\nInput Dispatcher State at time of last ANR:\n";
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006487 dump += mLastAnrState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006488 }
6489}
6490
6491void InputDispatcher::monitor() {
6492 // Acquire and release the lock to ensure that the dispatcher has not deadlocked.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006493 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006494 mLooper->wake();
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006495 mDispatcherIsAlive.wait(_l);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006496}
6497
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08006498/**
6499 * Wake up the dispatcher and wait until it processes all events and commands.
6500 * The notification of mDispatcherEnteredIdle is guaranteed to happen after wake(), so
6501 * this method can be safely called from any thread, as long as you've ensured that
6502 * the work you are interested in completing has already been queued.
6503 */
6504bool InputDispatcher::waitForIdle() {
6505 /**
6506 * Timeout should represent the longest possible time that a device might spend processing
6507 * events and commands.
6508 */
6509 constexpr std::chrono::duration TIMEOUT = 100ms;
6510 std::unique_lock lock(mLock);
6511 mLooper->wake();
6512 std::cv_status result = mDispatcherEnteredIdle.wait_for(lock, TIMEOUT);
6513 return result == std::cv_status::no_timeout;
6514}
6515
Vishnu Naire798b472020-07-23 13:52:21 -07006516/**
6517 * Sets focus to the window identified by the token. This must be called
6518 * after updating any input window handles.
6519 *
6520 * Params:
6521 * request.token - input channel token used to identify the window that should gain focus.
6522 * request.focusedToken - the token that the caller expects currently to be focused. If the
6523 * specified token does not match the currently focused window, this request will be dropped.
6524 * If the specified focused token matches the currently focused window, the call will succeed.
6525 * Set this to "null" if this call should succeed no matter what the currently focused token is.
6526 * request.timestamp - SYSTEM_TIME_MONOTONIC timestamp in nanos set by the client (wm)
6527 * when requesting the focus change. This determines which request gets
6528 * precedence if there is a focus change request from another source such as pointer down.
6529 */
Vishnu Nair958da932020-08-21 17:12:37 -07006530void InputDispatcher::setFocusedWindow(const FocusRequest& request) {
6531 { // acquire lock
6532 std::scoped_lock _l(mLock);
Vishnu Nairc519ff72021-01-21 08:23:08 -08006533 std::optional<FocusResolver::FocusChanges> changes =
6534 mFocusResolver.setFocusedWindow(request, getWindowHandlesLocked(request.displayId));
6535 if (changes) {
6536 onFocusChangedLocked(*changes);
Vishnu Nair958da932020-08-21 17:12:37 -07006537 }
6538 } // release lock
6539 // Wake up poll loop since it may need to make new input dispatching choices.
6540 mLooper->wake();
6541}
6542
Vishnu Nairc519ff72021-01-21 08:23:08 -08006543void InputDispatcher::onFocusChangedLocked(const FocusResolver::FocusChanges& changes) {
6544 if (changes.oldFocus) {
6545 std::shared_ptr<InputChannel> focusedInputChannel = getInputChannelLocked(changes.oldFocus);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006546 if (focusedInputChannel) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00006547 CancelationOptions options(CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS,
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006548 "focus left window");
6549 synthesizeCancelationEventsForInputChannelLocked(focusedInputChannel, options);
Harry Cutts33476232023-01-30 19:57:29 +00006550 enqueueFocusEventLocked(changes.oldFocus, /*hasFocus=*/false, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006551 }
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006552 }
Vishnu Nairc519ff72021-01-21 08:23:08 -08006553 if (changes.newFocus) {
Harry Cutts33476232023-01-30 19:57:29 +00006554 enqueueFocusEventLocked(changes.newFocus, /*hasFocus=*/true, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006555 }
6556
Prabir Pradhan99987712020-11-10 18:43:05 -08006557 // If a window has pointer capture, then it must have focus. We need to ensure that this
6558 // contract is upheld when pointer capture is being disabled due to a loss of window focus.
6559 // If the window loses focus before it loses pointer capture, then the window can be in a state
6560 // where it has pointer capture but not focus, violating the contract. Therefore we must
6561 // dispatch the pointer capture event before the focus event. Since focus events are added to
6562 // the front of the queue (above), we add the pointer capture event to the front of the queue
6563 // after the focus events are added. This ensures the pointer capture event ends up at the
6564 // front.
6565 disablePointerCaptureForcedLocked();
6566
Vishnu Nairc519ff72021-01-21 08:23:08 -08006567 if (mFocusedDisplayId == changes.displayId) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006568 sendFocusChangedCommandLocked(changes.oldFocus, changes.newFocus);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006569 }
6570}
Vishnu Nair958da932020-08-21 17:12:37 -07006571
Prabir Pradhan99987712020-11-10 18:43:05 -08006572void InputDispatcher::disablePointerCaptureForcedLocked() {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006573 if (!mCurrentPointerCaptureRequest.enable && !mWindowTokenWithPointerCapture) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006574 return;
6575 }
6576
6577 ALOGD_IF(DEBUG_FOCUS, "Disabling Pointer Capture because the window lost focus.");
6578
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006579 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006580 setPointerCaptureLocked(false);
6581 }
6582
6583 if (!mWindowTokenWithPointerCapture) {
6584 // No need to send capture changes because no window has capture.
6585 return;
6586 }
6587
6588 if (mPendingEvent != nullptr) {
6589 // Move the pending event to the front of the queue. This will give the chance
6590 // for the pending event to be dropped if it is a captured event.
6591 mInboundQueue.push_front(mPendingEvent);
6592 mPendingEvent = nullptr;
6593 }
6594
6595 auto entry = std::make_unique<PointerCaptureChangedEntry>(mIdGenerator.nextId(), now(),
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006596 mCurrentPointerCaptureRequest);
Prabir Pradhan99987712020-11-10 18:43:05 -08006597 mInboundQueue.push_front(std::move(entry));
6598}
6599
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006600void InputDispatcher::setPointerCaptureLocked(bool enable) {
6601 mCurrentPointerCaptureRequest.enable = enable;
6602 mCurrentPointerCaptureRequest.seq++;
6603 auto command = [this, request = mCurrentPointerCaptureRequest]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006604 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00006605 mPolicy.setPointerCapture(request);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006606 };
6607 postCommandLocked(std::move(command));
Prabir Pradhan99987712020-11-10 18:43:05 -08006608}
6609
Vishnu Nair599f1412021-06-21 10:39:58 -07006610void InputDispatcher::displayRemoved(int32_t displayId) {
6611 { // acquire lock
6612 std::scoped_lock _l(mLock);
6613 // Set an empty list to remove all handles from the specific display.
6614 setInputWindowsLocked(/* window handles */ {}, displayId);
6615 setFocusedApplicationLocked(displayId, nullptr);
6616 // Call focus resolver to clean up stale requests. This must be called after input windows
6617 // have been removed for the removed display.
6618 mFocusResolver.displayRemoved(displayId);
Christine Franksb768bb42021-11-29 12:11:31 -08006619 // Reset pointer capture eligibility, regardless of previous state.
6620 std::erase(mIneligibleDisplaysForPointerCapture, displayId);
Antonio Kantek15beb512022-06-13 22:35:41 +00006621 // Remove the associated touch mode state.
6622 mTouchModePerDisplay.erase(displayId);
Vishnu Nair599f1412021-06-21 10:39:58 -07006623 } // release lock
6624
6625 // Wake up poll loop since it may need to make new input dispatching choices.
6626 mLooper->wake();
6627}
6628
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006629void InputDispatcher::onWindowInfosChanged(const std::vector<WindowInfo>& windowInfos,
6630 const std::vector<DisplayInfo>& displayInfos) {
chaviw15fab6f2021-06-07 14:15:52 -05006631 // The listener sends the windows as a flattened array. Separate the windows by display for
6632 // more convenient parsing.
6633 std::unordered_map<int32_t, std::vector<sp<WindowInfoHandle>>> handlesPerDisplay;
chaviw15fab6f2021-06-07 14:15:52 -05006634 for (const auto& info : windowInfos) {
6635 handlesPerDisplay.emplace(info.displayId, std::vector<sp<WindowInfoHandle>>());
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07006636 handlesPerDisplay[info.displayId].push_back(sp<WindowInfoHandle>::make(info));
chaviw15fab6f2021-06-07 14:15:52 -05006637 }
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006638
6639 { // acquire lock
6640 std::scoped_lock _l(mLock);
Prabir Pradhan814fe082022-07-22 20:22:18 +00006641
6642 // Ensure that we have an entry created for all existing displays so that if a displayId has
6643 // no windows, we can tell that the windows were removed from the display.
6644 for (const auto& [displayId, _] : mWindowHandlesByDisplay) {
6645 handlesPerDisplay[displayId];
6646 }
6647
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006648 mDisplayInfos.clear();
6649 for (const auto& displayInfo : displayInfos) {
6650 mDisplayInfos.emplace(displayInfo.displayId, displayInfo);
6651 }
6652
6653 for (const auto& [displayId, handles] : handlesPerDisplay) {
6654 setInputWindowsLocked(handles, displayId);
6655 }
6656 }
6657 // Wake up poll loop since it may need to make new input dispatching choices.
6658 mLooper->wake();
chaviw15fab6f2021-06-07 14:15:52 -05006659}
6660
Vishnu Nair062a8672021-09-03 16:07:44 -07006661bool InputDispatcher::shouldDropInput(
6662 const EventEntry& entry, const sp<android::gui::WindowInfoHandle>& windowHandle) const {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006663 if (windowHandle->getInfo()->inputConfig.test(WindowInfo::InputConfig::DROP_INPUT) ||
6664 (windowHandle->getInfo()->inputConfig.test(
6665 WindowInfo::InputConfig::DROP_INPUT_IF_OBSCURED) &&
Vishnu Nair062a8672021-09-03 16:07:44 -07006666 isWindowObscuredLocked(windowHandle))) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006667 ALOGW("Dropping %s event targeting %s as requested by the input configuration {%s} on "
6668 "display %" PRId32 ".",
Vishnu Nair062a8672021-09-03 16:07:44 -07006669 ftl::enum_string(entry.type).c_str(), windowHandle->getName().c_str(),
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006670 windowHandle->getInfo()->inputConfig.string().c_str(),
Vishnu Nair062a8672021-09-03 16:07:44 -07006671 windowHandle->getInfo()->displayId);
6672 return true;
6673 }
6674 return false;
6675}
6676
Siarhei Vishniakou18050092021-09-01 13:32:49 -07006677void InputDispatcher::DispatcherWindowListener::onWindowInfosChanged(
6678 const std::vector<gui::WindowInfo>& windowInfos,
6679 const std::vector<DisplayInfo>& displayInfos) {
6680 mDispatcher.onWindowInfosChanged(windowInfos, displayInfos);
6681}
6682
Arthur Hungdfd528e2021-12-08 13:23:04 +00006683void InputDispatcher::cancelCurrentTouch() {
6684 {
6685 std::scoped_lock _l(mLock);
6686 ALOGD("Canceling all ongoing pointer gestures on all displays.");
Michael Wrightfb04fd52022-11-24 22:31:11 +00006687 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
Arthur Hungdfd528e2021-12-08 13:23:04 +00006688 "cancel current touch");
6689 synthesizeCancelationEventsForAllConnectionsLocked(options);
6690
6691 mTouchStatesByDisplay.clear();
Arthur Hungdfd528e2021-12-08 13:23:04 +00006692 }
6693 // Wake up poll loop since there might be work to do.
6694 mLooper->wake();
6695}
6696
Prabir Pradhan87112a72023-04-20 19:13:39 +00006697void InputDispatcher::requestRefreshConfiguration() {
Prabir Pradhana41d2442023-04-20 21:30:40 +00006698 InputDispatcherConfiguration config = mPolicy.getDispatcherConfiguration();
Prabir Pradhan87112a72023-04-20 19:13:39 +00006699
6700 std::scoped_lock _l(mLock);
6701 mConfig = config;
6702}
6703
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006704void InputDispatcher::setMonitorDispatchingTimeoutForTest(std::chrono::nanoseconds timeout) {
6705 std::scoped_lock _l(mLock);
6706 mMonitorDispatchingTimeout = timeout;
6707}
6708
Arthur Hungc539dbb2022-12-08 07:45:36 +00006709void InputDispatcher::slipWallpaperTouch(ftl::Flags<InputTarget::Flags> targetFlags,
6710 const sp<WindowInfoHandle>& oldWindowHandle,
6711 const sp<WindowInfoHandle>& newWindowHandle,
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08006712 TouchState& state, int32_t pointerId,
Siarhei Vishniakoubf880522023-05-01 11:03:22 -07006713 std::vector<InputTarget>& targets) const {
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08006714 std::bitset<MAX_POINTER_ID + 1> pointerIds;
6715 pointerIds.set(pointerId);
Arthur Hungc539dbb2022-12-08 07:45:36 +00006716 const bool oldHasWallpaper = oldWindowHandle->getInfo()->inputConfig.test(
6717 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
6718 const bool newHasWallpaper = targetFlags.test(InputTarget::Flags::FOREGROUND) &&
6719 newWindowHandle->getInfo()->inputConfig.test(
6720 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
6721 const sp<WindowInfoHandle> oldWallpaper =
6722 oldHasWallpaper ? state.getWallpaperWindow() : nullptr;
6723 const sp<WindowInfoHandle> newWallpaper =
6724 newHasWallpaper ? findWallpaperWindowBelow(newWindowHandle) : nullptr;
6725 if (oldWallpaper == newWallpaper) {
6726 return;
6727 }
6728
6729 if (oldWallpaper != nullptr) {
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08006730 const TouchedWindow& oldTouchedWindow = state.getTouchedWindow(oldWallpaper);
6731 addWindowTargetLocked(oldWallpaper,
6732 oldTouchedWindow.targetFlags |
6733 InputTarget::Flags::DISPATCH_AS_SLIPPERY_EXIT,
6734 pointerIds, oldTouchedWindow.firstDownTimeInTarget, targets);
6735 state.removeTouchedPointerFromWindow(pointerId, oldWallpaper);
Arthur Hungc539dbb2022-12-08 07:45:36 +00006736 }
6737
6738 if (newWallpaper != nullptr) {
6739 state.addOrUpdateWindow(newWallpaper,
6740 InputTarget::Flags::DISPATCH_AS_SLIPPERY_ENTER |
6741 InputTarget::Flags::WINDOW_IS_OBSCURED |
6742 InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED,
6743 pointerIds);
6744 }
6745}
6746
6747void InputDispatcher::transferWallpaperTouch(ftl::Flags<InputTarget::Flags> oldTargetFlags,
6748 ftl::Flags<InputTarget::Flags> newTargetFlags,
6749 const sp<WindowInfoHandle> fromWindowHandle,
6750 const sp<WindowInfoHandle> toWindowHandle,
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08006751 TouchState& state,
6752 std::bitset<MAX_POINTER_ID + 1> pointerIds) {
Arthur Hungc539dbb2022-12-08 07:45:36 +00006753 const bool oldHasWallpaper = oldTargetFlags.test(InputTarget::Flags::FOREGROUND) &&
6754 fromWindowHandle->getInfo()->inputConfig.test(
6755 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
6756 const bool newHasWallpaper = newTargetFlags.test(InputTarget::Flags::FOREGROUND) &&
6757 toWindowHandle->getInfo()->inputConfig.test(
6758 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
6759
6760 const sp<WindowInfoHandle> oldWallpaper =
6761 oldHasWallpaper ? state.getWallpaperWindow() : nullptr;
6762 const sp<WindowInfoHandle> newWallpaper =
6763 newHasWallpaper ? findWallpaperWindowBelow(toWindowHandle) : nullptr;
6764 if (oldWallpaper == newWallpaper) {
6765 return;
6766 }
6767
6768 if (oldWallpaper != nullptr) {
6769 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
6770 "transferring touch focus to another window");
6771 state.removeWindowByToken(oldWallpaper->getToken());
6772 synthesizeCancelationEventsForWindowLocked(oldWallpaper, options);
6773 }
6774
6775 if (newWallpaper != nullptr) {
6776 nsecs_t downTimeInTarget = now();
6777 ftl::Flags<InputTarget::Flags> wallpaperFlags =
6778 oldTargetFlags & (InputTarget::Flags::SPLIT | InputTarget::Flags::DISPATCH_AS_IS);
6779 wallpaperFlags |= InputTarget::Flags::WINDOW_IS_OBSCURED |
6780 InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED;
6781 state.addOrUpdateWindow(newWallpaper, wallpaperFlags, pointerIds, downTimeInTarget);
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006782 std::shared_ptr<Connection> wallpaperConnection =
6783 getConnectionLocked(newWallpaper->getToken());
Arthur Hungc539dbb2022-12-08 07:45:36 +00006784 if (wallpaperConnection != nullptr) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006785 std::shared_ptr<Connection> toConnection =
6786 getConnectionLocked(toWindowHandle->getToken());
Arthur Hungc539dbb2022-12-08 07:45:36 +00006787 toConnection->inputState.mergePointerStateTo(wallpaperConnection->inputState);
6788 synthesizePointerDownEventsForConnectionLocked(downTimeInTarget, wallpaperConnection,
6789 wallpaperFlags);
6790 }
6791 }
6792}
6793
6794sp<WindowInfoHandle> InputDispatcher::findWallpaperWindowBelow(
6795 const sp<WindowInfoHandle>& windowHandle) const {
6796 const std::vector<sp<WindowInfoHandle>>& windowHandles =
6797 getWindowHandlesLocked(windowHandle->getInfo()->displayId);
6798 bool foundWindow = false;
6799 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
6800 if (!foundWindow && otherHandle != windowHandle) {
6801 continue;
6802 }
6803 if (windowHandle == otherHandle) {
6804 foundWindow = true;
6805 continue;
6806 }
6807
6808 if (otherHandle->getInfo()->inputConfig.test(WindowInfo::InputConfig::IS_WALLPAPER)) {
6809 return otherHandle;
6810 }
6811 }
6812 return nullptr;
6813}
6814
Garfield Tane84e6f92019-08-29 17:28:41 -07006815} // namespace android::inputdispatcher